




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Reference guide to php
Typology: Study Guides, Projects, Research
1 / 163
This page cannot be seen from the preview
Don't miss anything!
PHP Reference: 2008
Beginner to Intermediate PHP
ISBN: 978-1-4357-1590-
Creative Commons Attribution-NonCommercial-ShareAlike 2.
You are free:
to Share — to copy, distribute and transmit the work
to Remix — to adapt the work
Under the following conditions:
Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Noncommercial. You may not use this work for commercial purposes. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights.
FIRST EDITION
http://www.phpreferencebook.com
Cover art credit (PHP REFERENCE:), included with permission:
Leo Reynolds ( www.flickr.com/lwr/ ) - 7 images
Patrick Goor ( www.labworks.eu ) - 3 images
Eva the Weaver ( www.flickr.com/evaekeblad/ ) - 2 images
Duncan Cumming ( www.flickr.com/duncan/ ) - 1 image
Preface
I taught myself PHP and MySQL and found myself, at times, without internet access and thus without search access to the PHP.net manual ( http://www.php.net/manual/en/ ). Since coding was not my primary job, I needed a refresher on syntax, usage, and most of all, a reminder of how to code PHP without spending an hour debugging a silly mistake. I printed out reference sheets, cards, cheat sheets and tried to work off of them exclusively. However, I still found myself needing more than would fit on one page of 8.5" x 11" paper front and back. So, off I went to the web and the local bookstore. After spending some time with a few books, giving them a trial run, I ran into two major problems:
confusing code that did little to explain the what of the function. I figured I couldn't be the only one with this problem, and quickly found out that I wasn't alone thanks to a chance run-in at a local bookstore. Casual PHP programmers, sometimes away from the internet, wanting a quick reference book that assumes they have some experience with PHP and understood the basics while still needing a little clarification sometimes on the details. Therefore, this book was born.
For this edition, I decided to eliminate some of the more advanced aspects of PHP programming: object oriented programming, image manipulation/creation, secondary modules, and a few others. Secondarily, items such as mail handling, file manipulation, regular expressions, MySQL, sessions, and cookies were balanced for complexity and usability, usually excluding the more advanced uses, such as streams. Finally, this book is not an exhaustive collection of every PHP function, but a majority selection of those appropriate for beginner to intermediate programmers. The most common or effective functions are included and some aliases are left out to reduce confusion, such as including is_int() and not is_long().
function name(input, [optional input])
Description/definition
Example: Code with // comments Output of code as seen through a web browser's output
See Also:
function – simplified and relevant definition function – simplified and relevant definition
♣ ♣ ♣
Thanks, and enjoy the show!
{Optional Section} Tip to help with usage or trick on using it Extra code related to the tip Output { [0] => Of [1] => Code }
" " (double quotes) – Variables inside double quotes are evaluated for their values.
Example:
$string = 'Double Quotes'; echo "$string"; Double Quotes
Backslash (Escape Character)
Escapes characters that should be evaluated literally when inside double quotations.
Example:
$string = 'Double Quotes'; echo "$string is set as $string"; $string is set as Double Quotes
Special Characters
backslash ( \ ) question mark (? ) single ( ' ) quotes double ( " ) quotes dollar sign ( $ )
Example:
$string = 'Hello World!'; echo "The variable $string contains ' $string ' " \"; The variable $string contains ' Hello World! ' "
echo 'The variable $string contains ' $string ' " \'; The variable $string contains ' $string ' " \
Comments
Single line, for everything to the right of the double forward slashes: // This is a comment
Multiple lines, opening and closing tags: /* / / This is a comment */
Formatting Characters
\n – New line \r – Carriage return \t – Tab \b – Backspace
define(name, value [, $boolean])
name – $string value – $scalar $boolean – [optional] default: FALSE, case-sensitive
Define a constant, a set value that is assigned globally, making it available to functions and classes without passing them directly as an argument.
Examples: define('HELLO', 'Hello World!'); echo HELLO; Hello World! define('GREETINGS', 'Hello World!', TRUE); echo GREETINGS; echo greetings; Hello World!Hello World!
Functions
function functionname([arguments]) { }
Functions can be placed anywhere in a page and will be available even if called above the actual function being created. The exception to this rule is if the function is only defined as part of a conditional statement, and is not available to be called until that conditional statement has been evaluated.
Examples:
hello(); // Above the conditional statement, this will cause an error if (0==0){ function hello(){ echo 'Hello!'; } } Fatal error: Call to undefined function hello()
exit([$string]) die([$string])
Stops the current script and outputs the optional $string.
Example:
$result = @mysql_connect('db', 'user', 'pw') or die('Unable to connect to database!'); echo 'If it fails, this will never be seen'; Unable to connect to database!
Note: The above output would only display if it failed. If the @ was not present before mysql_connect(), PHP would output a warning as well.
eval($string)
Evaluates a string as if it was code. This can be used to store code in a database and have it processed dynamically by PHP as if it were part of the page. All appropriate aspects of code must be included, such as escaping items with a backslash () and including a semicolon (;) at the end of the string.
Example: $name = 'Mario'; $string = 'My name is $name.'; // Note the single quotes echo $string; $code = "$evalstring = " $string " ;"; // Effect of backslash escape: $code = "$evalstring = " $string " ;"; eval($code); // eval($evalstring = " My name is $name " ;); // $evalstring is the same as $string, except with double quotes now echo $evalstring; My name is $name. My name is Mario.
sleep($integer)
Pauses PHP for $integer amount of seconds before continuing.
Example:
sleep(2); // pause for 2 seconds
If multiple pages will refer to the same functions, create a separate functions.php file (name it whatever you like) and require() or require_once() with pages that will need to use those functions. For speed and file size, page specific functions should be included directly on the necessary page.
usleep($integer)
Pauses PHP for $integer amount of microseconds before continuing.
Example: usleep(1000000); // pause for 1 second
uniqid([$scalar [, entropy]])
entropy – [optional] $boolean default: FALSE, 13 character output
Generate a unique ID based on the $scalar. If no input is given, the current time in microseconds is used automatically. This is best used in combination with other functions to generate a more unique value. If the $scalar is an empty string ('') and entropy is set to TRUE, a 26 character output is provided instead of a 13 character output.
Examples: $id = uniqid(); echo $id; 47cc82c917c $random_id = uniqid(mt_rand()); echo $random_id; 63957259147cc82c917cdb $md5 = md5($random_id); echo $md5; ea573adcdf20215bb391b82c2df3851f
See Also:
md5() – MD5 algorithm based encryption
setcookie(name [, value] [, time] [, path] [, domain] [, secure] [, httponly])
name – $string value – [optional] $string time – [optional] $integer default: till the end of the session path – [optional] $string default: current directory domain – [optional] $string default: current domain (e.g. http://www.example.com) secure – [optional] $boolean default: FALSE, does not require a secure connection httponly – [optional] $boolean default: FALSE, available to scripting languages
get_magic_quotes_gpc()
Returns 0 if it is off, 1 otherwise. Used to determine if magic quotes is on. This check is used for code portability and determining if the addition of backslashes is necessary for security purposes and preventing SQL injection. Magic_quotes_gpc processes GET/POST/Cookie data and, if turned on, automatically processes the above data every time with addslashes().
Example:
if (get_magic_quotes_gpc()){ echo 'Magic Quotes is on!'; }else{ echo 'Magic Quotes is NOT on, use addslashes()!'; } // This is the default setting for PHP5 installations Magic Quotes is NOT on, use addslashes()!
See Also:
addslashes() – Add backslashes to certain special characters in a string stripslashes() – Remove backslashes from certain special characters in a string
phpinfo([option])
option – [optional] Used with a specific $integer or $string to display only a portion of phpinfo(). Specific options excluded for simplicity.
By default, phpinfo() will display everything about the PHP installation, including the modules, version, variables, etc.
Example:
phpinfo();
Display All PHP Errors and Warnings
To catch programming errors, mistakes, or make sure that PHP is not making any assumptions about your code, troubleshooting is best done with all PHP errors being displayed. The following two lines of code will enable this mode:
error_reporting(E_ALL); ini_set('display_errors', '1');
mail(to, subject, message [, headers] [, parameters])
to – $string subject – $string message – $string headers – [optional] $string parameters – [optional] $string
This uses the sendmail binary which may not be configured or available depending on your system/setup. This is included here for basic reference. The configuration and security concerns are outside of the scope of this book. Security consideration: http://www.securephpwiki.com/index.php/Email_Injection
Example:
$to = 'johndoe@example.com'; $subject = 'Hello'; $message = 'Hi John Doe'; $headers = 'From: janedoe@example.com'. "\r\n". 'Reply-To: janedoe@example.com'. "\r\n". 'X-Mailer: PHP/'. phpversion(); mail($to, $subject, $message, $headers);
exec(command [, output] [, return])
command – $string to execute the external program output – [optional] Variable name to assign all the output of the command as an array return – [optional] Variable name to assign the return status as an $integer. Works only when output is also present.
The function will return the last line of the executed program's output. If the program fails to run and both output and return are both present, return will be most commonly set to 0 when successfully executed and 127 when the command fails.
Example (Linux specific program):
$lastline = exec('cal', $output, $return); echo '
'; // For better formatting of print_r() print_r($output); var_dump($lastline, $return);Array ( [0] => March 2008 [1] => Su Mo Tu We Th Fr Sa [2] => 1 [3] => 2 3 4 5 6 7 8
PHP Reference: Beginner to Intermediate PHP
Operators
When comparing or processing variables and other values you use operators. Without them, PHP would be more of a word jumble instead of a language. In some unique cases, operators slightly alter the relationship between two variables or their function within PHP. Without further adieu, here they are.
Basic Operators
Add ( + ): $a = 1; $a = $a + 5; // $a is equal to 6 Subtract ( - ): $s = 10; $s = $s - 5; // $s is equal to 5 Multiply ( * ): $m = 2; $m = $m * 10; // $m is equal to 20 Divide ( / ): $d = 20; $d = $d / 5; // $d is equal to 4 Modulus ( % ) Provides the remainder after division: $u = 5; $u = $u % 2; // $u is equal to 1
Assignment Operators
Add ( += ): $a = 1; $a += 5; // $a is equal to 6 Subtract ( -= ): $s = 10; $s -= 5; // $s is equal to 5 Multiply ( *= ): $m = 2; $m *= 10; // $m is equal to 20 Divide ( /= ): $d = 20; $d /= 5; // $d is equal to 4 Modulus ( %= ) Provides the remainder after division: $u = 5; $u %= 2; // $u is equal to 1
Concatenate ( .= ) Join onto the end of a string: $c = 5; $c .= 2; // $c is now a string, '52'
See Also:
Concatenate – Join together in succession
Mario Lurig
Comparison Operators
Greater Than ( > ): 2 > 1 Less Than ( < ): 1 < 2 Greater Than or Equal To ( >= ): 2 >= 2 3 >= 2 Less Than or Equal To ( <= ): 2 <= 2 2 <= 3
Short-Hand Plus or Minus one
Also known as: Increment ( $integer++; ) Decrement ( $integer--; )
Example: $a = 1; $a = $a + 1; // $a is now equal to 2 $a++; // $a is now equal to 3 $a--; // $a is now equal to 2 again, same as $a = $a – 1;
@ - Suppress Errors
Placing the commercial at symbol (@) before a function tells PHP to suppress any errors generated by that function.
Examples:
include('DoesNotExist.txt'); Warning: include(DoesNotExist.txt) [function.include]: failed to open stream: No such file or directory @include('DoesNotExist.txt'); // blank output below because the error was suppressed
& - Pass by Reference
References allow two variables to refer to the same content. In other words, a variable points to its content (rather than becoming that content). Passing by reference allows two variables to point to the same content under different names. The ampersand ( & ) is placed before the variable to be referenced.
Examples:
$a = 1; $b = &$a; // $b references the same value as $a, currently 1 $b = $b + 1; // 1 is added to $b, which effects $a the same way echo "b is equal to $b, and a is equal to $a"; b is equal to 2, and a is equal to 2