HTML Tags
Character Charts
W3C Compliancy
CSS
Regular Expressions
Useful Tools
PHP
1. GENERAL SYNTAX
introductingPhp Code is opened with "<?" and closed with "?>".
 
statementsPhp statements are to be followed with the ";" character. (Actually, there is an exception: if there is no ambiguity, such as where there is a single statement within the php opening and closing tags, then the semi-colon is not required.)
 
case sensitivePhp is case sensitive regarding variable names, function names, etc.
 
like javascriptThe following syntax items are coded as in javascript: 1. If. 2. For. 3. While. 4. Switch. 5. Function calls. 6. Operators: ==, +=, ++, ternary, etc. 7. Comments.
 
includeInclude external php files. If they are not in the same folder, you may want to use realpath – see "FILES" section.
include("fileName.php");
 
by referenceGenerally, variables passed to functions are passed by value. In order to change variables passed to functions, you must specify in the function definition that the parameter in question is to be passed by refence.
function myFunc (&$param) {
$param++;
}
 
optional parametersYou can declare a function with optional parameters. In this example, the parameter $id is optional. If it is not passed, it will be set to -1.
function myFunc ($id = -1) {
 
2. VARIABLES
declarationIn general, php variables are not declared. Just start using them.
 
syntaxVariables are preceded by the "$" character (unlike Perl, where for arrays you use '@').
 
constantsThe syntax for defining constants is: define("MAXSIZE", "10pt");. Usage would then be by reference to MAXSIZE.
 
scopeIn general, a variable declared inside a function is accessible only inside the function. A variable declared globally, outside the functions, is inaccessible inside functions.
 
$GLOBALSIf you do need to access inside a function a variable that was declared globally, then do so thus: $GLOBALS["globalVarName"]).
 
issetCheck whether a Variable has been set.
isset($myVar)
 
3. STRINGS
one characterTo access the nth character of your string, use '[]'. (This works because a string is internally stored as an array.)
$myString[7]
 
splitting stringsIn php, you can open a string literal on one line and close it on a later line.
$myString = "this is 1st line
this is 2nd line
this is 3rd line";
 
variablesA variable inside a string delimited by double-quotes will be evaluated. Inside single quotes, it will not be. Items such as $GLOBALS["myString"] will not be evaluated. If you want the '$' character inside a double-quoted string, escape it with \.
 
<<< EOSA nice feature for embedding both double-quotes and variables to be evaluated inside strings is to use <<< EOS. Any text from this opening to the closing will be taken as the string. The closing line must be "EOS;" – with nothing on the line before the EOS. ('EOS' is not a keyword – you can use anything instead.) This feature may be used in any string context.
$myString = <<< EOS
Here is a paragraph of text
which will be assigned to the string
by $myName
EOS;
 
.Operator to concatenate strings together.
EXPR1 . EXPR2
 
strlenReturn length of string.
strlen($myString)
 
ucfirstCapitalize first character of string (no parallel lcfirst).
ucfirst($myString)
 
strtoupperConvert string to uppercase
strtoupper($myString)
 
strtolowerConvert string to uppercase
strtolower($myString)
 
substrReturn specified substring.
substr($myString, $from[, $len])
 
strposReturn position of first occurrence of needle within haystack. Return false if not found.
strpos($haystack, $needle)
 
chrReturn the character with the specified ASCII.
chr(33)
 
ordReturn the ASCII value of the first character of a string.
ord("hello")
 
addslashesReturn string with backslashes inserted before appropriate characters for database inquiries (single-quote, double-quote, backslash, null).
addslashes($myString)
 
stripslashesReturn strings with backslashes removed. Useful because php usually automatically inserts slashes before characters like single-quote in contexts like get and post. While this is good for inserting those strings in the database, in other contexts they are unwanted.
stripslashes($myString)
 
printPrint string to the screen.
print($myString)
 
printfOutput a formatted string. The example shows how to indicate two decimal places. There are many different format specifications. Related functions: sprintf, fprintf.
printf("%.2f", "333.33")
 
echoPrint string to the screen. Same as print.
echo($myString)
 
str_replaceReturn the string with the specified replacement. Preferred function if no fancy pattern matching needed.
str_replace("Andy", "Andrew", $letter)
 
preg_replaceSame as str_replace, with fancy pattern matching
preg_replace("/^ /", "", $text)
 
str_ireplaceCase-insensitive version of str_replace – available as of version 5.
 
preg_matchPerform a regular expression search within a string for a specified pattern. Return 0 or 1.
preg_match("/^[0-9]/", $myString)
 
preg_quotePuts a backslash in front of every character that is part of the regular expression syntax. Useful for excaping these characters in a run-time string that you need to match. The special characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | :
$embedded = preg_quote($myString)
 
str_repeatRepeat a string a specified number of times.
str_repeat("--", 8)
 
4. ARRAYS
declarationNote that the 'a' of the word 'array' can apparently be uppercase or lowercase.
$myArray = array("apple", "orange")
 
associative arraysArrays where, instead of using 0, 1, 2, etc. as indices, you use whatever string you want as the indices.
$myArray = Array("Simon" => "Jerusalem", "Valerie" => "Hong Kong", "Gerald" => "Paris")
 
pass listTo pass a list of items as a parameter to a function, you need not declare an array. You can simply use 'Array'
funcCall($arg1, Array($var1, $var2))
 
elementAccess the fourth element of an array thus:
$myArray[3]
 
lengthThe count and sizeof functions both return an array's length.
sizeof($myArray)
 
array_pushPush list of new elements onto the end of an array. Note that if one of the new elements is an array, then the whole array together will be one new element.
array_push($myArray, $newItem1, $newItem2)
 
array_popPop and return the last element off the end of an array.
$lastElement = array_pop($myArray)
 
array_unshiftPush list of new elements onto the beginning of an array.
array_unshift($myArray, $newItem1, $newItem2)
 
array_shiftShift off and return the first element off the end of an array.
$firstElement = array_shift($myArray)
 
array_mergeMerge arrays together.
$combinedArray = array_merge($array1, $array2)
 
explodeExplode a string by a given substring into an array. Apparently, equivalent to split.
explode(":", $myString)
 
in_arraySee if given value is one of the elements of an array. Return 0 or 1
in_array($needle_string, $haystack_array)
 
str_splitSplit a string into an array of fixed-sized strings, each of length specified by second parameter. Warning: may not exist in certain PHP versions!
str_split($myString, 4)
 
preg_splitSimilar to explode – but allows pattern-matching. Useful for example when you want to split a string into an array of its component characters. Third and fourth parameters optional: third: maximum number of substrings – use -1 for no limit; fourth: flag – use PREG_SPLIT_NO_EMPTY if you only want results that are not the nullstring.
preg_split("/[a-z]/", $myString, -1, PREG_SPLIT_NO_EMPTY)
 
implodeJoin an array into string with the specified 'glue'.
$myString = implode(".", $myArray)
 
foreachUse this to loop down an array. Can be used with associative arrays
foreach ($myArray as $currentElement) {
echo $currentElement;
}
foreach ($myAssociativeArray as $key => $value) {
echo "$key: $value";
}
 
sortSort an array. Array itself is sorted
$ary = Array("the", "good", "dog");
sort($ary);
 
5. GENERAL MISC
exitHalt program execution.
exit();
 
redirectRedirect browser to a different URL. This function cannot be called once you have already begun to send actual html code to the screen.
header("location:thanks.html")
 
sessionsCookied-based sessions that you can use to store info on one page and access it on another.
$_SESSION["userName"] = "John"
 
session_startThis function must be called before any html output on any page where you use sessions.
session_start()
 
setcookieSend a cookie. Like other headers, cookies must be sent before any output from script. Fourth parameter: path on the server in which the cookie will be available. If "/", then available within entire domain.
setcookie("username", "johnsmith", 3600*24*100, "/");
 
md5Calculate the md5 hash of a string -- useful for encrypting data.
md5($myString);
 
character setYou can use this to set the charset of the document
header("Content-type: text/html; charset=utf-8");
 
mailSend server-side mail. Notes:
Subject: 1. Can be comma-separated list. 2. Each 'to' can be in the format 'name <address>'.
Body: 1. Each line should be separated with '\n'. 2. Lines should not contain > 70 chars.
Additional Headers: 1. Can be used to send other info. 2. Each header should have the form header-title, then ":", then the value of that header-title, such as "from:me@mail.com". 3. If there is more than one additional header, they should be separated by "\r\n". Here are some things you can pass with additional headers: from, cc, bcc. For html mail, do this:
$headers = "MIME-Version: 1.0 ";
$headers .= "Content-type: text/html; charset=iso-8859-1 ";
mail($to, $subject, $body, $headers)
 
print_rPrint human-readable information about a variable. Especially useful for arrays, within the 'pre' html tag.
print_r($myArray);
 
6. FORMS
case sensitivePhp is case sensitive regarding names of elements passed by a form.
 
input value – getGet value of a variable when form was passed by method get. Works for almost all input types.
$_GET["myInput"]
 
input value – postSame as above – for method post.
$_POST["myInput"]
 
post or getCheck whether info has been passed by method post or get.
$_SERVER["REQUEST_METHOD"]
 
number of elementsReturn number of elements passed by form – use whichever is appropriate. Note that unchecked radios and checkboxes will not figure in this or in the next item!
sizeof($_POST)
sizeof($_GET)
 
form submitted?If you have the code to produce the form and process it on the same page, and need to know which of the two stages the end-user is at, then, depending on the context, you can use these. The assumption is that the necessary items are always defined and that the default method is get.
if (sizeof($_POST) > 0)
if ($_SERVER["REQUEST_METHOD"] == "POST")
 
checkboxesIf checked, then $_POST or $_GET will return 'on'. If not, an error message will be generated! Solution: use 'isset':
if (isset($_POST["myCheckbox"]))
 
radiosSimilar problem to checkboxes. Solution: again, use 'isset' – and give each radio a different value, so you can then check the value and thus see which one was checked.
 
uploading fileYou will need to use $_FILES array and the file functions realpath, move_uploaded_files and chmod. $_FILES is a useful 2D array, where first element is the name of the uploaded file and the second element can be 'tmpname' for the temporary name of the uploaded file; 'name' for the actual name of the file; as well as 'size' and 'type'.
$fileName = $_FILES["myFile"]["name"];
if ($fileName != "") {
$newName = realpath($myFolder) . $fileName;
move_uploaded_file($_FILES["myFile"]["tmp_name"], $newName);
chmod($newName, 0644);
}
 
loop down elementsAn alternative to checking each element individually by name. Interestingly, even this method will not work if elements are not given a name on the form. Works for get or post.
foreach ($_GET as $currentItem)
echo $currentItem
 
7. MYSQL
Open databaseThe following block of code would open a database. What would change from project to project would be $dbuser, $dbPass and $dbDatabase.
$dbHost = "localhost.localdomain";
$dbUser = "yisrael";
$dbPass = "hellothere";
$dbDatabase = "mysite_com_-_db";
$li = mysql_connect($dbHost, $dbUser, $dbPass) or die("Could not connect");
mysql_select_db($dbDatabase, $li) or die ("could not select DB");
 
mysql_queryExecute mysql command.
mysql_query("INSERT INTO people (name) VALUES ('John Smith')")
 
mysql_affected_rowsReturn number of affected rows in previous MySQL INSERT, UPDATE, REPLACE or DELETE operation.
 
mysql_num_fieldsRetrieve the number of fields from a result set.
$rs = mysql_query("SELECT * FROM city");
$nFields = mysql_num_fields($rs);
 
mysql_field_nameReturns the name of the specified field index.
$rs = mysql_query("SELECT * from city");
echo mysql_field_name($rs, 0);
 
mysql_num_rowsRetrieve the number of rows from a result set.
$rs = mysql_query("SELECT * FROM city");
$nRows = mysql_num_rows($rs);
 
mysql_errorReturns the text of the error message from previous MySQL operation.
 
retrieve recordsUse mysql_query and mysql_fetch_array. Then, access desired field. Note that $get_row[0] would be equivalent to $get_row["firstName"]
$rs = mysql_query("SELECT firstName, lastName FROM myTable");
while ($get_row = mysql_fetch_array($rs))
echo $get_row["firstName"];
 
mysql_closeClose mysql connection. If no parameter specified, close last link opened.
mysql_close([$li])
 
addslashesAdd backslash before characters like single quote and double quote so that mysql commands will work smoothly.
addslahes($_POST[myField])
 
8. FILES
General NoteIt is important to note the distinction between the root folder Server-side and Client-side. For example, if the root folder on the Server where webpage files are stored is "/var/www/html", then in your php code, that would be the root folder. So if a file "index.php" resides in that folder, then server-side, it would be referred to as "/var/www/html/index.php", while client-side, it would be referred to as "/index.php".
 
realpathReturn absolute path. This function will often be used in conjunction with all of the other file functions.
realpath($myFile)
 
file_existsCheck whether or not file/folder exists. Returns true or false.
file_exists($myFile)
 
filesizeReturn size of file.
filesize($myFile)
 
filemtimeReturn, as UNIX timestamp – seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) – time of file modification. Similar functions: fileatime (access), filectime (creation).
filemtime($myFile)
 
basenameTake a long URL, and return just the base filename.
$fileName = basename($URL)
 
fopenOpen a file. Modes: "r", "w", "a", and others. Return a file pointer. The file pointer will be used for subsquent operations on the open file.
$fp = fopen($myFile, "r")
 
freadRead specified number of bytes from open file.
$contents = fread($fp, $nChars)
 
fgetsRead and return one line from a file. Newline character is included in return value.
while (!feof($fp)) {
$buffer = fgets($fp);
echo $buffer;
}
 
fwriteWrite to open file.
fwrite($fp, $myContent);
 
fcloseClose a file.
fclose($fp);
 
chmodChange mode of file. Mode is '0' followed by three digits, for each of owner, owner's group and everybody else. 1: execute. 2: write. 4: read. Add to combine, thus 6 is read + write. Examples of modes:
0600: Read and write for owner, nothing for everybody else.
0644: Read and write for owner, read for everybody else.
0755: Everything for owner, read and execute for others.
0750: Everything for owner, read and execute for owner's group.
chmod($myFile, $mode)
 
copyCopy file.
copy($fromFileName, $toFileName)
 
unlinkDelete file.
unlink($fileName)
 
mkdirCreate directory.
mkdir($dirName[, $mode])
 
is_dirIs file a directory?
is_dir($fileName)
 
opendirOpen directory for subsequent function calls
$dirHandle = opendir($dirName)
 
readdirReturn file name of next file in directory
$fileName = readdir($dirHandle)
 
9. MATH
roundRound a float to the nearest whole number – optionally, to the specified number of decimal places.
round($n[, $precision])
 
ceilRound a float up to the nearest whole number.
ceil($n)
 
floorRound a float down to the nearest whole number.
floor($n)
 
maxReturn the highest of a list of values.
max($n1, $n2[,...])
 
minReturn the lowest of a list of values.
min($n1, $n2[,...])
 
absReturn number's absolute value.
abs($n)
 
powReturn a number raised to the specified power.
pow($n, $exp)
 
randReturn a random number from the specified range – including the two parameters passed. The function which seeds the random number generator (srand) does not need to be called.
rand($from, $to)
 
%Return a modulus b.
a % b
 
10. GET MISC INFO
host nameHost address of current script. On this page, would return "www.finewebsites.net"
$_SERVER["SERVER_NAME"]
 
Full script URLReturn full URL of current script. For this page, would return "http://www.finewebsites.net/documentation/php.php"
$_SERVER["SCRIPT_URI"]
 
Full script nameReturn full name of current script, relative to document root. On this page, would return "/documentation/php.php". Three ways of doing it:
$_SERVER["PHP_SELF"]
$_SERVER["REQUEST_URI"]
$_SERVER["SCRIPT_NAME"]
 
document rootReturn root directory under which current script is executing, as defined in the server's configuration file. For this page, would return "/var/www/html"
$_SERVER["DOCUMENT_ROOT"]
 
absolute pathnameReturn absolute pathname of the current script. For this page, would return "/var/www/html/documentation/php.php"
$_SERVER["SCRIPT_FILENAME"]
 
referring URLFull URL, starting from "http", of page from which the user came to current script.
$_SERVER["HTTP_REFERER"]
 
ip addressReturn end-user's IP address.
$_SERVER["REMOTE_ADDR"]
 
date/timeReturn current date/time, according to specified format. The following just returned Sunday July 3, 2005 16:12:54:
date("l F j, Y G:i:s")
 
mktimeReturn current date/time, as UNIX timestamp – seconds since 01/01/1970.
$myNow = mktime()
 
ip addressReturn end-user's IP address.
$_SERVER["REMOTE_ADDR"]
 
browser infoReturn browser and other info about end-user's system. If it is MSIE, it will contain the string "MSIE". For Firefox, it will contain the string "Firefox".
$_SERVER["HTTP_USER_AGENT"]
 
full infoFunction which returns a ton of info about the server – most of which I personally do not understand! For full results, call with no arguments. This function returns a full html page, so simply create a php script that contains nothing but the following call:
phpinfo();
 
11. IMAGES
imagecreatefromjpegCreate an image object from a file or URL. The corresponding functions are imagecreatefrompng and imagecreatefromgif.
$myImage = imagecreatefromjpeg("http://www.mySite.com/myImage.jpg")
 
imagesxObtain the width of an image object.
imagesx($myImage)
 
imagesyObtain the height of an image object.
imagesy($myImage)
 
imagecreatetruecolorCreate a new black image of the specified width and height
$myImage = imagecreatefromjpeg($myWidth, $myHeight)
 
imagecopyresampledCopy (part of) one image object to another. If copying entire image, use 0 for the 4 x/y parameters.
imagecopyresampled($myImage2, $myImage1, $image2X, $image2Y, $image1X, $image1Y, $image2Width, $image2Height, $image1Width, $image1Height)
 
imagejpegCreate an image file from an image object. If second parameter omitted, prints the image to the screen. Be sure to use appropriate Content-type. Corresponding functions are imagepng and imagegif.
imagejpeg($myImage, "/var/www/html/pics/newImage.png")
 
imagedestroyDestory image object when done using it. Important to free memory resources.
imagedestroy($myImage)
 
 
References:
 
http://www.php.net/manual/en/
 
http://www.php.net/manual/en/funcref.php
 
 
 
 
Check this page for W3C Compliancy
 
Top of Page