CAUTION: this page is a collection of notes and not verified reference material — rely on it at your own risk! | |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Arrays | |
| $primes = array(2, 3, 5, 7, 11, 13); echo $primes[0]; |
Creates an array of prime numbers and returns 2 (the first element in the array) |
| $days = array('yesterday', 'today', 'tomorrow'); | Creates an array of string values |
| $sudoku = array(array(9, 8, 5), array(2, 7, 3), array(1, 6, 4)); echo $sudoku[1][0]; |
Creates a two-dimensional array (an array of arrays) and returns 2 (the first element in the second array) |
| $example[0] = "one"; $example[1] = "two"; $example[2] = "three"; $example[] = "one"; $example[] = "two"; $example[] = "three"; |
These two sets of statements have identical results since arrays can be populated without specifying an index and the elements will be indexed automatically as they are created |
| $prime_numbers = count($primes); $rows = count($sudoku, 0); $block = count($sudoku, 1); |
The count() function returns the number of elements in an array with an optional second argument to specific top-level-only (0) or all elements and sub-elements (1) |
| $prices = array('12.95', '3.50', '29.99', '77', '7'); sort($prices); rsort($prices); |
This will re-arrange the elements in the array so that they are in order (default sort order is alphabetical or numeric depending on content) rsort() does the same thing but in reverse order [note: sort() modifies the original array and returns true, so to create a new array as a sorted version of the original you need to clone the array and sort the clone] |
| $prices = array('12.95', '3.50', '29.99', '77', '7'); sort($prices, SORT_NUMERIC); rsort($prices, SORT_NUMERIC); |
Option second argument forces the elements to be sorted as numbers (so 3.50, 7, 12.95, 29.99, 77would result, and vice versa) |
| $prices = array('12.95', '3.50', '29.99', '77', '7'); sort($prices, SORT_STRING); rsort($prices, SORT_STRING); |
Option second argument forces the elements to be sorted as strings (so '12.95', '29.99', '3.50', '7', '77'would result, and vice versa) |
| $cards = array(1,2,3,4,5,6,7,8,9,10,11,12,13); shuffle($cards); |
This will re-arrange the elements in the array in random order (modifies the original array and returns true, so to create a new array as a shuffled version of the original you would clone the array and shuffle the clone) |
| $days = array(31,28,31,30,31,30,31,31,30,31,30,31); $m_sizes = array_unique($days); |
This will remove duplicate elements; only values in elements 0, 1 & 3 (the first instances of 31, 28 & 30) will be copied to the new array |
| $usa = array('New York', 'Washington'); $eur = array('London', 'Paris', 'Rome'); $cities = array_merge($eur, $usa); |
This will copy all 5 elements to the new array with indexes 0 to 4 (with associative arrays that both contain elements with the same keys, the first one copied will be replaced by the later one) |
| $first_element = reset($cards); | This will pull the first element of the array $cards (in a foreach loop, goes back to the first element in the array) |
| $last_element = end($cards); | This will pull the last element of the array $cards (in a foreach loop, goes ahead to the last element in the array) |
| if (is_array($primes)) { echo 'Array Confirmed. Woohoo!'; } |
the is_array() function tests whether its argument is an array |
| $ankhy = array('gender' => "male", 'fur' => "striped", 'size' => "extra large"); echo $ankhy['fur']; echo "<p> $ankhy[fur] </p>"; |
This is an associative array (in PHP, different from an object) |
| $ankhy['gender'] = "male"; $ankhy['fur'] = "striped"; $ankhy['size'] = "extra large"; |
This is the simple way to set up an associative array |
| extract($ankhy); | This creates a set of variables with names and values generated from the array, thus a variable $gender whose value is "male", etc. |
| extract($ankhy, EXTR_PREFIX_ALL, "cat"); | This refines the extract function to prefix the variable names, thus the variables are $cat_gender, $cat_fur, etc. |
| $md_cap = "Annapolis"; $va_cap = "Richmond"; $ny_cap = "Albany"; $capitals = compact('md_cap', 'va_cap', 'ny_cap'); echo $capitals['md_cap']; |
This creates an associative array from a specified set of variables |
| $c = compact(explode(' ', 'md_cap va_cap ny_cap')); | Shortcut for creating an array with compact() |
| $where = array('London', 'Rome', 'Nepal'); $when = array('2009', '2018', '2025'); $travels = array_combine($where, $when); |
Creates an associative array consisting of [London] 2009 etc. |
| asort($ankhy); arsort($ankhy); |
asort() sorts the elements of an associative array by value (resulting in: [size] extra large, [gender] male, [fur] striped) arsort() does the same thing but in reverse order |
| ksort($ankhy); krsort($ankhy); |
ksort() sorts the elements of an associative array by named key (resulting in: [fur] striped, [gender] male, [size] extra large) krsort() does the same thing but in reverse order |
| print_r($ankhy); | Will display the elements of an array and their values |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Cookies | |
| $visit_mark = time(); $exp = mktime(0, 0, 0, 12, 31, 2030); setcookie("visit_date", $visit_mark, $exp); |
Sets a cookie named "visit_date" with a value equal to the current date and an expiration date of 12/31/30; replaces any existing "visit_date" cookie Note that cookies must be set before the HTML tag |
| setcookie("visit_date", "none", time() - 86400); | Deletes the "visit_date" cookie by setting it to expire one day in the past (86400 seconds is one day) |
| $last_visit = $_COOKIE["visit_date"]; | Reads the value of the "visit_date" cookie (it may be necessary to reload the page to read data that was not already set on a previous visit) |
| if (!isset($_COOKIE["visit_date"])) // code to be run if there is no "visit_date" cookie |
Tests for the (non) presence of the "visit_date" cookie |
| $how_many_in_the_jar = count($_COOKIE); | Returns a count of elements in the superglobal array of cookies (a zero value can indicate that cookies are disabled in the browser) |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Date and Time🗝︎ | |
| $rightnow = time(); | Returns seconds since midnight 1/1/70 (PHP's core unit of time) |
| $newyear = mktime(0, 0, 0, 1, 1, 2016); $fiftieth = mktime(19, 30, 0, 10, 31, 2017); |
Returns seconds since midnight 1/1/70 for a specified point (12:00:00 am on 1/1/16 and 7:30:00 pm on 10/31/17) |
| echo date("l F jS, Y", $rightnow); echo date("l F jS, Y", time()); echo date("l F jS, Y"); |
Displays date formatted as Tuesday November 29th, 2016 (the second parameter is optional and defaults to the current time) |
| echo date("g: i A"); | Displays time formatted as 3:43 PM |
| echo "Day Formats: " . date("D l N w"); | Displays day formatted as Sun Sunday 7 0(N shows Monday to Sunday as 1 to 7 and w shows Sunday to Saturday as 0 to 6) |
| echo "Day of Month Formats: " . date("d j"); | Displays day of month formatted as 08and 8 |
| echo "Month Formats: " . date("M F m n"); | Displays month formatted as Apr April 04 4 |
| echo "Year Formats: " . date("Y y"); | Displays four-digit year and two-digit year |
| echo "Hour Formats: " . date("g h G H"); | Displays 8 o'clock as 8 or 8, 08 or 08, 8 or 20, 08 or 20 |
| echo "Minutes Format: " . date("i"); | Displays on the hour as 00 |
| echo "Seconds Format: " . date("s"); | Displays on the minute as 00 |
| echo "Place in Year Formats: " . date("z W"); | Displays day of the year (0-365) and week of the year (01-52) |
| echo "Modifiers: " . date("S a A"); | Displays day of month suffix thand 12-hour suffixes pm& PM |
| echo "Statistics: " . date("t L"); | Displays number of days in the month and leap days in year (1 or 0) |
| date_default_timezone_set("America/New_York"); date_default_timezone_set("America/Chicago"); date_default_timezone_set("America/Denver"); date_default_timezone_set("America/Los_Angeles"); date_default_timezone_set("Europe/London"); date_default_timezone_set("Europe/Paris"); date_default_timezone_set("Europe/Rome"); date_default_timezone_set("Asia/Hong_Kong"); date_default_timezone_set("Asia/Seoul"); date_default_timezone_set("Asia/Tokyo"); |
Sets the time zone for which the date and time will be read (Common zones shown; see 'php.net/manual/en/timezones.php' or 'w3schools.com/php/php_ref_timezones.asp' for others) |
| if (checkdate($month, $day, $year) { echo "$month/$day/$year is a valid date"; } |
Validates calendar dates based on m, d, y values |
| $s_w_day = strtotime('May 4 2017'); $birthday = strtotime('tomorrow'); $party = strtotime('next Saturday'); $vacation = strtotime('+6 months')' $otherholiday = strtotime('+180 days'); $meeting1 = strtotime('last Thursday'); $meeting2 = strtotime('+1 month 2 weeks', $meeting1); |
Interprets a text description of a date or a time adjustment and returns a timestamp that can be run through date() for display Time adjustments are done on the element specified so '+10 years' will differ from '+3650 days' (and the results should be checked in any case) The default base time is the current time and the preferred numerical date format is 2017-05-04 although it can read others |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Delay and Divert | |
| echo "password received"; sleep(3); echo "password validated"; |
Pauses 3 seconds between outputting "received" and "validated" [THE PAGE LOAD WILL BE DELAYED UNTIL SLEEP CONCLUDES] |
| echo "password received"; usleep(3500000); echo "password validated"; |
Pauses 3 1/2 seconds between outputting "received" and "validated" (1000000 microseconds—six zeroes—is one second) |
| time_sleep_until($alarm); time_sleep_until(time() + 30); |
Pauses until the point in time recorded as $alarm Pauses until the current time plus 30 seconds |
| echo "<script>location = 'page.php';</script>"; echo "<script>location.replace('pg.php');</script>"; |
Instead of equivalent PHP location methods, just generate Javascript |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Error Management | |
| $f = fopen("info.txt", 'r') or die("<h3>FAIL!</h3>"); | Outputs the message and stops the program (while blocking default warning message otherwise displayed when using a local/testing server) |
| function customError($e_type, $e_msg) { echo "<h3>FAIL!</h3>"; } set_error_handler("customError"); echo $nonexistent_variable; |
The message will be output for any error (while blocking default warning message otherwise displayed when using a local/testing server) |
| function cE($e_type, $e_msg, $e_file, $e_line, $e_vars) { $desc = "ERROR"; if ($e_type == 2) {$desc = "WARNING";} if ($e_type == 8) {$desc = "NOTICE";} echo "<h3>Processing of line $e_line of $e_file has produced the following $desc: $e_msg. The values involved include some or all of the following:</h3>"; print_r($e_vars); } set_error_handler("cE"); echo $nonexistent_variable; |
The message will be output for any error with the specifics conveyed by the arguments representing the error number, system-defined error message, file name, line number and an array of the active variables |
| function customError($e_type, $e_msg) { echo "<h3>$e_msg</h3>"; } set_error_handler("customError"); if ($n == 100) { trigger_error("Look out below!"); } |
The specified text will be output when the error is triggered |
| function supercustomError($e_type, $e_msg) { echo "<h3>$e_msg</h3>"; } set_error_handler("supercustomError", E_USER_WARNING); if ($n == 100) { trigger_error("Sky falling!", E_USER_WARNING); } |
The specified text will be output when triggered as a user warning |
| function supercustomError($e_type, $e_msg) { echo "<h3>$e_msg</h3>"; } set_error_handler("supercustomError", E_USER_ERROR); if ($n == 100) { trigger_error("Blue Screen O'Death!", E_USER_ERROR); } |
The specified text will be output when triggered as a user error —and the program will be stopped |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
External Code Importation | |
| include "signoff.php"; | Pastes the code from the signoff.php file into the current file |
| include_once "signoff.php"; | Pastes the code from the signoff.php file into the current file and prevents the same code from being included again even if another include or include_once command is encountered |
| require "signoff.php"; | Pastes the code from the signoff.php file into the current file and prevents the program from continuing if the file is not found |
| require_once "signoff.php"; | Pastes the code from the signoff.php file into the current file and prevents the program from continuing if the file is not found and prevents the same code from being included again even if another require or require_once command is encountered |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Form Handling | |
<form id=raction= inquiry.phpmethod= get> <label>City: <input type= textname= city/></label> <input type= submit/> </form> <?php $c = $_GET["city"]; // code for processing data ?> |
Passing data from a form using "get" (data shown in URL) |
| echo $_GET['city']; extract($_GET, EXTR_PREFIX_ALL, 'via_get'); echo $via_get_city; |
This method of extraction creates a set of variables prefixed with "via_get"—so if the the key/value pair "city:London" was sent over, then $via_get_city would have the value "London" and so on |
<form id=raction= register.phpmethod= post> <label>Name: <input type= textname= name/></label> <input type= submit/> </form> <?php $username = $_POST["name"]; // code for processing data ?> |
Passing data from a form using "post" (data hidden) |
| echo $_POST['name']; extract($_POST, EXTR_PREFIX_ALL, 'via_post'); echo $via_post_name; |
This method of extraction creates a set of variables prefixed with "via_post"—so if the the key/value pair "name:Oscar" was sent over, then $via_post_name would have the value "Oscar" and so on |
<form id=raction= <<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>method= post> | Posts (or, alternately, gets) data for processing to the same page it is being sent from without actually knowing the page name; htmlspecialchars() is used to remove HTML tags for security |
...<input type=submitname= login/>... ...<input type= submitname= register/>... <?php if ($_GET) { // code for processing data } if ($_POST) { // code for processing data } if ($_SERVER['REQUEST_METHOD'] == "GET") { // code } if ($_SERVER['REQUEST_METHOD'] == "POST") { // code } if ($_POST['login']) { // code for processing data } ?> |
The associated code runs when: The global variable which holds data sent by 'GET' has value The global variable which holds data sent by 'POST' has value Data has been sent by the 'GET' method Data has been sent by the 'POST' method The button named 'login' was pushed |
| $_REQUEST | This predefined global array contains info from all methods (i.e., everything that's in either $_GET or $_POST) |
| <?php $name_error = ""; if ($_POST['register'])) { if (empty($_POST['name'])) { $name_error = "Name Required!"; } } else // code for processing data ?> <form id= raction= register.phpmethod= post> <label>Name: <input type= textname= namerequired= required/> <?php echo $name_error; ?> </label> <input type= submitname="register" /> </form> |
Generating an error message when a field is skipped |
| <?php $email_error = ""; if ($_POST['register'])) { $email = $_POST['email']; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $email_error = "Invalid email address!"; } } else // code for processing data ?> <form id= raction= register.phpmethod= post> <label>Name: <input type= textname= required/> <?php echo $email_error; ?> </label> <input type= submitname="register" /> </form> |
There is a preset filter for validating email |
| if (!filter_var($x, FILTER_VALIDATE_INT) === false) | There is a preset filter for validating integers (except 0) |
| if (!filter_var($x, FILTER_VALIDATE_FLOAT) === false) | There is a preset filter for validating floating point numbers |
| $n = filter_var($x, FILTER_SANITIZE_NUMBER_INT); $n = filter_var($x, FILTER_SANITIZE_NUMBER_FLOAT); |
There are filters to clean up numbers which have extraneous characters |
| <?php $user_name = ""; if ($_POST['register'])) { $user_name = $_POST['name']; // code for processing data } ?> <form id= raction= register.phpmethod= post> <label>Name: <input type= textname= namerequired= requiredvalue="<?php echo $user_name; ?>" /> </label> <input type= submitname="register" /> </form> |
The submitted data can be retained in the fields in which it was entered |
| <?php $pref_day = ""; if ($_POST['register'])) { $pref_day = $_POST['day']; // code for processing data } ?> <form id= raction= register.phpmethod= post> <label>Preferred Day: <select name= daysize= 1> <option <?php if ($pref_day == "Sunday") echo "selected"; ?>>Sunday</option> </select></label> <input type= submitname="register" /> </form> |
Data retention for option selection menus |
| <?php $when = ""; if ($_POST['register'])) { $when = $_POST['when']; // code for processing data } ?> <form id= raction= register.phpmethod= post> <label><imput type="radio" name= whenvalue="afnoon" <?php if ($when) == "afnoon") echo "checked"; ?> /> Afternoon</label> <input type= submitname="register" /> </form> |
Data retention for radio buttons |
| <?php $newsletter = "on"; if ($_POST['register'])) { $newsletter = $_POST['newsletter']; // code for processing data } ?> <form id= raction= register.phpmethod= post> <label><imput type="checkbox" name= newsletter<?php if (!isset($newsletter) || $newsletter == "on") echo "checked"; ?> /> Get Our Newsletter!</label> <input type= submitname="register" /> </form> |
Data retention for (preselected) checkboxes |
<form id=uaction= upload.phpmethod= postenctype= multipart/form-data> <label>File: <input type= filename= pic/></label> <input type= submitvalue= UPLOAD/> </form> <?php $uploaded_file = $_FILES["pic"]["name"]; // code for processing data ?> |
Files can be uploaded via postusing a form like this |
| $p = "images/newpicture.jpg"; move_uploaded_file($_FILES['pic']['tmp_name'], $p); |
Stores the uploaded file as images/newpicture.jpg |
| $filetype = $_FILES["pic"]["type"]; | Possible values for image files include image/jpeg, image/gif, image/png, image/tiffalso see finfo_open |
| $filesize = $_FILES["pic"]["size"]; | Returns the file size in bytes (e.g. 15000 is 15KB) |
| $uploadcheck = $_FILES["pic"]["error"]; | No error (0) is UPLOAD_ERR_OK |
| $originalfilename = basename($_FILES["pic"]["name"]); | Returns the given name of the file that was uploaded |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Functions | |
| function square($y) { return $y * $y; } |
Will multiply the value sent to it times itself and return that result to the place where the function was invoked |
| $x = square($a); | Calls function square and sets the value of $x as the result of doing the function's calculations on $a |
| function expoMe($x) { $s1 = $x * $x; $s2 = $x * $x *$x; $s3 = $x * $x * $x * $x; return array($x,$s1,$s2,$s3); } |
A function can be set up to return data in the form of an array |
| function schedule($h = 10) { return $h . " o'clock tomorrow"; } |
This function can be called without an argument and the specified default value 10 will be used as though it had been passed as the argument |
| function describe_cat($value, $key_text, $x) { echo "<p style='font-size:" . $x . "em;'>"; echo "The cat's $key_text is $value."; echo "</p>"; } array_walk($ankhy, "describe_cat", 2); |
A function can be called on all the elements of an array with array_walk() [$key_text and $value arguments are read from the array; the additional argument $x is passed as an optional argument of array_walk()] |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Loops and Conditionals | |
| if ($x == 10) { $y = "decade"; } |
If the value of $x is 10, set the value of $y to "decade" |
| if ($x == 10) { $y = "decade"; } else { $y = "year"; } |
If the value of $x is 10, set the value of $y to "decade" —otherwise, set the value of $y to "year" |
| $x == 10 ? $y = "decade" : $y = "year"; | If the value of $x is 10, set the value of $y to "decade" —otherwise, set the value of $y to "year" |
| $elder = $age >= 100 ? "centenarian" : "senior"; | If the value of $age is 100 or more, set the value of $elder to "centenarian"—otherwise, set the value to "senior" |
| if ($x == 10) { $y = "decade"; } elseif ($x == 100) { $y = "century"; } |
If the value of $x is 10, set the value of $y to "decade" —otherwise, if $x is 100 set the value of $y to "century" (either else if or elseif will work) |
| for ($a = 10; $a <= 50; $a +=10) { echo $a . " "; } |
10 20 30 40 50 |
| for ($a = 10, $b = 50; $a <= 50; $a +=10, $b -=10) { echo $a . " " . b . "<br />"; } |
10 50 20 40 30 30 40 20 50 10 |
|
switch ($callSign) { case "A": echo "<h4>Alpha</h4>"; break; case "B": echo "<h4>Bravo</h4>"; break; case "C": echo "<h4>Charlie</h4>"; break; default: echo "<h4>INVALID SIGN</h4>"; } |
Will print "Alpha" if $callSign equals "A", etc. |
| $a = 10; while ($a <= 50) { echo $a . " "; $a +=10; } |
10 20 30 40 50 |
| $a = 10; do { echo $a . " "; $a +=10; } while ($a <= 50); |
10 20 30 40 50 |
| $primes = array(2, 3, 5, 7, 11, 13); foreach($primes as $number) { echo "One prime number is $number <br />"; } |
The foreach...as loop will automatically loop through an array (this is the syntax for a numerically indexed array) |
| $ankhy = array('gender' => "male", 'fur' => "striped", 'size' => "extra large"); foreach($ankhy as $trait => $descrip) { echo "The cat's $trait is $descrip <br />"; } |
The foreach...as loop will automatically loop through an array (this is the syntax for an associative array) |
| break; break 2; |
When executed in the {body} of a loop or switch statement, will discontinue the loop and move on to the next statement after the loop (most commonly used in a switch statement to stop after one case) —can also specify the number of levels to break through |
| continue; | When executed in the {body} of a loop, it bypasses the rest of the statements in the body and re-iterates the loop |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Math and Number Manipulation | |
| $x = rand(1, 12); $x = mt_rand(1, 12); |
Sets $x to a random integer from 1 to 12 Also sets $x to a random integer from 1 to 12; works better because it uses an algorithm with an interesting name |
| $gap = abs(8 - 12); | Sets $gap to 4 whether the expression value is 4 or -4 |
| $x = min($a, $b, $c); $y = max($a, $b, $c); |
Sets $x to the smallest value in the list (of at least two, or an array) Sets $y to the largest value in the list (of at least two, or an array) |
| if (is_nan($entry)) echo "Can't count to $entry!"; | Validates (by returning 1) if $entry is NOT a number |
| echo "The hex value of $x is " . dechex($x) . "!"; | Converts a decimal value to the hexadecimal version (as a string) |
| echo "The decimal value of $x is " . hexdec($x) . "!"; | Converts a hexadecimal (string) to the decimal format number |
| printf("<p>A hundred can be the decimal integer %d, the unsigned decimal %u, the floating point decimal %f, the scientific notation %e, the binary %b and the octal %o. </p>", 100, 100, 100, 100, 100, 100); | Using various formatting characters, printf will convert standard decimal values into other formats (all of them are also usable with sprintf) |
| printf("<p>A hundred in hex is %x.</p>", 100); $hundroid = sprintf("%x", 100); |
Outputs the value in lowercase hexadecimal (printf outputs to the browser while sprintf returns for assignment) |
| printf("<p style='color:#%X%X%X'>K</p>", 66, 77, 88); printf("<p style='color:#%X%X%X'>Other numeric expressions are valid</p>", 200, $x, $y * 1.2); |
Outputs the values represented by %X in uppercase hexadecimal |
| printf("<p>Per diem is $%.2f.</p>", $allowance / 7); | Outputs the value as a 2-decimal-place floating point number |
| printf("<p>Amount: $%6f.</p>", 75 / 8); | Outputs the value in a 6 character field [ 9.375] (NEEDS <pre> TAGS) |
| printf("<p>Amount: $%6.2f.</p>", 75 / 8); | Outputs the value as 6 characters, 2 decimal places [ 9.38] " |
| printf("<p>Amount: $%06.2f.</p>", 75 / 8); | Outputs the value as 0-padded 6 characters, 2 decimal places [0009.38] |
| printf("<p>Amount: $%'*6.2f.</p>", 75 / 8); | Outputs the value as *-padded 6 characters, 2 decimal places [***9.38] |
| printf("<p>There are %s bottles of beer...</p>", 99); | Outputs the value represented by %s as a string |
| $phone = sprintf("%s - %s", 625, 1190); | Outputs the values represented by %s as strings |
| $x = number_format("1234"); $x = number_format("1234", 2); $x = number_format("1234", 2, "*", "^"); |
Sets $x to 1,234 (will round off to an integer) Sets $x to 1,234.00 (displays the specified number of decimal places) Sets $x to 1^234*00 (first character is used as decimal point) |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
MySQL Controls | |
$targetserver = localhost; $user = root; $password = ; $mc = new MySQLi($targetserver, $user, $password); if ($mc->connect_error) { echo "Connection to SQL server failed."; } else echo "Connection to SQL server established."; $sqlcommand = "CREATE DATABASE ships"; if ($mc->query($sqlcommand) === TRUE) { echo "Database has been created."; } else echo "Database creation failed."; $mc->close(); |
Open a connection to the SQL server Check for errors Create a database to hold tables of information And close the connection when finished |
$targetserver = localhost; $user = root; $password = ; $db = ships; $mc = new MySQLi($targetserver, $user, $password, $db); if ($mc->connect_error) { echo "Connection to SQL server failed."; } else echo "Connection to SQL server established."; $sqlcommand = "CREATE TABLE baltimore (regnum INT(6) UNSIGNED AUTO INCREMENT PRIMARY KEY, name VARCHAR(25) NOT NULL, tonnage FLOAT, regdate TIMESTAMP)"; if ($mc->query($sqlcommand) === TRUE) { echo "Table has been created."; } else echo "Table creation failed."; $sqlcommand = "INSERT INTO baltimore (name, tonnage) VALUES ('Grey Ghost', 42.7)"; if ($mc->query($sqlcommand) === TRUE) { $entrynum = $mc->insert_id; echo "Data entry #$entry_num has been added."; } else echo "Data entry failed."; $sqlcommand = "DROP TABLE carthage"; if ($mc->query($sqlcommand) === TRUE) { echo "The table has been deleted."; } else echo "Table deletion failed."; $mc->close(); |
Open a connection to a database on the SQL server Check for errors Create a table with defined fields to hold information Add data to the table Delete a table that is no longer needed And close the connection when finished |
$targetserver = localhost; $user = root; $password = ; $db = inventory; $mc = new MySQLi($targetserver, $user, $password, $db); if ($mc->connect_error) { echo "Connection to SQL server failed."; } else echo "Connection to SQL server established."; $a = $mc->prepare("INSERT INTO cars (make, model, year) VALUES (?, ?, ?)"); $a->bind_param("ssi", $make, $model, $year); $make = "Pontiac"; $model = "Fiero"; $year = 1985; $a->execute(); $a->close(); $mc->close(); |
Open a connection to a database on the SQL server Check for errors Set up a prepared statement to data to a table ("ssi" means "string string integer"; can also use double and blob) Invoke the prepared statement with the data to add Close the prepared statement And close the connection when finished |
| // code to open a database connection called $mc $sqlcommand = "SELECT name, t FROM boston"; $table_data = $mc->query($sqlcommand); if ($table_data->num_rows > 0) { while ($row = $table_data->fetch_assoc()) { echo $row['name'] . ":" . $row['t'] . " tons"; } } else echo "No data was found"; // code to close the database connection called $mc |
Select the data to be pulled from the table Loop through each row of the data |
| $sqlcommand = "UPDATE ny SET t = 42 WHERE name = 'X'"; $sqlcommand = "DELETE FROM miami WHERE name = 'Jade'"; $sqlcommand = "SELECT * FROM boston LIMIT 3"; $sqlcommand = "SELECT * FROM boston LIMIT 3 OFFSET 3"; |
Change the data on an existing row Delete an existing row entirely Get only the first 3 rows from the table Skip three rows and then get the next 3 rows Note: Full MySQL Query syntax is on the MySQL page |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Objects | |
| echo "The car is a $car_1->model by $car_1->make"; | Basic syntax for referring to a property of an object |
| $car_1->reminder(); | Basic syntax for calling a method of an object |
| class Car { function Car($c1, $c2) { $this->make = $c1; $this->model = $c2; $this->registered = "Maryland"; } function reminder() { echo "Wash the $this->model!"; } } |
Class declaration to provide the structure to create an object [constructor function can be named "__construct" or the class name] |
| $c_make = "Pontiac"; $c_model = "Fiero"; $car_1 = new Car($c_make, $c_model); |
Basic syntax for creating an object (as an instance of a class) [the actual values can also be passed as arguments] |
| $car_2 = clone $car_1; $car_2->model = "Solstice"; |
Create a separate copy of an object without affecting the original (an object's value is passed by reference so the new one would otherwise just behave as a second name for the same object) |
| class Car { function Car($c1, $c2) { $this->make = $c1; $this->model = $c2; $this->registered = "Maryland"; } static function reminder() { echo "Wash the car!"; } } |
Class declaration that includes a method for the class, not for its objects |
| Car::reminder(); | Basic syntax for calling a method of a class |
| class Bike extends Car { public $engine, $surface; } |
Create a subclass that is a copy of the original plus any additions |
| class Bike extends Car { public $engine, $surface; function reminder() { echo "Watch out for rain!"; } function alt_reminder() { parent::reminder(); } } |
Conflicts between identical names used in original and subclasses are resolved with parent:: and self:: (also applies to properties) |
| class Painting { public $title; protected $curator; private $price; const MUSEUM = "The Froink Collection"; static function creditline() { echo 'Courtesy of ' . self::MUSEUM; } } |
A public property is accessible to all code (default status) A protected property is only accessible within a class or its subclasses A private property is only accessible within the original class A constant is defined within a class using const... ...and accessed using self:: |
| class Boat { static $count; function log_boat() { self::$count +=1; return self::$count; } } $jade = new Boat(); $jade->log_boat(); $bc = Boat::$count; |
Includes a property for the class itself that can be accessed indirectly by its objects through a function as well as directly through the class name |
| class Car { function __construct($c1, $c2) { $this->make = $c1; $this->model = $c2; $this->registered = "Maryland"; } final function reminder() { echo "Be Safe!"; } } |
A final method will not be overridden by a subclass method |
| class Car { function __construct($c1, $c2) { $this->make = $c1; $this->model = $c2; $this->registered = "Maryland"; } function __destruct() { echo "Goodbye!"; } } |
A destructor method will run when the object is destroyed (deleted) |
| print_r($car_1); | Will display the properties of an object and their values |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Operators | |
| + [e.g. $x = $n + 1;] | Sums the values of two numbers |
| . [e.g. $greeting = "Hello " . $name;] | Concatenates two strings (numbers will convert to strings) |
| $x +=$y; | Shortcut equivalent to $x = $x + $y; |
| $x .=$y; | Shortcut equivalent to $x = $x . $y; |
| - * / % ++ -- = -= *= /= %= == != > < >= <= |
These all work the same as in Javascript |
| === !== | These are identityinstead of strict equalitycomparison operators; no type conversion so 1000 won't match "1000", nor will 1 match true |
| && [e.g. $x == 0 && $y > 100] | Works the same as in Javascript |
| and [e.g. $x == 0 and $y > 100] | An alternate version of && with lower precedence |
| || [e.g. $x == 0 || $x > 100] | Works the same as in Javascript |
| or [e.g. $x == 0 or $x > 100] | An alternate version of || with lower precedence |
| xor [e.g. $x == 0 xor $y == 100] | exclusive or— true if either but not both are true |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Pattern Matching | |
| if (preg_match("/[0-9]/", $digit)) { echo "Verified numerical!"; } |
Returns true if the argument is a numerical character |
| if (preg_match("/[a-zA-Z]/", $letter)) { echo "Verified alphabetical!"; } |
Returns true if the argument is a letter |
| if (preg_match("/[.,:;@- ]/", $other)) { echo "Verified space or other interrupty thing!"; } |
Returns true if the argument is a space or hyphen etc. |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Session Variables | |
| <?php session_start(); ?> <!DOCTYPE html> |
Opens a session so that session variables can be used Note: sessions must be opened before the DOCTYPE declaration |
| $_SESSION["comments"] = "on"; | Creates (or updates) a session variable called "comments" |
| if($_SESSION["comments"]) { $comment_status = $_SESSION["comments"]; } else $comment_status = "off"; |
Accesses a session variable called "comments" |
| session_unset(); | Destroys all the session variables (also go away when browser is closed) |
| session_destroy(); | Destroys the session itself (also goes away when browser is closed) |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Strings | |
| $s = 'The variable $mud says \'sling me\'...'; | This is a literal string: except for the \' used to include a single-quote mark without closing the string, it will set the value of $s to the exact characters that are between the single quotation marks |
| $s = "The pumpkin said $mud to the trebuchet..."; | This string in double-quotes will interpret variables so if $mud is sling methen $s will be The pumpkin said sling me to the trebuchet... |
| \' \\ | Escape characters which work in literal strings |
| \t \n \r | Escape characters for tab, new line and return which work in strings |
| $section1 = <<<_HEADLINE <h1 id="breaking">$masthead</h1> <h2>$subhead</h2> <h4>$byline</h4> _HEADLINE; |
This is a heredoc, which is a multiline string format that allows for quotation marks and line breaks but can interpret variables |
| $banner = strtoupper("Festival!"); | Sets $banner to FESTIVAL! |
| $banner = strtolower("E. E. Cummings"); | Sets $banner to e. e. cummings |
| $banner = ucfirst("this is a text message"); | Sets $banner to This is a text message |
| $banner = ucfirst(strtolower("HILL")); | Sets $banner to Hill [ucfirst() modifies result of strtolower()] |
| $banner = str_repeat("* ", 20); | Sets $banner to * * * * * * * * * * * * * * * * * * * * (20 *s) |
| $banner = strrev("icniV ad odranoeL ma I"); | Sets $banner to I am Leonardo da Vinci |
| $x = strlen($log_entry); | Sets $x to the number of characters in $log_entry |
| $x = strpos($log_entry, "snow"); | Sets $x to the position where "snow" first appears in $log_entry |
| $x = strrpos($log_entry, "snow"); | Sets $x to the position where snow last appears in $log_entry |
| $spring = str_replace("snow", "rain", $log_entry); | Changes the word snow to rain in new version of $log_entry |
| $creed = "Not all those who wander are lost"; $c1 = substr($creed, 8) $c2 = substr($creed, -8) $c3 = substr($creed, 4, 3) $c4 = substr($creed, 0, -8) |
[characters are numbered beginning with 0, so #8 is the 9th] Sets $c1 to the section of the string from the 9th character forward Sets $c2 to the last 8 characters of the string Sets $c3 to the 3 characters of the string from the 5th forward Sets $c4 to the portion of the string from the 1st to the 9th from the end |
| $creed = "Not all those who wander are lost"; $words = explode(' ', $creed); |
Creates an array $words with elements whose values are "Not", "all", etc. |
| $creed = "Not all those who wander are lost"; $letters = str_split($creed, 1); |
Creates an array $letters with elements whose values are "N", "o", etc. (1 is actually the default value but any length can be specified) |
| $r = trim($r); $r = stripslashes($r); $r = htmlspecialchars($r); |
These are common methods for cleaning up data when processing forms specifically, removing white space from the ends of a string, removing backslashes, and changing < > ' " and & to their character entities |
| printf("<p>ASCII character 55 is %c.</p>", 55); $p = sprintf("ASCII character 55 is %c.", 55); |
Outputs the ASCII character for the value represented by %c (printf outputs to the browser while sprintf returns for assignment) |
| printf("<p>There are %s bottles of beer...</p>", 99); | Outputs the value represented by %s as a string OTHER printf SPECIFICATIONS ARE UNDER MATH/NUMBERS |
| $phone = sprintf("%s - %s", 625, 1190); | Outputs the value represented by %s as a string OTHER sprintf SPECIFICATIONS ARE UNDER MATH/NUMBERS |
| printf("<pre>«%15s»</pre>", $word); | Outputs the string to fill 15 spaces, padding on the left |
| printf("<pre>«%-15s»</pre>", $word); | Outputs the string to fill 15 spaces, padding on the right |
| printf("<pre>«%015s»</pre>", $word); | Outputs the string to fill 15 spaces, padded with 0's on the left |
| printf("<pre>«%'*15s»</pre>", $word); | Outputs the string to fill 15 spaces, padded with *'s on the left |
| printf("<pre>«%15.12s»</pre>", $word); | Outputs the first 12 characters to fill 15 spaces, padding on the left |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Structural Basics | |
| <?php all the PHP code goes here ?> |
Code within these tags will be processed as PHP |
| statements end with; | Semi-colon marks the end of a statement |
| // just a comment | A single-line comment |
| /* just a comment that keeps going */ |
A multi-line comment |
echo <h1>Hello $world</h1>; |
Sends something through to the browser |
print <h1>Hello $world</h1>; |
Alternative to echothat can be used in complex expressions |
| http://localhost/filename.php | This is the address for internally stored pages |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
System & Program Info | |
| phpinfo(); | This is a component of PHP that provides an extensively detailed display of the user's PHP installation specs (already styled & formatted) NEVER LEAVE A phpinfo() CALL ONLINE AS IT IS A SECURITY RISK |
| echo phpversion(); | This predefined function provides the version of PHP currently running |
| echo $_SERVER['SERVER_SOFTWARE']; | This predefined global provides the type of server (e.g. Apache) |
| if (function_exists("array_combine")) { echo "PHP is not too old!"; } |
Checks if the version of PHP now running supports the specified function |
| echo 'The file directory is ' . __DIR__; | This predefined constant provides the file directory chain |
| echo 'The name of this document is ' . __FILE__; | This predefined constant provides the file name |
| echo 'The active function name is ' . __FUNCTION__; | This predefined constant provides the function name |
| echo 'Currently at line number ' . __LINE__; | This predefined constant provides the line number within the file |
| $via_link_at = $_SERVER['HTTP_REFERER']; | This predefined global provides the url of the site from which the user navigated to the page as part of an array of information from the server |
| $via = htmlentities($_SERVER['HTTP_REFERER']); | The predefined htmlentities() function changes potentially malicious code into HTML characters (e.g. <) for security reasons in case the predefined global has been hacked |
| $user_ip = $_SERVER['REMOTE_ADDR']; | This predefined global provides the user's IP address |
| $browser = $_SERVER['HTTP_USER_AGENT']; | This predefined global provides some browser details |
| if($_SERVER['HTTPS']) { // code goes here; } | Is true if site was accessed through a secure connection |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Text Files | |
| $mf = fopen("magic.txt", 'w') or die("FAIL!"); $mc = "rabbit"; fwrite($mf, $mc) or die("FAIL!"); fclose($mf); |
Creates a text file named "magic.txt" (replacing any old "magic.txt" file) and adds the string "rabbit" to it and then closes the file |
| $mf = fopen("magic.txt", 'a') or die("FAIL!"); $mc = " cards"; fwrite($mf, $mc) or die("FAIL!"); fclose($mf); |
adds the string " cards" to the "magic.txt" file |
| $mf = fopen("magic.txt", 'a') or die("FAIL!"); flock($mf, LOCK_EX); $mc = " wand"; fwrite($mf, $mc) or die("FAIL!"); flock($mf, LOCK_UN); fclose($mf); |
locking and unlocking the file when updating it will prevent corruption |
| $mf = fopen("magicspells.txt", 'r') or die("FAIL!"); $mc1 = fgets($mf); $mc2 = fgets($mf); $mc3 = fread($mf, 1000); fclose($mf); |
sets $mc1 equal to line 1 of the "magicspells.txt" file sets $mc2 equal to line 2 of the "magicspells.txt" file sets $mc3 equal the rest of the "magicspells.txt" file (as long as that's less than 1000 characters; close & reopen to start over) |
| $ms = filesize("magicspells.txt"); | Gets the size of a file |
| $mf = fopen("magicspells.txt", 'r') or die("FAIL!"); fseek($mf, 25); echo "Seeing <q>" . fread($mf, 10) . "<q>" echo " and now at " . ftell($mf) . "."; fclose($mf); |
goes to element 25 of the text file reads the next ten characters and reads the position it's now at (35) |
| $mf = fopen("magicspells.txt", 'r') or die("FAIL!"); while (!feof($mf)) { $mc_next = fgetc($mf); } fclose($mf); |
reads the location of the last character of the text file sets $mc_next equal to the next character of the text file |
| $mc = file_get_contents("magicspells.txt"); | Gets the entire contents of a file (or web page) without fopen |
| $mc_plus = readfile("magicspells.txt"); | Gets the entire contents of a file as one long string (no line breaks) plus the size of the file, also without fopen |
| copy("magic.txt", "props.txt") or die("FAIL!"); | Copies the "magic.txt" file as "props.txt" |
| rename("magic.txt", "magic.new") or die("FAIL!"); | Renames the "magic.txt" file as "magic.new" |
| if (unlink("magic.txt")) echo "DELETED!"; | Destroys the "magic.txt" file—by invoking unlink, even via 'if' or 'if (!' |
| if (file_exists("magic.txt")) echo "FOUND!"; | Checks for the existence of a "magic.txt" file |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |
Variables | |
| $count = 0; $name = Charlotte; |
All variable names start with $ (no explicit declaration needed and types are fluid) |
| $cash = 25 * 80; $c1 = substr($cash, 0, 1); $tax = $c1 / 4; |
A number can be treated as a string so this will return the first digit (1 character starting at element 0) without type modification and then numerical calculations can be done on the returned character |
| $x = null; | A variable with no value has a value of null; equal but not identical to 0 |
| define("COMPANY", "Boeing"); echo COMPANY . $status; |
A constant variable is specifically defined and then cannot be changed |
| $a = 19; $b = 27; $c = 42; function predict($x, $y) { $z = 85; return "The winning numbers are $x and $z"; } echo predict($a, $b); |
Will produce "The winning numbers are 19 and 85" The way variable scope works, the function can read $a and $b (under the identifiers $x & $y) but not $c since it's not a global variable like it would be in Javascript; $z does only exist inside the function as usual, though |
| $a = 19; $b = 27; global $C = 67; function predict($x, $y) { global $Z = 73; return "The winning numbers are $y $C and "; } echo predict($a, $b) . $Z; |
Will produce "The winning numbers are 27 67 and 73" To bypass default variable scope, variables can be specifically defined as global variables so both $C and $Z are accessible by all lines; a constant (created with 'define') would also be globally accessible—and a variable could be defined outside a function then declared as global inside one (The function arguments are passed as before) |
| function countHits($x) { static $macks = 0; $macks +=$x; return $macks; } |
The static variable $macks is only accessible inside the function (like a local variable) but it retains its value between function calls (like a global one) |
| $GLOBALS echo $GLOBALS['x']; |
This predefined global contains global variables this is a way the variable $x could be accessed from within a function |
| var_dump($x); | Will show the type and value of the variable $x |
| ♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣♣ | |