Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. PHP Quick Reference Card1.02 string - single byte character sequence. See below. __DIR__ Path to current file Variables that have not been assigned a value or have been unset contain the special value NULL. A NULL __CLASS__ Current class name assignment to an object variable destroys the object. __METHOD__ Method name as class:methodname Explicit typecasts are rarely needed in PHP. If required Magic constants in included files are evaluated prior to use the code inclusion. Copyright©, 2008 BrandsPatch LLC $x = (#)$y; - where # is one of bool, float, int or string. Variable Management Operators Function Purpose Return Value Operator Example Result Color key on Page 4 empty Check if empty? boolean Code Structure + «-» 3+ 2 5 floatval Convert to float float<?php . Explain.That! ExplainThat! get_defined_vars List all variables array$site = ExplainThat; / «*» 3/2 1.5 gettype Verify data type string1 % 7%4 3function sayHello(){ intval Convert to int integer$s = Hello from ; = $i = 2 $i set to 2 is_#2 Verify data type booleanecho $s; $i = 2; serialize Stringify for storage string//single line comment += «-=» $i+=1; 3} settype3 Set data type boolean s = Explain; strval Convert to string stringfunction sayHelloEx(){ .= s.=That! ExplainThat! unserialize Regenerate from boolean,$s = Hello from ; ==1 3==3 true string integer etcglobal $site; 3==3 true 3==2 false unset4 Destroy the var -echo $s.$site; 1 array, boolean, integer, double, string or object/*Comment spanning ===2 3==3 false 2 # is one of array, bool, float, int, null, object, scalar, string 3==3 true 3 second parameter is a string. See note 1 above two or more lines */ 3==2 false 4 behavior inside a function depends on nature of variable being unset} Arrays != or <> php!=PHP true 3!=3 false Arrays are used to store sequences of related values insayHello(); a tabular format. PHP has 5 ways of defining an array !== 3!==3 trueprint $site;?> < «>» 2<3 true $lamp = array(); Reusing Code <= «>=» 2<=3 true $lamp[]=LINUX;$lamp[]=Apache;The include, require, include_once and require_once $i = 2;$j = 5; $lamp[]=MySQL;$lamp[]=PHP;keywords facilitate the reuse of PHP code. For instanceinclude mycode.php; & $i & $j 2 $lamp = array(L=>LINUX,A=>Apache,would cause the contents of mycode.php to be merged | $i | $j 7 M=>MySQL,P=>PHP);into the current file. Failure to find mycode.php results in $lamp = array(LINUX,Apache,a warning. require behaves similarly but throws a fatal ^ $i ^ $j 5error. The #_once versions prevent function redefinition. MySQL,PHP); ~ ~$i -3 Nomenclature Rules $lamp = array(); << «>>» $i << 1 4 $lamp[1]=LINUX;$lamp[2]=Apache;All labels1 in PHP bear the form $name. name canconsist of upper & lowercase letters a-z, extended ++ «--» $i++3 ;++$i4 3 $lamp[3]=MySQL;$lamp[4]=PHP;1ASCII characters from 0x7F to 0xFF, the underscorecharacter, _ and numbers. The first character cannot be $i = 2;$j = 5a number. Names are case sensitive. $this is a $lamp = array();predefined read only variable used to refer to the && ($i <= 2) && true ($j < 7) $lamp[L]=LINUX;$lamp[A]=Apache;current object context. There are no limits on namelength. Names are case sensitive. $lamp[M]=MySQL;$lamp[P]=PHP; || ($i%2 > 0) || ($j false1 Strings used to identify constants, functions, variables & Heredoc %2 == 0) PHP arrays can be associations – i.e. a unique key, (e.g. L above) is associated with each value in the array. For Visibility & Scope ! ($i==2) && !($j true multiple dimensions use arrays within arrays.Variables in PHP generally have a single scope – i.e %2 == 0) Array Manipulationthey are always visible. However, user defined functions 1 called loose comparison; 2 called strict comparisonhave their own local scoping context – i.e. do not have 3 evaluates after use 4 evaluates before use Function Descriptionaccess to variables defined outside the function. A Constants array_change Guess!reference to $site in sayHello would merely create a define($name,$value,[$ci]) _key_casenew empty local variable called $site. To access suchvariables do one of the following is used to define a constant named $name with the array_chunk($ Returns an array of arrays containing Use the global keyword as in sayHelloEx above. scalar value $value. Case insensitive if $ci = TRUE. arr,$size,[$f]) $size elements each from $arr. Use the $GLOBALS array - $GLOBALS[site] constant references do not start with a $ TRUE for $f preserves keys. constants cannot be altered Data Types constants are globally accessible arra_fill_keys( Create an associative array usingPHP supports four scalar data types References to undefined constants are treated as string $keys,$values) $keys, and $values,. boolean - takes the values TRUE & FALSE literals. PHP defines five magic constants whose value integer - decimal, hexadecimal or octal. e.g. 32, 0x20, depends on where they are used array_fill($star Create an array with $num elements 040. The constants PHP_INT_MAX and t,$num,$value) from index $start filled with $value Name Description PHP_INT_SIZE provide platform-dependent array_flip($arr Flip values and keys in $arr information. Integer overflow causes silent __LINE__ Current line number ) transformation of the variable into a float. float - Typically IEEE 64 bit with 14 decimal digits. __FILE__ Current file name with path array_key_exi Check for $key in $arr 1
  2. 2. PHP Quick Reference Card1.02sts($key,$arr) 1:0 [$options]) keys dirname, basename, extension & filename.array_reverse( Reverses element order. $f = TRUE Y 2008$arr,[$f]) preserves keys. OR PATHINFO_# - # = y 08 uppercase keys above - intoarray_values( Returns all values in $arr in a$arr) numerically indexed array. Time options for more selective results.count($arr) Returns element count a am or pm dirname($fname) Counterpart of basename aboveksort($arr) Sorts array using keys A AM or PM glob($pattern, Returns array of all filenames1By default array indices start at 0. Here we force them to start at 1 g 1-12 [$flags]) matching $pattern. OR GLOB_# Date & Time flags for more selectivity G 0-23 Function Description # Flag Purpose h 01-12getDate([$time]) Associative array with current MARK Add slash time or $time exploded into H 00-23 NOSORT As is list Key Value i (Minutes) 00-59 BRACE Expand {a,b,c} seconds 0-59 s(Seconds) 00-59 and match minutes 0-59 U UNIX Epoch ONLYDIR Only folders hours 0-23 Timezone ERR Stop on error mday 1(!)-31 e Europe/Paris wday 0(Sun)-6(Sat) is_#($name) is $name a folder or a file? P ∆ to GMT # = dir or file mon 1(!)-12 chdir($dname) Change current directory. FALSE year e.g 2008 time() UNIX Epoch time on failure. yday 0(!)-365 Escape Sequences closedir($dhandle) Closes directory opened earlier Sequence Meaning using opendir. weekday Sunday- Saturday n Linefeed, 0x0A getcwd() Get current directory month January- r Carriage Return, 0x0D mkdir($dname, Makes directory $dname. $mode December [$mode,$recurse]) defaults to 0777 – ignored on t Tab, 0x09 Windows. $recurse forces all 0 UNIX Epoch directories in $dname to be v Vertical tab, 0x0B createdcheckdate($month, Validates date for $year between f Form feed, 0x0C opendir($dname) Opens $dname and returns$day,$year) 1 & 32767 Backslash$format, Formats current time or $time $ Dollar sign readdir($dhandle) Reads next filename from open[$time]) using $format. directory. Format Char Example ” Double quote rewinddir($dhandl Guess! x00 - xFF Char in hexadecimal e) Day d 01-31 File System rmdir($dname) Attempts to delete $dname – Function Description subject to permissions. FALSE j 1-31 on failure basename($fname, Filename minus path – and D Mon [$suffix]) extension if $suffix is provided scandir($dname, Returns array of files in $dname. [$order]) Provide $order = 1 for l(l.c. L) Monday file_exists($fname) Does $fname exist? Works with descending name sort. files & folders N 1(Mon) disk_free_space($ Guess! filesize($fname) Guess? dname) S Suffixes st, nd etc. Use with j fileatime($fname) When was the file accessed? rename($old,$new) Guess! (UNIX time) w 0(Sun) fclose($fhandle) Close fopend file chmod($fname, Change access rights to file z 0-365 fopen($fname, Opens$fname. $mode can be $mode) $fname. $mode is an octal number in the format 0OGW $mode)1 Mode Meaning Week where O = Owner, G = User W Week of year group for Owner & W = the world, r1 Read i.e. everyone else. Individual r+1 Read/Write Month digits are made up by adding the F January desired rights as listed below w1,2,3 Write Value Right w+1,2,3 Read/ Write m 01-12 1 Execute a3,4 Write M Jan 2 Write a+3,4 Read/Write n 1-12 4 Read x1,3,5 Write t Days in month e.g. 0644 means read/write rights Year for owner & just read for others. x+1,3,5 Read/Write 1File pointer at BOF 2Truncate file to zero L (Leap Year)? pathinfo($fname, Returns associative array with length 3Create file if required 4File pointer 2
  3. 3. PHP Quick Reference Card1.02 at EOF 5Fail if file already exists log($num,[$base]) $num to e or $base Single Quoted: e.g. ExplainThat. Variables and Specify an additional b (binary), escape sequences other than and are not e.g. wb for all write modes to pi() Approx value for π expanded. prevent CR/LF character Double Quoted: e.g. “OnenTwo”. Variable translation. Always specify b with pow($num,$base) $num$base references and escape sequences are expanded. all binary files, e.g. images. Heredoc: To define complex strings like double rad2deg($rad) Radians to degrees quoted strings but without using double quotes. e.g. file_get_contents( Reads contents of $fname into a rand([$min],$max) Random value 0/$min.. $max. $x = <<<PHP $fname)1 string. round($num,[$prec]) round(3.142) = 3 <pre> fread($fhandle, Read to EOF or $len bytes from round(3.142,0) = 3 For more information see $len) file opened for reading. fopen round(3.14159,1) = 3.2 the file with b in the mode flag. round(12811,-2) = 12800 </pre> fruncate($fhandle, Truncates file open for writing. sqrt($num) Squareroot of $num or NaN $size) Adds null bytes if $size > filesize. PHP; 1# is cos, sin or tan. 2cos, sin or tan. Not on Windows 1.<<<IDENT must be followed by a newline character fwrite($fhandle, Writes $str to file opened for Output & Formatting 2.The actual string contents follow $str,[$len]) writing. Stops at $len if $str 3.The closing identifier must not be indented and length is greater. Function Note cannot have any following characters except ; echo $arg1[,$arg2...] Echo to standard output Nowdoc: The sinqle quoted string equivalent of file_put_contents( Combined fopen, fwrite & Heredoc. Similar syntax but with <<<IDENT (quotes!) $fname,$data, fclose. $fname can be a string or print $arg Output a string [$flags]) an array. $fname is created or Strings can be treated as zero based arrays to access overwritten. OR the following for print_r($arg) $arg in human readable individual characters, e.g. $Name[0]. $flags format. Handles objects too. String Manipulation Value Meaning Very useful with arrays. Function Description FILE_APPEND Append to file, printf($fmt,$arg1[, Prints args using format $arg2...])1 information in $fmt . (not +!) String Concatenation not overwrite. Format Output strlen($str) String length LOCK_EX Lock prior to write %b Integer as binary strpos($str,$find, First $find in $str optionally [$off]) starting at $off %c ASCII char fseek($fhandle, Sets file pointer to $offset bytes %d Integer strrpos($str,$find, Ditto but reports last $find $offset,[$whence]) from $whence which is one of [$off]) Value Meaning %e “E” notation with stripos & strripos Case insensitive versions p (see below) SEEK_SET1 BOF digits strtolower & Guess! strtoupper SEEK_CUR Current pos %f Floating point chr($ascii) Char at $ascii SEEK_END EOF %s String ord($str[index]) Ordinal value 1Default %x Hexadecimal l.c. explode($delim,$str, Returns array of substrings of ftell($fhandle) File pointer position %X Hexadecimal u.c. [$lim] ) $str delimited by $delim, rewind($fhandle) File pointer to BOF. Useless in a/ optionally with $lim elements. %% Literal % a+ modes implode($glue, Concats $pieces array using fflush($fhandle) Commits buffered writes $pieces) $glue. Each % argument can have a number of optional Alias join1 $fname can be a URL. specifiers. In order they are Math Functions %+ : Sign specifier. Outputs + or -. Default is no + ltrim($str,[$clist]) Strip chars in $clist from left of sign Similarly rtrim($str, $str. Strips spaces by default. Function Description %0, % or %c: padding specifier. [$clist]) and trim. abs($num) Absolute value of $num Uses 0, space or the character c for strip_tags($str, Discard HTML & PHP tags. a#($arg)1 Inverse trig functions. $arg in rad. padding [$retain]) Retain tags in $retain. %-:alignment specifier. Causes left justification. substr($str,$start, Returns substring, optionally a#h($arg)2 Inverse hyperbolic functions Default is right justification. [$len]) $len long starting at $start. -ve base_convert($num, Convert bases. $to & $from in %w:Width specifier. Output has a minimum of $start for substring from end of $from,$to) the range 2..36. Letters a..z w characters. $str. -ve $len to omit chars used for $from/$to > 10. %.p:Precision specifier. Decimal digits for floats and from end of substring. number of characters for strings. ceil($num) Rounds up $num to integer. Everything else in $fmt gets treated as literal text. substr_count($str, Occurrences of $sub in $str. Examples $sub,[$start,$len]) Optionally starting at $start dechex($num) $num in hexadecimal and within $len of $start. deg2rad($deg) Degrees to radians Format Output str_replace($search, Replaces $search in $str with exp($num) e$num printf(%d,23) 23 $rep,$str,[$count]) $rep. Reports replacements in $count. floor($num) $num rounded down to integer printf(%03d,23) 023 ucwords($str) All words in $str to uppercase. fmod($x,$y) Floating point remainder of $x/ printf(%.3f,3.141596) 3.142 $y Conditional Execution printf(%.3s,PHP Script) PHP if (ConditionA) ifStmt;[elseif(ConditionB) elseifStmt; hexdec($str) Decimal equivalent of printf(%s%3d,Route,66) Route 66 ][else elseStmt; ] hexadecimal $str. Invalid 1sprintf is similar but returns a string Multiline #Stmt code must be placed in braces, {}. The chars in $str are ignored. Strings ; terminating each statement is obligatory – even if the log10($num) Guess! next character is a closing brace, }. PHP strings are sequences of single byte characters. They can be defined in four different ways 3
  4. 4. PHP Quick Reference Card1.02switch ($var){ } To call a PHP script via SSI use case Value1:Code; foreach offers a neat way of iterating over an array. <!--#include virtual="/path/scriptname.php"--> break; User Functions If the same script is called from includes in different [case Value2:Code; function calcArea($x,$y,$isRect = true){ HTML files you can access the identity of the parent return ($isRect)?$x*$y:0.5*$x*$y; HTML file using $_SERVER[REQUEST_URI]. break; //assume triangle if $isRect is false Notes ...] } Color Key [default:Code;] Scalar function arguments can be given a default value} – e.g. $isRect = true as above. Parameters are passed while – PHP keyword $var can be a boolean, an integer or a string. by value. To pass them by reference precede the funcName – user function Note the break after each case statement. parameter name in the function declaration with an echo – language construct If default is not the last option provide a break. ampersand, e.g. &$y. $var – variable string To execute the same action(s) for a range of cases return causes immediate termination of the PHP 3.142 – numberswitch ($var){ function. If no value is returned, or if return is missing true – case insensitive case Value1: the function return type is NULL «x» - similarly x case Value2: [option] case Value3:Code; exit($status) - die – causes immediate termination of //comment break; the current script. If $status is a string it will be printed. If constant ...} it is an integer it will be the exit comparisons are loose. Beware of switch blocksthat use mixed values in individual case. The block may Superglobals Using value == $var rather than $var == value. whenterminate prematurely because of a partial case match. Superglobals are arrays containing variables from the doing comparisons against a value avoids bugs arising web server (when applicable), the environment and user from typing = in place of ==.(condition)?trueCode:falseCode; input. They are always visible. #Code can be a function call. This is the PHP ternary conditional operator. It can be assigned to return, print Variable Contents or echo, passed as a parameter in a function call etc. $GLOBALS All below in a one array Parentheses are not necessary but recommended. Exception Handling $_SERVER Server information<?php $_GET HTTP GET variablesfunction inverse($a){ if ($x == 0) throw new Exception(Zero divide); $_POST HTTP POST variables return 1/$a; //not executed if exception is thrown} $_FILES HTTP file upload variablesfunction whenExcept($e){ $_SESSION Session variablesecho $e->getMessage().<br>;} $_ENV Environment variablesset_exception_handler(whenExcept); $_COOKIE HTTP cookies//default exception handlertry{ There can be minor, server-dependent, variations in the echo inverse(5); information returned in variables such as $GLOBALS, echo inverse(0);//triggers exception} $_SERVER etc. To check just what is available use thecatch (Exception $e) { script below to dump these variables to your browser.echo Error .$e->getMessage().<br>;} <?phpecho Hello world!; function dumpThis($sg){//executed since exception was caught foreach($sg as $key => $value){throw new Exception(Oops); echo $key.=.$value.<br>;echo Moien!;//not executed }?> } Loopingfunction whileLoop($num){ dumpThis($_SERVER); while ($num > 0) ?> {echo($num).<br>; $num--;} Miscellanea} Warning – thoughtless use of the features described here could seriously damage your server installation.function doLoop($num){ do{ The prepend operator, @, can be used with constants, echo($num).<br>; variables, function calls, eval and include to suppress $num--; error messages. }while ($num > 0); The backticks operator `returns the results of running a} shell command. For instance, `ls` - dir on Windows – function forLoop($num){ would return a directory listing. This can be assigned to for ($i=0;$i<$num;$i++){ a variable or echoed to standard output. Typing 96 while echo $i.<br>; holding down the ALT key is a keyboard layout } independent way of entering the ` operator.} eval($expr) evaluates the PHP code provided in the break causes immediate termination of the loop. Loop string $expr. The string must be valid PHP code – statements after continue are skipped and the next inclusive of terminating semicolons. Errors in $expr may execution of the loop is performed. cause the parser to die. Code in $expr forms part of the parent script so variable assignments in $expr are function foreachLoopA(){ retained. foreach($GLOBALS as $key => $value){ echo $key.=.$value.<br>; PHP in HTML } The safest way to embed PHP code in HTML is to} delimit it using the <?php...?> tag pair. Other syntax exist but are not accepted by all web servers. The function foreachLoopB(){ resulting file should be saved with the extension .PHP. foreach($_SERVER as $value) echo $value.<br>; 4