PHPPHP Hypertext Preprocessor Introduction PHP or PHP Hypertext

  • Slides: 77
Download presentation
PHP-"PHP Hypertext Preprocessor"

PHP-"PHP Hypertext Preprocessor"

Introduction PHP, or PHP Hypertext Preprocessor, is one of the most popular server side

Introduction PHP, or PHP Hypertext Preprocessor, is one of the most popular server side scripting languages for creating dynamic Web pages. PHP was created in 1994 by Rasmus Lerdorf In 1995, Lerdorf released it as a package called the “Personal Home Page Tools. ” PHP 2 featured built-in database support and form handling. In 1997, PHP 3 was released, featuring a rewritten parser, increased performance and led to an explosion in PHP use. It is estimated that over six million domains now use PHP. The release of PHP 4, which features the new Zend Engine and is much faster and more powerful than its predecessor More information about the Zend engine can be found at www. zend. com

Introduction PHP, or PHP Hypertext Preprocessor, is one of the most popular server side

Introduction PHP, or PHP Hypertext Preprocessor, is one of the most popular server side scripting languages for creating dynamic Web pages. The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

Introduction PHP is an open-source technology that is supported by a large community of

Introduction PHP is an open-source technology that is supported by a large community of users and developers. Open source software provides developers with access to the software’s source code and free redistribution rights. PHP is platform independent; implementations exist for all major UNIX, Linux and Windows operating systems. PHP also provides support for a large number of databases, including My. SQL

What is PHP? PHP is an acronym for "PHP Hypertext Preprocessor" PHP is a

What is PHP? PHP is an acronym for "PHP Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP costs nothing, it is free to download and use

What is a PHP File? PHP files can contain text, HTML, CSS, Java. Script,

What is a PHP File? PHP files can contain text, HTML, CSS, Java. Script, and PHP code are executed on the server, and the result is returned to the browser as plain HTML PHP files have extension ". php"

What Can PHP Do? PHP can generate dynamic page content PHP can create, open,

What Can PHP Do? PHP can generate dynamic page content PHP can create, open, read, write, and close files on the server PHP can collect form data PHP can send and receive cookies PHP can add, delete, modify data in your database PHP can restrict users to access some pages on your website PHP can encrypt data

PHP 5 Syntax The PHP script is executed on the server, and the plain

PHP 5 Syntax The PHP script is executed on the server, and the plain HTML result is sent back to the browser. A PHP script can be placed anywhere in the document. A PHP script starts with <? php and ends with ? >: <? php // PHP code goes here ? >

Comments in PHP <!DOCTYPE html> <body> <? php // This is a single line

Comments in PHP <!DOCTYPE html> <body> <? php // This is a single line comment # This is also a single line comment /* This is a multiple lines comment block that spans over more than one line */ ? > </body> </html>

PHP Introduction PHP scripts are executed on the server. PHP code is embedded directly

PHP Introduction PHP scripts are executed on the server. PHP code is embedded directly into XHTML documents. <!DOCTYPE html> <body> <h 1>My first PHP page</h 1> <? php echo “ Hello World !"; ? > </body> </html>

PHP 5 Variables are "containers" for storing information: PHP variables are "multitype” A variable

PHP 5 Variables are "containers" for storing information: PHP variables are "multitype” A variable starts with the<!DOCTYPE html> $ sign, followed by the <html> name of the variable <body> <? php $x=5; $y=6; $z=$x+$y; echo $z; ? > </body> </html>

PHP 5 echo and print Statements In PHP there is two basic ways to

PHP 5 echo and print Statements In PHP there is two basic ways to get output: echo and print. echo - can output one or more strings echo "This ", "string ", "was ", "made ", "with multiple parameters. "; print - can only output one string, and returns always 1 print $x + $y; echo is marginally faster compared to print as echo does not return any value.

PHP Data Types String, Integer, Floating point numbers, Boolean, Array, Object, NULL. PHP Strings

PHP Data Types String, Integer, Floating point numbers, Boolean, Array, Object, NULL. PHP Strings A string is a sequence of characters, like "Hello world!". A string can be any text inside quotes. You can use single or double quotes: <? php $x = "Hello world!"; echo $x; echo " "; $x = 'Hello world!'; echo $x; ? >

PHP Data Types PHP Integers (the PHP var_dump() function returns the data type and

PHP Data Types PHP Integers (the PHP var_dump() function returns the data type and value of variables) <? php $x = 20. 10; var_dump($x); float 20. 10 PHP Floating Point Numbers <? php $x = 10. 365; var_dump($x); PHP Booleans $x=true; $y=false; var_dump($x);

Demonstrates the PHP data types <? php $test. String = "3. 5 seconds"; $test.

Demonstrates the PHP data types <? php $test. String = "3. 5 seconds"; $test. Double = 79. 2; $test. Integer = 12; ? > <? php print( $test. String ) ? > is a string. <br /> 24 <? php print( $test. Double ) ? > is a double. 25 <? php print( $test. Integer ) ? > is an integer.

 <? php print( "$test. String" ); settype( $test. String, "double" ); print( "

<? php print( "$test. String" ); settype( $test. String, "double" ); print( " as a double is $test. String " ); print( "$test. String" ); settype( $test. String, "integer" ); print( " as an integer is $test. String " ); settype( $test. String, "string" ); print( "Converting back to a string results in $test. String " );

 $data = "98. 6 degrees"; print( "Now using type casting instead: <br />

$data = "98. 6 degrees"; print( "Now using type casting instead: <br /> As a string - ". (string) $value. " As a double - ". (double) $value. " As an integer - ". (integer) $value ); ? >

Set a PHP Constant To set a constant, use the define() function it takes

Set a PHP Constant To set a constant, use the define() function it takes three parameters: The first parameter defines the name of the constant, the second parameter defines the value of the constant, and the optional third parameter specifies whether the constant name should be caseinsensitive.

function define to create a named constant. <? php define("name", "5"); echo name+10; ?

function define to create a named constant. <? php define("name", "5"); echo name+10; ? > In PHP, uninitialized variables have the value undef, which evaluates to different values, depending on its context.

PHP Data Types PHP Arrays $second = array( "zero", "one", "two", "three" ); for

PHP Data Types PHP Arrays $second = array( "zero", "one", "two", "three" ); for ( $i = 0; $i < count( $second ); $i++ ) print( "Element $i is $second[$i] " ); $first[ 0 ] = "zero"; $first[ 1 ] = "one"; $first[ 2 ] = "two"; 21 $first[] = "three";

assign values to non-numerical indices $third[ "Harvey" ] = 21; $third[ "Paul" ] =

assign values to non-numerical indices $third[ "Harvey" ] = 21; $third[ "Paul" ] = 18; $third[ "Tem" ] = 23; for ( reset( $third ); $element = key( $third ); next( $third ) ) print( "$element is $third[$element] " ); Function reset sets the iterator to the first element of the array. Function key returns the index of the element to which the iterator points, and function next moves the iterator to the next element.

 The for loop continues to execute as long as function key returns an

The for loop continues to execute as long as function key returns an index. The foreach loop is a control structure that is specially designed for iterating through arrays. The syntax for a foreach loop starts with the array to iterate through, followed by the keyword as, followed by the variables to receive the index and the value for each element.

$fourth = array( "January" => "first", "February" => "second", "March" => "third", "April" =>

$fourth = array( "January" => "first", "February" => "second", "March" => "third", "April" => "fourth", "May" => "fifth", "June" => "sixth", "July" => "seventh", "August" => "eighth", "September" => "ninth", "October" => "tenth", "November" => "eleventh", "December" => "twelfth“ ); // print each element’s name and value foreach ( $fourth as $element => $value ) print( "$element is the $value month " );

PHP Control Stuctures PHP Conditional Statements if statement - executes some code only if

PHP Control Stuctures PHP Conditional Statements if statement - executes some code only if a specified condition is true if. . . else statement - executes some code if a condition is true and another code if the condition is false if. . . elseif. . else statement - selects one of several blocks of code to be executed switch statement - selects one of many blocks of code to be executed

PHP Loops while - loops through a block of code as long as the

PHP Loops while - loops through a block of code as long as the specified condition is true do. . . while - loops through a block of code once, and then repeats the loop as long as the specified condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array <? php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value "; }

PHP User Defined Functions A function is a block of statements that can be

PHP User Defined Functions A function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads. A function will be executed by a call to the function.

A user defined function declaration starts with the word "function": Syntax function. Name() {

A user defined function declaration starts with the word "function": Syntax function. Name() { code to be executed; }

PHP User Defined Functions <? php function write. Msg() { echo "Hello world!"; }

PHP User Defined Functions <? php function write. Msg() { echo "Hello world!"; } write. Msg(); // call the function ? >

PHP Function Arguments Information can be passed to functions through arguments. An argument is

PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

<? php function family. Name($fname) { echo "$fname Refsnes. "; } family. Name("Jani"); family.

<? php function family. Name($fname) { echo "$fname Refsnes. "; } family. Name("Jani"); family. Name("Hege"); family. Name("Stale"); family. Name("Kai Jim"); family. Name("Borge"); ? >

The following example has a function with two arguments ($fname and $year): <? php

The following example has a function with two arguments ($fname and $year): <? php function family. Name($fname, $year) { echo "$fname Refsnes. Born in $year "; } family. Name("Hege", "1975"); family. Name("Stale", "1978"); family. Name("Kai Jim", "1983"); ? >

PHP Default Argument Value The following example shows how to use a default parameter.

PHP Default Argument Value The following example shows how to use a default parameter. If we call the function set. Height() without arguments it takes the default value as argument: <? php function set. Height($minheight = 50) { echo "The height is : $minheight "; } set. Height(350); set. Height(); // will use the default value of 50 set. Height(135); set. Height(80); ? >

PHP Functions - Returning values <? php function sum($x, $y) { $z = $x

PHP Functions - Returning values <? php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = ". sum(5, 10). " "; echo "7 + 13 = ". sum(7, 13). " "; echo "2 + 4 = ". sum(2, 4); ? >

PHP String Functions The PHP strlen() function The strlen() function returns the length of

PHP String Functions The PHP strlen() function The strlen() function returns the length of a string, in characters. <? php echo strlen("Hello world!"); ? > The PHP strpos() function The strpos() function is used to search for a specified character or text within a string. <? php echo strpos("Hello world!", "world"); ? > // ouput 6

Counting Number of Words in a String The str_word_count() function counts the number of

Counting Number of Words in a String The str_word_count() function counts the number of words in a string. <? php $my_str = 'The quick brown fox jumps over the lazy dog. '; // Outputs: 9 echo str_word_count($my_str); ? >

Replacing Text within Strings The str_replace() replaces all occurrences of the search text within

Replacing Text within Strings The str_replace() replaces all occurrences of the search text within the target string. Example <? php $my_str = 'If the facts do not fit theory, change the facts. '; // Display replaced string echo str_replace("facts", "truth", $my_str); ? >

 You can optionally pass the fourth argument to the str_replace() function to know

You can optionally pass the fourth argument to the str_replace() function to know how many times the string replacements was performed, like this. <? php $my_str = 'If the facts do not fit theory, change the facts. '; // Perform string replacement str_replace("facts", "truth", $my_str, $count); // Display number of replacements performed echo "The text was replaced $count times. "; ? >

Reversing a String The strrev() function reverses a string. <? php $my_str = 'You

Reversing a String The strrev() function reverses a string. <? php $my_str = 'You can do anything, but not everything. '; // Display reversed string echo strrev($my_str); ? > The output of the above code will be: . gnihtyreve ton tub , gnihtyna od nac uo. Y

PHP - Sort Functions For Arrays sort() - sort arrays in ascending order rsort()

PHP - Sort Functions For Arrays sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order sort() <? php $cars = array("Volvo", "BMW", "Toyota"); sort($cars);

Sort Array in Ascending Order sort() <? php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); ? > <? php $numbers = array(4, 6, 2, 22, 11); sort($numbers); ? >

Sort Array in Descending Order rsort() <? php $cars = array("Volvo", "BMW", "Toyota"); rsort($cars);

Sort Array in Descending Order rsort() <? php $cars = array("Volvo", "BMW", "Toyota"); rsort($cars); ? >

Sort Array (Ascending Order), According to Value - asort() The following example sorts an

Sort Array (Ascending Order), According to Value - asort() The following example sorts an associative array in ascending order, according to the value: <? php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>" 43"); asort($age); ? >

OUTPUT Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43

OUTPUT Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43

Sort Array (Ascending Order), According to Key - ksort() The following example sorts an

Sort Array (Ascending Order), According to Key - ksort() The following example sorts an associative array in ascending order, according to the key: <? php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>" 43"); ksort($age); ? >

OUTPUT Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35

OUTPUT Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35

Sort Array (Descending Order), According to Value - arsort() The following example sorts an

Sort Array (Descending Order), According to Value - arsort() The following example sorts an associative array in descending order, according to the value: <? php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>" 43"); arsort($age); ? >

OUTPUT Key=Joe, Value=43 Key=Ben, Value=37 Key=Peter, Value=35

OUTPUT Key=Joe, Value=43 Key=Ben, Value=37 Key=Peter, Value=35

Sort Array (Descending Order), According to Key - krsort() The following example sorts an

Sort Array (Descending Order), According to Key - krsort() The following example sorts an associative array in descending order, according to the key: <? php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>" 43"); krsort($age); ? >

OUTPUT Key=Peter, Value=35 Key=Joe, Value=43 Key=Ben, Value=37

OUTPUT Key=Peter, Value=35 Key=Joe, Value=43 Key=Ben, Value=37

PHP 5 Global Variables Superglobals Several predefined variables in PHP are "superglobals", which means

PHP 5 Global Variables Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

PHP $GLOBALS is a PHP super global variable which is used to access global

PHP $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. The example below shows how to use the super global variable $GLOBALS:

<? php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x']

<? php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ? > In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from outside the function!

PHP $_SERVER <!DOCTYPE html> <body> <? php echo $_SERVER['PHP_SELF']; echo " "; echo $_SERVER['SERVER_NAME'];

PHP $_SERVER <!DOCTYPE html> <body> <? php echo $_SERVER['PHP_SELF']; echo " "; echo $_SERVER['SERVER_NAME']; echo " "; echo $_SERVER['SCRIPT_FILENAME']; ? > </body> </html>

$_SERVER['PHP_SELF'] Returns the filename of the currently executing script $_SERVER['SERVER_NAME'] Returns the name of

$_SERVER['PHP_SELF'] Returns the filename of the currently executing script $_SERVER['SERVER_NAME'] Returns the name of the host server (such as www. w 3 schools. com) $_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script

$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web server

$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web server for communication (such as 80) $_SERVER['SERVER_ADDR'] Returns the IP address of the host server

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol (such as HTTP/1. 1)

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol (such as HTTP/1. 1)

PHP $_REQUEST is used to collect data after submitting an HTML form.

PHP $_REQUEST is used to collect data after submitting an HTML form.

<html> <body> <form method="post" action="<? php echo $ _SERVER['PHP_SELF']; ? >"> Name: <input type="text"

<html> <body> <form method="post" action="<? php echo $ _SERVER['PHP_SELF']; ? >"> Name: <input type="text" name="fname"> <input type="submit"> </form>

<? php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name

<? php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_REQUEST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ? > </body> </html>

PHP Arrays <? php $cars=array("Volvo", "BMW", "Toyota"); echo "I like ". $cars[0]. ", ".

PHP Arrays <? php $cars=array("Volvo", "BMW", "Toyota"); echo "I like ". $cars[0]. ", ". $cars[1]. " and ". $cars[2]. ". "; ? > // outputs : I like Volvo, BMW and Toyota.

String Processing and Regular Expressions echo strcmp("a", "b"); Output : -1 echo strcmp(“b", “a");

String Processing and Regular Expressions echo strcmp("a", "b"); Output : -1 echo strcmp(“b", “a"); Output : 1 echo strcmp(“b", "b"); Output : 0

<? php $search = "Now is the time"; if ( ereg( "Now", $search )

<? php $search = "Now is the time"; if ( ereg( "Now", $search ) ) print( "String 'Now' was found. " ); if ( ereg( "^Now", $search ) ) print( "String 'Now' found at beginning of the line. " );

if ( ereg( "Now$", $search ) ) print( "String 'Now' was found at the

if ( ereg( "Now$", $search ) ) print( "String 'Now' was found at the end of the line. " ); if ( ereg( "[[: <: ]]([a-z. A-Z]*ow)[[: >: ]]", $search, $match ) ) print( "Word found ending in 'ow': ". $match[ 1 ]. " " );

PHP Form Handling -GET Method <html> <body> PHP $_GET can also be used to

PHP Form Handling -GET Method <html> <body> PHP $_GET can also be used to collect form data after submitting an HTML form with method="get". <form action="welcome_get. php" method="get"> Name: <input type="text" name="name"> E-mail: <input type="text" name="email"> <input type="submit"> </form> </body> </html> // welcome_get. php <html> <body> Welcome <? php echo $_GET["name"]; ? > Your email address is: <? php echo $_GET["email"]; ? > </body> </html>

PHP Form Handling -POST Method <html> <body> PHP $_POST is widely used to collect

PHP Form Handling -POST Method <html> <body> PHP $_POST is widely used to collect form data after submitting an HTML form with method="post" <form action="welcome. php" method="post"> Name: <input type="text" name="name"> E-mail: <input type="text" name="email"> <input type="submit"> </form> // welcome. php <html> </body> </html> Welcome <? php echo $_POST["name"]; ? > Your email address is: <? php echo $_POST["email"]; ? > </body> </html>

Form processing <? php extract( $_GET ); echo “$name”; ? >

Form processing <? php extract( $_GET ); echo “$name”; ? >

Open a Connection to the My. SQL Server <? php $query = "SELECT *

Open a Connection to the My. SQL Server <? php $query = "SELECT * FROM Books"; if ( !( $database = mysql_connect( “localhost", “username", “password" ) ) ) die( "Could not connect to database" ); if ( !mysql_select_db( "Products", $database ) ) die( "Could not open Products database" ); if ( !( $result = mysql_query( $query, $database ) )){ print( "Could not execute query! " ); die( mysql_error() ); } ? >

<table border = "1”> <? php for ( $counter = 0; $row = mysql_fetch_row(

<table border = "1”> <? php for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ print( "<tr>" ); foreach ( $row as $value ) print( "<td>$value</td>" ); print( "</tr>" ); } mysql_close( $database ); ? > </table>

Cookie setcookie( "Name", $Name, time() + 60 * 24 * 5 ); <table> <?

Cookie setcookie( "Name", $Name, time() + 60 * 24 * 5 ); <table> <? php // iterate through array $_COOKIE and print // name and value of each cookie foreach ( $_COOKIE as $key => $value ) print( "<tr><td>$key</td> <td >$value</td></tr>" ); ? ><!-- end PHP script --> </table>

Insert Data From a Form Into a Database <html> <body> <form action="insert. php" method="post">

Insert Data From a Form Into a Database <html> <body> <form action="insert. php" method="post"> Firstname: <input type="text" name="firstname"> Lastname: <input type="text" name="lastname"> Age: <input type="text" name="age"> <input type="submit"> </form> </body> </html>

"insert. php". <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); // Check connection if

"insert. php". <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to My. SQL: ". mysqli_connect_error(); } $sql="INSERT INTO Persons (First. Name, Last. Name, Age) VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[age]')"; if (!mysqli_query($con, $sql)) { die('Error: '. mysqli_error($con)); } echo "1 record added"; mysqli_close($con); ? >

Example Description The example above stores the data returned by the mysqli_query() function in

Example Description The example above stores the data returned by the mysqli_query() function in the $result variable. Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array. Each call to mysqli_fetch_array() returns the next row in the recordset. To print the value of each row, we use the PHP $row variable ($row['First. Name'] and $row['Last. Name']).

Display the Result in an HTML Table <? php $con=mysqli_connect("example. com", "peter", "abc 123",

Display the Result in an HTML Table <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to My. SQL: ". mysqli_connect_error(); } $result = mysqli_query($con, "SELECT * FROM Persons"); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>". $row['First. Name']. "</td>"; echo "<td>". $row['Last. Name']. "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ? > Firstname Lastname Ajith Lal Manu Thambi

Update Data In a Database <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); //

Update Data In a Database <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to My. SQL: ". mysqli_connect_error(); } mysqli_query($con, "UPDATE Persons SET Age=36 WHERE First. Name='Peter' AND Last. Name='Griffin'"); mysqli_close($con); ? >

PHP My. SQL Delete <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); // Check

PHP My. SQL Delete <? php $con=mysqli_connect("example. com", "peter", "abc 123", "my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to My. SQL: ". mysqli_connect_error(); } mysqli_query($con, "DELETE FROM Persons WHERE Last. Name='Griffin'"); mysqli_close($con); ? >

Thank you

Thank you