Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Introduction. Open Source Open source is a development method for software that harnesses the power of distributed peer review and transparency of.

Similar presentations


Presentation on theme: "PHP Introduction. Open Source Open source is a development method for software that harnesses the power of distributed peer review and transparency of."— Presentation transcript:

1 PHP Introduction

2 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

3 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?

4 What is PHP (cont’d) Interpreted language, scripts are parsed at run- time 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

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

6 Recommended Texts for Learning PHP PHP Manual www.php.netwww.php.net Larry Ullman’s books from the Visual Quickpro series PHP & MySQL for Dummies Beginning PHP 5 and MySQL: 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)

7 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 PHP-GTK 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+ classes and functions and greatly simplifies writing client-side cross-platform GUI applications.

8 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 iPlanet 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 PDF files Flash movies Compression Download and upload XML support

9 PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, 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. e.g. You can use java classes in php.

10 Installation on Linux Ubuntu LAMP Step 1: You start by installing mysql sudo apt-get install mysql-client mysql-server Specify new password for theMySQl “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 Apache2: sudo apt-get install apache2 And you get apache2 installed as well. To double check, point your browser to http://localhost, and you should see the Apache2 placeholder page like this.

11 Cont.. Step 3: To install support for PHP, do the usual sudo apt-get install php5 libapache2-mod-php5 To verify that everything installed correctly and php support is enabled, you need to restart apache by doing this sudo /etc/init.d/apache2 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 <?php phpinfo(); ?> Now open the following page http://localhost/info.php

12 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 MySQL 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 can even choose to assign a random password for it. Once you have made your choice the installation would finish. -Create a directory called phpmyadmin under /var/www. sudo mount --bind /usr/share/phpmyadmin /var/www/phpmyadmin sudo /etc/init.d/apache2 restart you should be able to access phpmyadmin by pointing your web browser to http://localhost/phpmyadmin/

13 Installation on Windows- WAMP Doanload and install wamp server.

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

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

16 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 … ?>

17 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 “ ”; short tags “ ”; ASP tags “ ”; script tags “ ”. The standard and the script tags are guaranteed to work under any configuration, the other two need to be enabled in your “php.ini”

18 php.ini – The configuration file

19 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 */

20 A Sample PHP Script PHP Test <?php echo " Hello World "; phpinfo(); ?> A call to the phpinfo() function returns a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings.

21 Variables in PHP PHP variables must begin with a “$” sign Case-sensitive ($Var != $var != $vAr) 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.

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

23 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 it. e.g. $int_var=15; $str=“string1”;

24 If you want to check out the type and value of a certain variable, use var_dump(). It dumps information about variable. o/p : float(3.1) bool(true) If you want to get type of a variable, then use gettype(). echo gettype($bool); // prints out "boolean“ echo gettype($str); // prints out "string“

25 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 use the settype() function on it. It returns true on success and false on failure. settype($var, "integer");

26 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”; }

27 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. $output "; ?>

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

29 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 arg1 [, string argn...])  In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function

30 Echo example Notice how echo ‘5x5=$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 “\\”) <?php $foo = 25;// Numerical variable $bar = “Hello”;// String variable echo $bar;// Outputs Hello echo $foo,$bar;// Outputs 25Hello echo “5x5=”,$foo;// Outputs 5x5=25 echo “5x5=$foo”;// Outputs 5x5=25 echo ‘5x5=$foo’;// Outputs 5x5=$foo ?>

31 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.

32 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/prog1.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.”);

33 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.

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

35 Concatenation Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1. “ ”. $string2; Print $string3; ?> Hello PHP

36 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”

37 PHP Control Structures  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 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; }

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

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

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

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

42 Syntax: function 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

43 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

44 Functions example <?php // This is a function 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 ?>

45 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: Copyright © 2008-2010 KSU ALL RIGHTS RESERVED URL: http://www.kent.edu

46 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.

47 Syntax to create an array: For simple array: $arr=array(“ele1”,”ele2”,”ele3”); OR $arr[0]=“ele1”; $arr[1]=“ele2”; $arr[2]=“ele3”; OR $arr[]=“ele1”; $arr[]=“ele2”; $arr[]=“ele3”; OR $arr=array( 0 => “ele1”, 1=> “ele2”, 2 => “ele3” ); For associative array : $arr[“key1”]=“val1”; $arr[“key2”]=“val2”; $arr[4]=“val3”; OR $arr=array(“key1”=>”val1”, “key2”=>”val2”, 4 => “val3” );

48 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. print_r( $arr); To retrieve array element: $val=$arr[0]; OR $val=$arr[“key1”]; OR You can assign your array values to list of scalars. list($val1,$val2,$val3)=$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.

49 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.

50 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.

51 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

52 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

53 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

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

55 array_keys() array 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 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 )

56 array_flip () array 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 array_reverse ( array 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 array_merge ( array array1, array array2 [, array...]) It merges two or more arrays. $arr1= (“a”=>1,”b”=>2); $arr2= (“C”=>3, “D”=>4); $arr_result=array_merge($arr1,$arr2); OR $arr_result= $arr1 + $arr2 ;

57 References 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);

58 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: won't unset $b, just $a. Again, it might be useful to think about this as analogous to Unix unlink call.

59 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 client-browser 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 <?php header("Location: message.php"); exit(); ?>

60 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

61  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']

62 $_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.

63 $_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.

64 $_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

65 $_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 $_ENV : It contains variable from environment under which PHP parser is running. e.g. PATH

66 PHP - Forms Access to the HTTP POST and GET data is simple in PHPAccess to the HTTP POST and GET data is simple in PHP The global variables $_POST[] and $_GET[] contain the request dataThe global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo " You clicked Submit! "; else if ($_POST["cancel"]) echo " You clicked Cancel! "; ?>

67 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.

68 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(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire when the user closes browser window.

69 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. website PHP's Sessionseachwebsite PHP's Sessionseach 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.

70 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.

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

72 Avoid Error PHP - Sessions PHP Example: "; session_start(); ?> Error! PHP Example: Correct 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 3session 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 3session

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

74 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.session session_destroy() session NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy.array Here's how we use session_destroy():session_destroy

75 Destroy PHP - Sessions Step 5 - Destroy This Session "; if($_SESSION['name']){ echo "The session is still active"; } else { echo "Ok, the session is no longer active! "; echo " "; } ?>

76 Session Fixation

77 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.

78 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 which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. See also session_save_path(). 4) session.name string session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name(). 5) session.use_cookies boolean session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled). 6) session.use_only_cookies boolean session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0. Defaults to 1 (enabled) since PHP 5.3.0. 7) session.gc_maxlifetime integer session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up.

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

80 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

81 second.php MySQL Table Viewer <?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");

82 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 " Choose one table: "; echo " "; for($i=0; $i<$num_row; $i++) { $tablename=mysql_fetch_row($result); echo " {$tablename[0]} "; } echo " "; mysql_free_result($result); mysql_close($conn); ?>

83 showtable.php MySQL Table Viewer <?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());

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

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

86 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");

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

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

89 Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $fields = mysql_list_fields("database1", "table1", $link); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { echo mysql_field_name($fields, $i). "\n"; } ?>

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

91 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.

92 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]

93 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 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.

94 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:')

95 What is SQL Injection SQL injection refers to the act of someone inserting a MySQL 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 MySQL 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'' The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy. However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query * username = ' ' and then added on to our WHERE statement with an OR clause of 1 (always true). * username = ' ' OR 1 This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!

96 Example: <?php $name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; // our MySQL 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; ?> Becomes: SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' ' If you were run this query, then the injected DELETE statement would completely empty your "customers" table.

97 Injection Prevention - mysql_real_escape_string() What mysql_real_escape_string does is take a string that is going to be used in a MySQL 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 MySQL-safe substitute, an escaped quote \'. <?php //NOTE: you must be connected to the database to use this function! // connect to MySQL $name_bad = "' OR 1'"; $name_bad = mysql_real_escape_string($name_bad); $query_bad = "SELECT * FROM customers WHERE username = '$name_bad'"; echo "Escaped Bad Injection: ". $query_bad. " "; $name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; $name_evil = mysql_real_escape_string($name_evil); $query_evil = "SELECT * FROM customers WHERE username = '$name_evil'"; echo "Escaped Evil Injection: ". $query_evil; ?> Escaped Bad Injection: SELECT * FROM customers WHERE username = '\' OR 1\'' Escaped Evil Injection: SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''

98 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 database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte). An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommended to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using doesn't have an escape function and the DBMS uses \ to escape special chars, you can use this function. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '. The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this. get_magic_quotes_gpc() — Gets the current configuration setting of magic_quotes_gpc <?php $str = "Is your name O'reilly?"; // Outputs: Is your name O\'reilly? echo addslashes($str); ?> stripslashes() — Un-quotes a quoted string

99 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 with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded. URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a + sign. Ex-1: ”> Ex-2: header("Location: user_insert.php?uname = ". urlencode( $str_username ) ); Note: Be careful about variables that match HTML entities. Like & are parsed by the browser. Use htmlentities() for this. Use urldecode() to reverse.

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

101 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: * '&' (ampersand) becomes '&' * '"' (double quote) becomes '"' when ENT_NOQUOTES is not set. * "'" (single quote) becomes ''' only when ENT_QUOTES is set. * '<' (less than) becomes '<' * '>' (greater than) becomes '>' htmlspecialchars_decode( ) — Convert special HTML entities back to characters

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

103 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. a+ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

104 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=“file1.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)

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

106 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 2MB. 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.

107 $_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. This is the name of the file assigned to it while stored in the temporary directory (specified by the PHP directive upload_tmp_dir).

108 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']); } ?>

109 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.

110 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'].

111 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 completely uploaded. This might occur if a network error occurs that results in a disruption of the upload process. UPLOAD_ERR_NO_FILE (Value = 4) A value of 4 is returned if the user submits the form without specifying a file for upload.


Download ppt "PHP Introduction. Open Source Open source is a development method for software that harnesses the power of distributed peer review and transparency of."

Similar presentations


Ads by Google