PHP Introduction Open Source Open source is a

  • Slides: 114
Download presentation
PHP Introduction

PHP Introduction

Open Source Open source is a development method for software that harnesses the power

Open Source Open source is a development method for software that harnesses the power of distributed peer review and transparency of process. The promise of open source is better quality, higher reliability, more flexibility, lower cost, and an end to predatory vendor lock-in. Programmers on the Internet can read, redistribute, and modify the source for a piece of software, it evolves People improve it, people adapt it, people fix bugs. And this can happen at a speed that, compared to conventional software development, seems astonishing

What is PHP? PHP == ‘Hypertext Preprocessor’. It was also called 'Personal Home Page'

What is PHP? PHP == ‘Hypertext Preprocessor’. It was also called 'Personal Home Page' origionally. Open-source, server-side scripting language Used to generate dynamic web-pages PHP scripts reside between reserved PHP tags This allows the programmer to embed PHP scripts within HTML pages

What is PHP (cont’d) Interpreted language, scripts are parsed at runtime rather than compiled

What is PHP (cont’d) Interpreted language, scripts are parsed at runtime rather than compiled beforehand Executed on the server-side Source-code not visible by client ‘View Source’ in browsers does not display the PHP code Various built-in functions allow for fast development Compatible with many popular databases

History of PHP PHP began in 1995 when Rasmus Lerdorf developed a Perl/CGI script

History of PHP PHP began in 1995 when Rasmus Lerdorf developed a Perl/CGI script toolset he called the Personal Home Page or PHP 2 released 1997 (PHP now stands for Hypertex Processor). Lerdorf developed it further, using C instead PHP 3 released in 1998 (50, 000 users) PHP 4 released in 2000 (3. 6 million domains). Considered debut of functional language and including Perl parsing, with other major features PHP 5. 0. 0 released July 13, 2004 (113 libraries>1, 000 functions with extensive object-oriented programming) PHP 5. 0. 5 released Sept. 6, 2005 for maintenance and bug fixes

Recommended Texts for Learning PHP Manual www. php. net Larry Ullman’s books from the

Recommended Texts for Learning PHP Manual www. php. net Larry Ullman’s books from the Visual Quickpro series PHP & My. SQL for Dummies Beginning PHP 5 and My. SQL: From Novice to Professional by W. Jason Gilmore (This is more advanced and dense than the others, but great to read once you’ve finished the easier books. One of the best definition/description of object oriented programming I’ve read)

Features of PHP PHP stands for “Hypertext Preprocessor“. It is a widely-used Open Source

Features of PHP PHP stands for “Hypertext Preprocessor“. It is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. It is an interpreted language. There are three main fields where PHP scripts are used: 1. Server side scripting 2. Command line scripting. 3. Writing client-side GUI applications. For this PHPGTK is used. PHP-GTK is an extension for the PHP programming language that implements language bindings for GTK+. It provides an object-oriented interface to GTK+

 PHP can be used on all major operating systems, including Linux, many Unix

PHP can be used on all major operating systems, including Linux, many Unix variants, Microsoft Windows, Mac OS X etc. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and i. Planet servers, Oreilly Website Pro server and many others. You also have the choice of using procedural programming or object oriented programming, or a mixture of them. PHP does more than just generating dynamic web-pages. PHP's abilities includes: Generating images dynamically

 PHP also has support for talking to other services using protocols such as

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP 3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. (Support for web services) PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use CORBA extension to access remote objects.

Installation on Linux Ubuntu LAMP Step 1: You start by installing mysql sudo apt-get

Installation on Linux Ubuntu LAMP Step 1: You start by installing mysql sudo apt-get install mysql-client mysqlserver Specify new password for the. My. SQl “root” user when you asked for. Repeat it for a second time and you would have YSQL server and client installed. Step 2: Next, install Apache 2: sudo apt-get install apache 2 And you get apache 2 installed as well. To double check, point your browser to

Cont. . Step 3: To install support for PHP, do the usual sudo apt-get

Cont. . Step 3: To install support for PHP, do the usual sudo apt-get install php 5 libapache 2 -mod-php 5 To verify that everything installed correctly and php support is enabled, you need to restart apache by doing this sudo /etc/init. d/apache 2 restart Create a test php file called info. php, using a text editor of your choice (say gedit) sudo gedit /var/www/info. php and paste the following content and save the file <? phpinfo();

Cont. . Step 5: Finally install phpmyadmin It would ask if you want to

Cont. . Step 5: Finally install phpmyadmin It would ask if you want to configure it automatically for apache or lightppd choose apache and press Ok. It would be automatically configured, it would also ask for configuring database, choose yet and on next screen you would be asked to enter the My. SQL root password, next it would ask you to enter a password to be used by phpmyadmin to register with the database (basically it would create a user called “phpmyadmin” the password is for that. You

Installation on Windows- WAMP Doanload and install wamp server.

Installation on Windows- WAMP Doanload and install wamp server.

Editors Dreamweaver. Notepad Linux: Install and Access Dreamweaver using Wine. Use gedit.

Editors Dreamweaver. Notepad Linux: Install and Access Dreamweaver using Wine. Use gedit.

Useful Websites php. net mysql. com ubuntu. com/community

Useful Websites php. net mysql. com ubuntu. com/community

What does PHP code look like? Structurally similar to C/C++ Supports procedural and object-oriented

What does PHP code look like? Structurally similar to C/C++ Supports procedural and object-oriented paradigm (to some degree) All PHP statements end with a semi-colon Each PHP script must be enclosed in the reserved PHP tag <? php … ? >

Hello PHP <? php print "Hello World!"; ? > In this script PHP tags

Hello PHP <? php print "Hello World!"; ? > In this script PHP tags are used to separate the actual PHP content from the rest of the file. You can inform the interpreter that you want it to execute your commands by adding a pair of such tags: standard tags “<? php ? >”; short tags “<? ? >”; ASP tags “<% %>”; script tags “<SCRIPT LANGUAGE=”php”> </SCRIPT>”. The standard and the script tags are guaranteed to work under any configuration, the other two need to be enabled in your “php. ini”

php. ini – The configuration file

php. ini – The configuration file

Comments in PHP Standard C, C++, and shell comment symbols // C++ and Java-style

Comments in PHP Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */

A Sample PHP Script <html> <head> <title>PHP Test</title> </head> <body> <? php echo "<p>Hello

A Sample PHP Script <html> <head> <title>PHP Test</title> </head> <body> <? php echo "<p>Hello World</p>"; ? > phpinfo(); </body> </html> A call to the phpinfo() function returns a lot of useful information about your system and setup such as available

Variables in PHP variables must begin with a “$” sign Case-sensitive ($Foo != $f.

Variables in PHP variables must begin with a “$” sign Case-sensitive ($Foo != $f. Oo) Global and locally-scoped variables Global variables can be used anywhere Local variables restricted to a function or class Certain variable names reserved by PHP Form variables ($_POST, $_GET) Server variables ($_SERVER) Etc.

Variable usage <? php $a = 25; // Numerical variable $b = “Hello”; //

Variable usage <? php $a = 25; // Numerical variable $b = “Hello”; // String variable $a = ($a * 7); $b = ($b * 7); ? > // Multiplies foo by 7 // Invalid expression

PHP Data Types PHP provides 8 primitive data-types. Four scalar types: boolean integer float

PHP Data Types PHP provides 8 primitive data-types. Four scalar types: boolean integer float string Two compound types array object Two special types: resource NULL PHP, types are associated with values rather than variables. No previous declaration is needed. You can assign value to variable as and when you need

If you want to check out the type and value of a certain variable,

If you want to check out the type and value of a certain variable, use var_dump(). It dumps information about variable. <? php $b = 3. 1; $c = true; var_dump($b, $c); ? > o/p : float(3. 1) bool(true) If you want to get type of a variable, then use gettype().

To check type of veriables in condition, separate functions are there for each type.

To check type of veriables in condition, separate functions are there for each type. basic syntax is is_type(variable) some of it are is_integer is_float is_numeric is_string is_scalar is_object is_array It returns true if variable will be of that specific type. Otherwise it returns false. If you would like to force a variable to be converted to a certain type, you may either cast the variable or

Operators Arithmetic : +, -, /, %, * String. , . = Assignment operators

Operators Arithmetic : +, -, /, %, * String. , . = Assignment operators for all above operators. +=, -= etc , ++ , -Comparision == , != , <> , >= , <= , === returns true if its two operands are having the same value, and they are of the same type. e. g. $a=15; $b=15; if( $a === $b) { print “Identical variables”; }

Operators PHP supports one execution operator: backquotes (``). PHP will attempt to execute the

Operators PHP supports one execution operator: backquotes (``). PHP will attempt to execute the contents of the backquotes as a system command; the output will be returned in a variable. <? php $output = `ls`; echo "<pre>$output</pre>"; ? >

Control Structures if, elseif while, for , do. . while , foreach , break

Control Structures if, elseif while, for , do. . while , foreach , break , continue , switch $i=1; switch ($i) { case 0: print "i break; case 1: print "i break; case 2: print "i break; default : print "i } equals 0"; equals 1"; equals 2"; equals -1";

Echo The PHP command ‘echo’ is used to output the parameters passed to it

Echo The PHP command ‘echo’ is used to output the parameters passed to it The typical usage for this is to send data to the client’s web-browser Syntax void echo (string arg 1 [, string argn. . . ]) In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function

Echo example <? php $foo = 25; // Numerical variable $bar = “Hello”; //

Echo example <? php $foo = 25; // Numerical variable $bar = “Hello”; // String variable echo echo ? > $bar; // $foo, $bar; // “ 5 x 5=”, $foo; “ 5 x 5=$foo”; // ‘ 5 x 5=$foo’; // Outputs Hello Outputs 25 Hello // Outputs 5 x 5=25 Outputs 5 x 5=$foo Notice how echo ‘ 5 x 5=$foo’ outputs $foo rather than replacing it with 25 Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP This is true for both variables and character escape-sequences (such as “n” or “\”)

print and echo Both are used to print data on screen. Difference between print

print and echo Both are used to print data on screen. Difference between print and echo is that print returns value 1, whereas echo doesn’t return any such value. echo() can take multiple expressions. Print cannot take multiple expressions. echo "The first", "the second"; echo has the slight performance advantage because it doesn't have a return value.

Terminating Execution exit() and die() are used to terminate script execution. exit() takes either

Terminating Execution exit() and die() are used to terminate script execution. exit() takes either string or number as an argument, prints that argument and then terminates execution of script. The die() function is an alias for exit(). $filename = '/path/prog 1. php'; $file = fopen($filename, 'r') or exit("unable to open file ($filename)"); $connection=mysql_connect(“ 192. 168. 0. 1”, ”user”, ”pass”) ; if ( ! $connection ) die (“Connection not established. ”);

Including common file content The include() and require() statements includes and evaluates the specified

Including common file content The include() and require() statements includes and evaluates the specified file. But if included file is not found, then require() will result into fatal error and further execution will stop. Where as include() will just raise a warning and further execution will continue. require_once() and include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

Arithmetic Operations <? php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h 1>$total</h 1>”; //

Arithmetic Operations <? php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h 1>$total</h 1>”; // total is 45 ? > $a - $b $a * $b $a / $b $a += 5 // subtraction // multiplication // division // $a = $a+5 Also works for *= and /=

Concatenation Use a period to join strings into one. <? php $string 1=“Hello”; $string

Concatenation Use a period to join strings into one. <? php $string 1=“Hello”; $string 2=“PHP”; $string 3=$string 1. “ ”. $string 2; Print $string 3; ? > Hello PHP

Escaping the Character If the string has a set of double quotation marks that

Escaping the Character If the string has a set of double quotation marks that must remain visible, use the [backslash] before the quotation marks to ignore and display them. <? php $heading=“”Computer Science””; Print $heading; ? > “Computer Science”

5 -oct-2011 12 -oct-2011

5 -oct-2011 12 -oct-2011

PHP Control Structures: Are the structures within a language that allow us to control

PHP Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script. Grouped into conditional (branching) structures (e. g. if/else) and repetition structures (e. g. while loops). Example if/else statement: if ($foo == 0) { echo ‘The variable foo is equal to 0’; } else if (($foo > 0) && ($foo <= 5)) { echo ‘The variable foo is between 1 and 5’; } else { echo ‘The variable foo is equal to ‘. $foo; }

If. . . Else. . . If (condition) { Statements; } Else { Statement;

If. . . Else. . . If (condition) { Statements; } Else { Statement; } <? php If($user==“John”) { Print “Hello John. ”; } Else { Print “You are not John. ”; } ? > No THEN in PHP

While Loops While (condition) { Statements; } <? php $count=0; While($count<3) { Print “hello

While Loops While (condition) { Statements; } <? php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ? > hello PHP.

Date Display 2009/4/1 Wednesday, April 1, 2009 $datedisplay=date(“Y/m/d”); Print $datedisplay; # If the date

Date Display 2009/4/1 Wednesday, April 1, 2009 $datedisplay=date(“Y/m/d”); Print $datedisplay; # If the date is April 1 st, 2009 # It would display as 2009/4/1 $datedisplay=date(“l, F m, Y”); Print $datedisplay; # If the date is April 1 st, 2009 # Wednesday, April 1, 2009

Month, Day & Date Format Symbols Day of Month d 01 M Jan

Month, Day & Date Format Symbols Day of Month d 01 M Jan

Functions MUST be defined before then can be called Function headers are of the

Functions MUST be defined before then can be called Function headers are of the format function. Name($arg_1, $arg_2, …, $arg_n) Note that no return type is specified Unlike variables, function names are not case sensitive (foo(…) == Fo. O(…))

Syntax: function_name() { /* function statements */ return result; } Function names are case-insensitive.

Syntax: function_name() { /* function statements */ return result; } Function names are case-insensitive. Variables defined in a function are local by default. To access any variable of function out of that function, use global variables. function sum($a, $b) { global $c; $c=$a+$b; } $c=0; sum ( 5 , 1 ); print $c; o/p - > 6

Static Variables If you don't want to alter value of a function’s variable outside

Static Variables If you don't want to alter value of a function’s variable outside your function, and you still want to retain your variable, you can use the static variable. A static variable exists only in a local function scope, but it does not loose its value when program execution leaves this scope. function sum($a, $b) { static $c=0; $c=$a+$b; print “ Value of $c in function is $c n”; } $c=3; sum ( 5 , 1 ); print “ Value of $c outside the function is $c n”; o/p Value of $c in function is 6 Value of $c in outside the function is 3

Functions example <? php // This is a function foo($arg_1, $arg_2) { $arg_2 =

Functions example <? php // This is a function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2; return $arg_2; } $result_1 = foo(12, 3); // Store the function echo $result_1; // Outputs 36 echo foo(12, 3); // Outputs 36 ? >

Include Files Include “opendb. php”; Include “closedb. php”; This inserts files; the code in

Include Files Include “opendb. php”; Include “closedb. php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer. php”); The file footer. php might look like: <hr SIZE=11 NOSHADE WIDTH=“ 100%”> <i>Copyright © 2008 -2010 KSU </i></font> <i>ALL RIGHTS RESERVED</i></font> <i>URL: http: //www. kent. edu</i></font>

Arrays PHP arrays are associative arrays because they associates keys with values. You can

Arrays PHP arrays are associative arrays because they associates keys with values. You can use it either as a simple c like array or as an associative array. Here array indices are enclosed into [ ] Rather than having a fixed number of slots, php creates array slots as new elements are added to the array. You can assign any type for keys and values . such as string, float , integer etc.

Syntax to create an array: For simple array: $arr=array(“ele 1”, ”ele 2”, ”ele 3”);

Syntax to create an array: For simple array: $arr=array(“ele 1”, ”ele 2”, ”ele 3”); OR $arr[0]=“ele 1”; $arr[1]=“ele 2”; $arr[2]=“ele 3”; OR $arr[]=“ele 1”; $arr[]=“ele 2”; $arr[]=“ele 3”; OR $arr=array( 0 => “ele 1” , 1=> “ele 2” , 2 => “ele 3” ); For associative array : $arr[“key 1”]=“val 1”; $arr[“key 2”]=“val 2”; $arr[4]=“val 3”; OR $arr=array(“key 1”=>”val 1” , “key 2”=>”val 2” , 4 => “val 3” );

To create empty array , $arr=array(); After creating array like this, you can add

To create empty array , $arr=array(); After creating array like this, you can add elements using any of the above methods. You can print the array with print_r( $arr); To retrieve array element: $val=$arr[0]; OR $val=$arr[“key 1”]; OR You can assign your array values to list of scalars. list($val 1, $val 2, $val 3)=$arr; List is reverse of array because array packages its arguments into array and list takes array and assign its values to list of individual variables.

is_array() syntax : [true/false] = is_array(array ); If variable is of type array, then

is_array() syntax : [true/false] = is_array(array ); If variable is of type array, then is_array function will return true otherwise false. count() syntax: [no. of eles. ] = count ( array ); It returns number of elements in the given array. in_array() syntax: [true/false] = in_array( array , value ) ; It checks if value exists in given array or not. Isset ( $arr[$key] ). Returns true if key $key exists in array.

Functions to traverse through an array: current() function returns stored value that the current

Functions to traverse through an array: current() function returns stored value that the current pointer points to. Initially, current() will point to the first element in the array. next(array) function Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements. reset() function sets the pointer to the first element & returns the stored value. prev() sets the pointer to the previous element. end() sets the pointer to the last element. key() returns key of current element. each() returns the current key and value pair from an array and advances the array pointer.

e. g. $transport = array(‘bus', 'bike', 'car', 'plane'); $mode = current($transport); // $mode =

e. g. $transport = array(‘bus', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = ‘bus'; $mode = next($transport); // $mode = 'bike'; $mode = current($transport); // $mode = 'bike'; $mode = prev($transport); // $mode = ‘bus'; $mode = end($transport); // $mode = ‘plane'; $array_cell=each($transport); // $array_cell[‘key’] will be 3 and // $array_cell[‘value’] will be plane

Traversing an array with while loop. $arr = array("one", "two", "three"); reset ($arr); while

Traversing an array with while loop. $arr = array("one", "two", "three"); reset ($arr); while (list( , $value) = each ($arr)) { echo "Value: $value n"; } reset ($arr); foreach ($arr as $value) { echo "Value: $value n"; } For both loops , o/p Value: one Value: two Value: three

Traversing an associative array with loop. $a = array ( "one" => 1, "two"

Traversing an associative array with loop. $a = array ( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); while (list( $key , $value) = each ($a)) { echo “$key => $value n"; } reset($a); foreach ($a as $key => $value ) { print "$a[$key] => $value. n"; } o/p one => 1 two => 2 three => 3

Why 1 is one and 0 is zero Look at this. . !!!

Why 1 is one and 0 is zero Look at this. . !!!

array_keys() array_keys ( array input [, mixed search_value]) array_keys() returns the keys from the

array_keys() array_keys ( array input [, mixed search_value]) array_keys() returns the keys from the input array. If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. array_values () array_values ( array input) array_values() returns all the values from the input array and indexes the array numerically. array_count_values () $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); Returns an array using the values of the input array as keys and their frequency as values. o/p Array ( [1] => 2 , [hello] => 2 , [world] => 1 )

array_flip () array_flip ( array trans) Exchanges all keys with their associated values in

array_flip () array_flip ( array trans) Exchanges all keys with their associated values in an array If a value has several occurrences, the latest key will be used as its values, and all others will be lost. array_flip() returns FALSE if it fails. $trans = array("a" => 1, "b" => 1, "c" => 2); $trans = array_flip($trans); o/p -> 1=>b , 2=>c array_reverse () array_reverse ( array [, bool preserve_keys]) array_reverse() takes input array and returns a new array with the order of the elements reversed, preserving the keys if preserve_keys is TRUE. array_merge () array_merge ( array 1, array 2 [, array. . . ]) It merges two or more arrays. $arr 1= (“a”=>1, ”b”=>2); $arr 2= (“C”=>3, “D”=>4); $arr_result=array_merge($arr 1, $arr 2); OR $arr_result= $arr 1 + $arr 2 ;

References in PHP are means to access the same variable content by different names.

References in PHP are means to access the same variable content by different names. They are not like C pointers. PHP references allow you to make two variables to refer to the same content. Meaning, when you do: $a =& $b ; Pass by reference: function add( &$var) { $var++; } $a=5; add($a);

References. . . When you unset the reference, you just break the binding between

References. . . When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example: <? php $a = 1; $b =& $a; unset ($a); ? > won't unset $b, just $a. Again, it might be useful to think about this as analogous to Unix unlink call.

Header function In a network transmission, a header is part of the data packet

Header function In a network transmission, a header is part of the data packet and contains transparent information about the file or the transmission. Headers can be separated in 2 main types: 1) request header 2) response header Request header is sent by client browser to web-server when client browser makes request for any web-page Response header is sent from web-server to clientbrowser when it serves the file requested by the client. header function in php sends response header to client. Http response header has so many fields through which you can control output of the response page. In php, header function allows you to set these fields. Location – For page redirection

Super Global Arrays All variables that come into PHP arrive inside one of several

Super Global Arrays All variables that come into PHP arrive inside one of several special arrays known collectively as the superglobals. They're called superglobal because they are available everywhere in your script, even inside classes and functions

track_vars setting is on in the php. ini file: GET, and POST variables (among

track_vars setting is on in the php. ini file: GET, and POST variables (among others) will be available through global arrays: $HTTP_POST_VARS and $HTTP_GET_VARS. For example: $HTTP_POST_VARS["name"]. Note: these arrays are not global. register_globals setting is on in the php. ini: GET and POST variables will be available in the format of standard variables. For example: $name. Variables passed from forms are automatically part of the global namespace. register_globals and track_vars are on in the php. ini: variables are available in both forms. PHP version 4. 1. 0 and higher: Due to security concerns, register_globals is being deprecated. Though still on in default configurations of 4. 1. 0, following releases will not have the setting enabled. New, shorter, arrays have been introduced to replace the old $HTTP_POST_* arrays: $_GET, $_POST. These arrays are also automatically global. For Example: $_POST['name']

$_GET -- Contains all variables sent via a HTTP GET request. That is, sent

$_GET -- Contains all variables sent via a HTTP GET request. That is, sent by way of the URL. $_POST --- Contains all variables sent via a HTTP POST request. $_FILES --- Contains all variables sent via a HTTP POST file upload. $_COOKIE --- Contains all variables sent via HTTP cookies.

$_REQUEST --- Contains all variables sent via HTTP GET, HTTP POST, and HTTP cookies.

$_REQUEST --- Contains all variables sent via HTTP GET, HTTP POST, and HTTP cookies. This is basically the equivalent of combining $_GET, $_POST, and $_COOKIE. However, as it does contain all variables from untrusted sources (that is, your visitors). $_SESSION ---- Contains all variables stored in a user's session. $_SERVER ---- Contains all variables set by the web server you are using, or other sources that directly relate to the execution of your script. $_ENV --- Contains all environment variables set by your system or shell for the script.

$_SERVER The $_SERVER superglobal gives access to the Server attributes and a few HTTP

$_SERVER The $_SERVER superglobal gives access to the Server attributes and a few HTTP request attributes. The complete list of keys that are currently supported includes : $_SERVER['DOCUMENT_ROOT'] Path to the application's root $_SERVER['HTTP_HOST'] The value of the Host header $_SERVER['HTTP_REFERER'] The value of the Referer header $_SERVER['HTTP_USER_AGENT'] The value of the User-Agent header $_SERVER['HTTPS'] The value 'https' if the request was made using the https transport $_SERVER['REMOTE_ADDR'] The IP address of the client making the request $_SERVER['REMOTE_PORT] The port number of the client making the request $_SERVER['SCRIPT_FILENAME'] The file name of the script being invoked $_SERVER['SCRIPT_NAME'] The name of the script being invoked $_SERVER['SERVER_PORT'] The port number that the server accepted the request on $_SERVER['REQUEST_METHOD'] The HTTP method of the request $_SERVER['REQUEST_URI'] The URI associated with the HTTP request

$_SERVER is an array containing information such as headers, paths and script locations. So

$_SERVER is an array containing information such as headers, paths and script locations. So it will depend on web server’s configuration. e. g. PHP_SELF SERVER_ADDR SERVER_NAME QUERY_STRING REQUEST_METHOD REMOTE_ADDR SCRIPT_NAME

PHP - Forms • Access to the HTTP POST and GET data is simple

PHP - Forms • Access to the HTTP POST and GET data is simple in PHP • The global variables $_POST[] and $_GET[] contain the request data <? php if ($_POST["submit"]) echo "<h 2>You clicked Submit!</h 2>"; else if ($_POST["cancel"]) echo "<h 2>You clicked Cancel!</h 2>"; ? > <form action="form. php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form>

Cookies PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in

Cookies PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser. You can set cookies using the setcookie() function. $_COOKIE auto-global array will always be set with any cookies sent from the client.

Cookie bool setcookie (name , [value], [expire], [path], [domain], [secure] ) Cookies are part

Cookie bool setcookie (name , [value], [expire], [path], [domain], [secure] ) Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. Expire time is time() function plus the number of seconds before you want it to expire. Or you can use mktime().

WHY PHP – Sessions ? Whenever you want to create a website that allows

WHY PHP – Sessions ? Whenever you want to create a website that allows you to store and display information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features. Cookies are about 30% unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there. PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99% flawless in operation and it is virtually invisible to the user.

Session Handling Session support in PHP consists of a way to preserve certain data

Session Handling Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session. auto_start is set to 1) or on your request (explicitly through session_start() ) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

PHP – Sessions & Variables • Sessions store their identifier in a cookie in

PHP – Sessions & Variables • Sessions store their identifier in a cookie in the client’s browser • Every page that uses session data must be proceeded by the session_start() function • Session variables are then set and retrieved by accessing the global $_SESSION[] • Save it as session. php <? php session_start(); if (!$_SESSION["count"]) $_SESSION["count"] = 0; if ($_GET["count"] == "yes") $_SESSION["count"] = $_SESSION["count"] + 1; echo "<h 1>". $_SESSION["count"]. "</h 1>"; ? > <a href="session. php? count=yes">Click here to count</a>

Avoid Error PHP - Sessions PHP Example: <? php echo "Look at this nasty

Avoid Error PHP - Sessions PHP Example: <? php echo "Look at this nasty error below: <br />"; session_start(); ? > Error! Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error. php: 2) in session_header_error/session_error. php on line 3 Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error. php: 2) in session_header_error/session_error. php on line 3 PHP Example: <? php session_start(); echo "Look at this nasty error below: "; ? > Correct

Unregistering Session Variables To destroy one var, unset() To destroy all vars, use session_unset()

Unregistering Session Variables To destroy one var, unset() To destroy all vars, use session_unset() <? php session_start(); unset($_SESSION['count']); ? >

Destroy PHP - Sessions Destroying a Session why it is necessary to destroy a

Destroy PHP - Sessions Destroying a Session why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Well, imagine that you had a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called session_destroy() comes in handy. session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session. NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy. Here's how we use session_destroy():

Destroy PHP - Sessions <? php // start the session_start(); $_SESSION = array(); session_destroy();

Destroy PHP - Sessions <? php // start the session_start(); $_SESSION = array(); session_destroy(); echo "<strong>Step 5 - Destroy This Session </strong><br />"; if($_SESSION['name']){ echo "The session is still active"; } else { echo "Ok, the session is no longer active! <br />"; echo "<a href="page 1. php"><< Go Back Step 1</a>"; } ? >

Session Fixation

Session Fixation

session_id() returns user's current session id. session_regenerate_id() Update the current session id with a

session_id() returns user's current session id. session_regenerate_id() Update the current session id with a newly generated one session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

Session configuration in php. ini 1) session. save_handler string session. save_handler defines the name

Session configuration in php. ini 1) session. save_handler string session. save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. 2) session. auto_start boolean session. auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled). 3) session. save_path string session. save_path defines the argument

My. SQL Database Connectivity mysql_connect -- Open a connection to a My. SQL Server

My. SQL Database Connectivity mysql_connect -- Open a connection to a My. SQL Server resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]]) Returns a My. SQL link identifier on success, or FALSE on failure. mysql_error -- Returns the text of the error message from previous My. SQL operation mysql_errno -- Returns the numerical value of the error message from previous My. SQL operation mysql_insert_id -- Get the ID generated from

Example – show data in the tables Function: list all tables in your database.

Example – show data in the tables Function: list all tables in your database. Users can select one of tables, and show all contents in this table. second. php showtable. php

second. php <html><head><title>My. SQL Table Viewer</title></head><body> <? php // change the value of $dbuser

second. php <html><head><title>My. SQL Table Viewer</title></head><body> <? php // change the value of $dbuser and $dbpass to your username and password $dbhost = 'hercules. cs. kent. edu: 3306'; $dbuser = 'nruan'; $dbpass = ‘*********’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: '. mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database");

second. php (cont. ) $result = mysql_query("SHOW TABLES"); if (!$result) { die("Query to show

second. php (cont. ) $result = mysql_query("SHOW TABLES"); if (!$result) { die("Query to show fields from table failed"); } $num_row = mysql_num_rows($result); echo "<h 1>Choose one table: <h 1>"; echo "<form action="showtable. php" method="POST">"; echo "<select name="table" size="1" Font size="+2">"; for($i=0; $i<$num_row; $i++) { $tablename=mysql_fetch_row($result); echo "<option value="{$tablename[0]}" >{$tablename[0]}</option>"; } echo "</select>"; echo "<div><input type="submit" value="submit"></div>"; echo "</form>"; mysql_free_result($result); mysql_close($conn); ? > </body></html>

showtable. php <html><head> <title>My. SQL Table Viewer</title> </head> <body> <? php $dbhost = 'hercules.

showtable. php <html><head> <title>My. SQL Table Viewer</title> </head> <body> <? php $dbhost = 'hercules. cs. kent. edu: 3306'; $dbuser = 'nruan'; $dbpass = ‘*****’; $dbname = 'nruan'; $table = $_POST[“table”]; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) die('Could not connect: '. mysql_error()); if (!mysql_select_db($dbname)) die("Can't select database"); $result = mysql_query("SELECT * FROM {$table}"); if (!$result) die("Query to show fields from table failed!". mysql_error());

showtable. php (cont. ) $fields_num = mysql_num_fields($result); echo "<h 1>Table: {$table}</h 1>"; echo "<table

showtable. php (cont. ) $fields_num = mysql_num_fields($result); echo "<h 1>Table: {$table}</h 1>"; echo "<table border='1'><tr>"; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td><b>{$field->name}</b></td>"; } echo "</tr>n"; while($row = mysql_fetch_row($result)) { echo "<tr>"; // $row is array. . . foreach(. . ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>"; echo "</tr>n"; } mysql_free_result($result); mysql_close($conn); ? > </body></html>

Functions Covered mysql_connect() include() mysql_query() mysql_fetch_array() mysql_select_db() mysql_num_rows() mysql_close()

Functions Covered mysql_connect() include() mysql_query() mysql_fetch_array() mysql_select_db() mysql_num_rows() mysql_close()

Retrieving Table Information mysql_list_fields(database, table, link) For a select query it retrieves information from

Retrieving Table Information mysql_list_fields(database, table, link) For a select query it retrieves information from given table in given database. link is optional The returned resource can be used to obtain properties of the table such as names of the table columns and field type information Example $fields = mysql_list_fields("web_db", "books");

Number Of Table Columns mysql_num_fields(result) return the numbers of columns in a table result

Number Of Table Columns mysql_num_fields(result) return the numbers of columns in a table result is the resource returned by a call to the mysql_list_fields function Example $fields = mysql_list_fields("web_db", "books"); $num_columns = mysql_num_fields($fields);

Names Of Table Columns mysql_field_name(result, index) return the name of the table column whose

Names Of Table Columns mysql_field_name(result, index) return the name of the table column whose position is given by index (0, 1, . . . ) result is the resource returned by a call to mysql_list_fields Example: the first column name $fields = mysql_list_fields("web_db", "books"); $isbn = mysql_field_name($fields, 0);

Example <? php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $fields = mysql_list_fields("database 1", "table 1",

Example <? php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $fields = mysql_list_fields("database 1", "table 1", $link); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { echo mysql_field_name($fields, $i). "n";

mysql_affected_rows(result) used after an INSERT, UPDATE, or DELETE query to return the number of

mysql_affected_rows(result) used after an INSERT, UPDATE, or DELETE query to return the number of rows affected result is the resource returned

mysql_free_result(result) free memory associated with the given resource called result (after a select query).

mysql_free_result(result) free memory associated with the given resource called result (after a select query). Not necessary except for large result sets Done automatically when script exits. mysql_close(link) close the database connection associated with the given link doesn't do anything for persistent links.

LIMIT • This can be used to limit the amount of rows. LIMIT 10

LIMIT • This can be used to limit the amount of rows. LIMIT 10 19 • This is useful it web sites where you show a selection of the results. SELECT [options] columns [INTO file_details] FROM table [WHERE conditions] [GROUP BY group_type] [HAVING where_definitions] [ORDER BY order_type] [LIMIT limit_criteria]

Error Supression The function mentioned in this library usually report any error that has

Error Supression The function mentioned in this library usually report any error that has occurred. It can be useful to suppress such errors with the PHP error suppression operator @. @function() will run the function without reporting mistakes. You can then create your own customized mistakes by checking for errors every time you run a mysqli function. This is useful.

Passing Data in pages & Page flow - Post data through form (html elements

Passing Data in pages & Page flow - Post data through form (html elements and hidden field) - Get data through form (html elements and hidden field) - Passing data through query string in URL - In hyperlink - In header('location: ')

What is SQL Injection SQL injection refers to the act of someone inserting a

What is SQL Injection SQL injection refers to the act of someone inserting a My. SQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a My. SQL statement that you will unknowingly run on your database. Example: Normal: SELECT * FROM customers WHERE username = 'timmy' Injection: SELECT * FROM customers WHERE username = '' OR 1''

Example: <? php $name_evil = "'; DELETE FROM customers WHERE 1 or username =

Example: <? php $name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; // our My. SQL query builder really should check for injection $query_evil = "SELECT * FROM customers WHERE username = '$name_evil'"; // the new evil injection query would include a DELETE statement echo "Injection: ". $query_evil; ? >

Injection Prevention - mysql_real_escape_string() What mysql_real_escape_string does is take a string that is going

Injection Prevention - mysql_real_escape_string() What mysql_real_escape_string does is take a string that is going to be used in a My. SQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a My. SQL-safe substitute, an escaped quote '. <? php //NOTE: you must be connected to the database to use this function! // connect to My. SQL

One more solution to SQL Injection: addslashes(), get_magic_quotes_gpc() and stripslashes() addslashes() — Quote string

One more solution to SQL Injection: addslashes(), get_magic_quotes_gpc() and stripslashes() addslashes() — Quote string with slashes string addslashes ( string $str ) Returns a string with backslashes before characters that need to be quoted in

urlencode() and urldecode() string urlencode ( string str) URL encoding converts characters into a

urlencode() and urldecode() string urlencode ( string str) URL encoding converts characters into a format that can be transmitted over the Internet. Returns a string in which all non -alphanumeric characters except -_. have been replaced

Note: The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element

Note: The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

htmlspecialchars() Certain characters have special significance in HTML, and should be represented by HTML

htmlspecialchars() Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead. The translations performed are:

htmlentities() and html_entity_decode() htmlentities()— Convert all applicable characters to HTML entities html_entity_decode — Convert

htmlentities() and html_entity_decode() htmlentities()— Convert all applicable characters to HTML entities html_entity_decode — Convert all HTML entities to their applicable characters

Files $fp=fopen(filepath, mode); r Open for reading only; place the file pointer at the

Files $fp=fopen(filepath, mode); r Open for reading only; place the file pointer at the beginning of the file. r+ Open for reading and writing; place the file pointer at the beginning of the file. w Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. w+ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. a Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

fread(file_handle, number_of_bytes) Reads up to length bytes from the file pointer referenced by handle

fread(file_handle, number_of_bytes) Reads up to length bytes from the file pointer referenced by handle and return that content into string. $file=“file 1. php”; $fp=fopen($file, ”r”); $str=fread($fp, 20); fwrite (filehandle, string) Writes the contents of string to the file stream pointed to by handle. fclose (filehandle)

is_file(filename) is_link(filename) is_readable(filename) is_writable(filename) is_dir() unlink() realpath(relative_path) mkdir(dirpath) filesize() file_exists() copy(source, dest) fpassthru(file_handle)

is_file(filename) is_link(filename) is_readable(filename) is_writable(filename) is_dir() unlink() realpath(relative_path) mkdir(dirpath) filesize() file_exists() copy(source, dest) fpassthru(file_handle)

File Uploads Managing file uploads via PHP is the result of cooperation between various

File Uploads Managing file uploads via PHP is the result of cooperation between various configuration directives and the $_FILES superglobal array. Directives in php. ini file_uploads (boolean) It determines whether PHP scripts on the server can accept file uploads. max_execution_time (integer) Default value: 30 It directive determines the maximum amount of time, in seconds, that a PHP script will execute before registering a fatal error. upload_max_filesize (integer) The upload_max_filesize directive determines the maximum size, in megabytes, of an uploaded file. Default is 2 MB. upload_tmp_dir (string) Before subsequent processing on the uploaded file can begin, a staging area of sorts must be designated for such files as the location where they can be temporarily placed until moved to their final location. This location is specified using the this directive.

$_FILES Uploaded files’ information is stored in $_FILES array which is two dimentional array.

$_FILES Uploaded files’ information is stored in $_FILES array which is two dimentional array. 1) $_FILES['userfile']['name'] The $_FILES['userfile']['name'] variable specifies the original name of the file, including the extension, as declared on the client machine. Therefore, if you browse to a file named vacation. jpg, and upload it via the form, this variable will be assigned the value vacation. jpg. 2 $_FILES['userfile']['size'] The $_FILES['userfile']['size'] variable specifies the size, in bytes, of the file uploaded from the client machine. Therefore, in the case of the vacation. jpg file, this variable could plausibly be assigned a value like 5253, or roughly 5 kilobytes. 3) $_FILES['userfile']['tmp_name'] The $_FILES['userfile']['tmp_name'] variable specifies the temporary name assigned to the file once it has been uploaded to the server.

4) $_FILES['userfile']['type'] The $_FILES['userfile']['type'] variable specifies the mime-type of the file uploaded from the

4) $_FILES['userfile']['type'] The $_FILES['userfile']['type'] variable specifies the mime-type of the file uploaded from the client machine. Therefore, in the case of the vacation. jpg file, this variable would be assigned the value image/jpeg. If a PDF were uploaded, then the value application/pdf would be assigned. 5) $_FILES['userfile']['error'] The $_FILES['userfile']['error'] array value offers important information pertinent to the outcome of the upload attempt. In total, five return values are possible, one signifying a successful outcome, and four others denoting specific errors which arise from the attempt. is_uploaded_file(file) <? php if (is_uploaded_file($_FILES['classnotes']['tmp_name'])) { copy($_FILES['classnotes']['tmp_name'], $_FILES['classnotes']['name']); } ? >

move_uploaded_file() move_uploaded_file(uploaded_file, d estionation) This function checks to ensure that the file designated by

move_uploaded_file() move_uploaded_file(uploaded_file, d estionation) This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

Upload error messages Like any other application component involving user interaction, you need a

Upload error messages Like any other application component involving user interaction, you need a means to assess the outcome, successful or otherwise. How do you definitively know that the file-upload procedure was successful? And if something goes awry during the upload process, how do you know what caused the error? Thankfully, sufficient information for determining the outcome, and in the case of an error, the reason for the error, is provided in $_FILES['userfile']['error'].

UPLOAD_ERR_OK (Value = 0) A value of 0 is returned if the upload is

UPLOAD_ERR_OK (Value = 0) A value of 0 is returned if the upload is successful. UPLOAD_ERR_INI_SIZE (Value = 1) A value of 1 is returned if there is an attempt to upload a file whose size exceeds the specified by the upload_max_filesize directive. UPLOAD_ERR_FORM_SIZE (Value = 2) A value of 2 is returned if there is an attempt to upload a file whose size exceeds the value of the MAX_FILE_SIZE directive, which can be embedded into the HTML form. UPLOAD_ERR_PARTIAL (Value = 3) A value of 3 is returned if a file was not