Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Php reference beginner to intermediate php5, Study Guides, Projects, Research of Web Design and Development

Reference guide to php

Typology: Study Guides, Projects, Research

2014/2015

Uploaded on 11/09/2015

Guna.Sai
Guna.Sai 🇮🇳

1 document

1 / 163

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
PHP Reference: Beginner to Intermediate PHP5
PHP Reference: Beginner to
Intermediate PHP5
Mario Lurig
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Php reference beginner to intermediate php5 and more Study Guides, Projects, Research Web Design and Development in PDF only on Docsity!

PHP Reference: Beginner to Intermediate PHP

PHP Reference: Beginner to

Intermediate PHP

Mario Lurig

Mario Lurig

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

Mario Lurig

PHP Reference: Beginner to Intermediate PHP

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:

  1. I spent most of the time weeding through extensive tutorials to find the keyword and answer I was looking for, sometimes fruitlessly.

2. Information was biased or surrounded by irrelevant and often

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().

PHP Reference: Beginner to Intermediate PHP

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 }

Mario Lurig

Mario Lurig

" " (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 */

PHP Reference: Beginner to Intermediate PHP

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()

PHP Reference: Beginner to Intermediate PHP

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.

Mario Lurig

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

Mario Lurig

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');

PHP Reference: Beginner to Intermediate PHP

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