| |
|
| PHP
1. GENERAL SYNTAX | introducting | Php Code is opened with "<?" and closed with "?>". |
| statements | Php 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 sensitive | Php is case sensitive regarding variable names, function names, etc. |
| like javascript | The 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. |
| include | Include external php files. If they are not in the same folder, you may want to
use realpath – see "FILES" section. include("fileName.php"); |
| by reference | Generally, 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 parameters | You 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 | declaration | In general, php variables are not declared. Just start using them. |
| syntax | Variables are preceded by the "$" character (unlike Perl, where for arrays you use '@'). |
| constants | The syntax for defining constants is: define("MAXSIZE", "10pt");. Usage would then be
by reference to MAXSIZE. |
| scope | In general, a variable declared inside a function is accessible only inside the function. A
variable declared globally, outside the functions, is inaccessible inside functions. |
| $GLOBALS | If you do need to access inside a function a variable that was declared globally, then do so
thus: $GLOBALS["globalVarName"]). |
| isset | Check whether a Variable has been set. isset($myVar) |
3. STRINGS | one character | To access the nth character of your string, use '[]'. (This works
because a string is internally stored as an array.) $myString[7] |
| splitting strings | In 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"; |
| variables | A 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 \. |
| <<< EOS | A 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 |
| strlen | Return length of string. strlen($myString) |
| ucfirst | Capitalize first character of string (no parallel lcfirst). ucfirst($myString) |
| strtoupper | Convert string to uppercase strtoupper($myString) |
| strtolower | Convert string to uppercase strtolower($myString) |
| substr | Return specified substring. substr($myString, $from[, $len]) |
| strpos | Return position of first occurrence of needle within haystack. Return false if not found. strpos($haystack, $needle) |
| chr | Return the character with the specified ASCII. chr(33) |
| ord | Return the ASCII value of the first character of a string. ord("hello") |
| addslashes | Return string with backslashes inserted before appropriate characters for database
inquiries (single-quote, double-quote, backslash, null). addslashes($myString) |
| stripslashes | Return 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) |
| print | Print string to the screen. print($myString) |
| printf | Output 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") |
| echo | Print string to the screen. Same as print. echo($myString) |
| str_replace | Return the string with the specified replacement. Preferred function if no fancy
pattern matching needed. str_replace("Andy", "Andrew", $letter) |
| preg_replace | Same as str_replace, with fancy pattern matching preg_replace("/^ /", "", $text) |
| str_ireplace | Case-insensitive version of str_replace – available as of version 5. |
| preg_match | Perform a regular expression search within a string for a specified pattern. Return 0 or 1. preg_match("/^[0-9]/", $myString) |
| preg_quote | Puts 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_repeat | Repeat a string a specified number of times. str_repeat("--", 8) |
4. ARRAYS | declaration | Note that the 'a' of the word 'array' can apparently be uppercase or lowercase. $myArray = array("apple", "orange") |
| associative arrays | Arrays 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 list | To 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)) |
| element | Access the fourth element of an array thus: $myArray[3] |
| length | The count and sizeof functions both return an array's length. sizeof($myArray) |
| array_push | Push 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_pop | Pop and return the last element off the end of an array. $lastElement = array_pop($myArray) |
| array_unshift | Push list of new elements onto the beginning of an array. array_unshift($myArray, $newItem1, $newItem2) |
| array_shift | Shift off and return the first element off the end of an array. $firstElement = array_shift($myArray) |
| array_merge | Merge arrays together. $combinedArray = array_merge($array1, $array2) |
| explode | Explode a string by a given substring into an array. Apparently, equivalent to split. explode(":", $myString) |
| in_array | See if given value is one of the elements of an array. Return 0 or 1 in_array($needle_string, $haystack_array) |
| str_split | Split 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_split | Similar 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) |
| implode | Join an array into string with the specified 'glue'. $myString = implode(".", $myArray) |
| foreach | Use 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"; } |
| sort | Sort an array. Array itself is sorted $ary = Array("the", "good", "dog");
sort($ary); |
5. GENERAL MISC | exit | Halt program execution. exit(); |
| redirect | Redirect 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") |
| sessions | Cookied-based sessions that you can use to store info on one page and access it on another. $_SESSION["userName"] = "John" |
| session_start | This function must be called before any html output on any page where you use sessions. session_start() |
| setcookie | Send 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, "/"); |
| md5 | Calculate the md5 hash of a string -- useful for encrypting data. md5($myString); |
| character set | You can use this to set the charset of the document header("Content-type: text/html; charset=utf-8"); |
| mail | Send 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_r | Print human-readable information about a variable. Especially useful for arrays, within the 'pre' html tag. print_r($myArray); |
6. FORMS | case sensitive | Php is case sensitive regarding names of elements passed by a form. |
| input value – get | Get value of a variable when form was passed by method get. Works for almost
all input types. $_GET["myInput"] |
| input value – post | Same as above – for method post. $_POST["myInput"] |
| post or get | Check whether info has been passed by method post or get. $_SERVER["REQUEST_METHOD"] |
| number of elements | Return 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") |
| checkboxes | If checked, then $_POST or $_GET will return 'on'. If not, an error message will be generated!
Solution: use 'isset': if (isset($_POST["myCheckbox"])) |
| radios | Similar 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 file | You 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 elements | An 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 database | The 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_query | Execute mysql command. mysql_query("INSERT INTO people (name) VALUES ('John Smith')") |
| mysql_affected_rows | Return number of affected rows in previous MySQL INSERT, UPDATE, REPLACE or DELETE operation. |
| mysql_num_fields | Retrieve the number of fields from a result set. $rs = mysql_query("SELECT * FROM city");
$nFields = mysql_num_fields($rs); |
| mysql_field_name | Returns the name of the specified field index. $rs = mysql_query("SELECT * from city");
echo mysql_field_name($rs, 0); |
| mysql_num_rows | Retrieve the number of rows from a result set. $rs = mysql_query("SELECT * FROM city");
$nRows = mysql_num_rows($rs); |
| mysql_error | Returns the text of the error message from previous MySQL operation. |
| retrieve records | Use 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_close | Close mysql connection. If no parameter specified, close last link opened. mysql_close([$li]) |
| addslashes | Add backslash before characters like single quote and double quote so that mysql commands will work smoothly. addslahes($_POST[myField]) |
8. FILES | General Note | It 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". |
| realpath | Return absolute path. This function will often be used in conjunction with all of the
other file functions. realpath($myFile) |
| file_exists | Check whether or not file/folder exists. Returns true or false. file_exists($myFile) |
| filesize | Return size of file. filesize($myFile) |
| filemtime | Return, 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) |
| basename | Take a long URL, and return just the base filename. $fileName = basename($URL) |
| fopen | Open 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") |
| fread | Read specified number of bytes from open file. $contents = fread($fp, $nChars) |
| fgets | Read and return one line from a file. Newline character is included in return value. while (!feof($fp)) {
$buffer = fgets($fp);
echo $buffer;
} |
| fwrite | Write to open file. fwrite($fp, $myContent); |
| fclose | Close a file. fclose($fp); |
| chmod | Change 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) |
| copy | Copy file. copy($fromFileName, $toFileName) |
| unlink | Delete file. unlink($fileName) |
| mkdir | Create directory. mkdir($dirName[, $mode]) |
| is_dir | Is file a directory? is_dir($fileName) |
| opendir | Open directory for subsequent function calls $dirHandle = opendir($dirName) |
| readdir | Return file name of next file in directory $fileName = readdir($dirHandle) |
9. MATH | round | Round a float to the nearest whole number – optionally, to the specified number of
decimal places. round($n[, $precision]) |
| ceil | Round a float up to the nearest whole number. ceil($n) |
| floor | Round a float down to the nearest whole number. floor($n) |
| max | Return the highest of a list of values. max($n1, $n2[,...]) |
| min | Return the lowest of a list of values. min($n1, $n2[,...]) |
| abs | Return number's absolute value. abs($n) |
| pow | Return a number raised to the specified power. pow($n, $exp) |
| rand | Return 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 name | Host address of current script. On this page, would return
"www.finewebsites.net" $_SERVER["SERVER_NAME"] |
| Full script URL | Return full URL of current script. For this page, would return "http://www.finewebsites.net/documentation/php.php" $_SERVER["SCRIPT_URI"] |
| Full script name | Return 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 root | Return 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 pathname | Return absolute pathname of the current script. For this page, would return "/var/www/html/documentation/php.php" $_SERVER["SCRIPT_FILENAME"] |
| referring URL | Full URL, starting from "http", of page from which the user came to current script. $_SERVER["HTTP_REFERER"] |
| ip address | Return end-user's IP address. $_SERVER["REMOTE_ADDR"] |
| date/time | Return 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") |
| mktime | Return current date/time, as UNIX timestamp – seconds since 01/01/1970. $myNow = mktime() |
| ip address | Return end-user's IP address. $_SERVER["REMOTE_ADDR"] |
| browser info | Return 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 info | Function 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 | imagecreatefromjpeg | Create an image object from a file or URL. The corresponding functions are imagecreatefrompng and imagecreatefromgif. $myImage = imagecreatefromjpeg("http://www.mySite.com/myImage.jpg") |
| imagesx | Obtain the width of an image object. imagesx($myImage) |
| imagesy | Obtain the height of an image object. imagesy($myImage) |
| imagecreatetruecolor | Create a new black image of the specified width and height $myImage = imagecreatefromjpeg($myWidth, $myHeight) |
| imagecopyresampled | Copy (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) |
| imagejpeg | Create 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") |
| imagedestroy | Destory 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
|
|