PHP

What is PHP?
 PHP is a server-side scripting language

 PHP stands for PHP: Hypertext Preprocessor
 PHP scripts are executed on the server  PHP supports many databases (MySQL, Informix,

Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)  PHP is an open source software  PHP is free to download and use

What is a PHP File?
 PHP files can contain text, HTML tags and scripts

 PHP files are returned to the browser as plain

HTML  PHP files have a file extension of ".php", ".php3", or ".phtml"

Installing PHP
 PHP runs on different platforms (Windows, Linux,

Unix, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)

 Download PHP for free

here: http://windows.php.net/download/  Download MySQL Database here: http://www.mysql.com/downloads/  Download Apache for free here: http://httpd.apache.org/download.cgi

.

.

php #configure the path to php.Configuring Apache2.conf file in “ C:\Program Files\Apache Software Foundation\Apache2.dll” AddHandler application/x-httpd-php .ini PHPIniDir “C:/php” .2\conf ” #LoadModule php5_module “c:/php/php5apache2_2.2 for PHP • Add following line at end of the httpd.

2 3. Select Apache2.Restarting the Server 1. Click the “apache service Monitor” icon the taskbar 2. Select Restart on .

First PHP File • Create a file named “first.php” in “C:\Program Files\Apache Software Foundation\Apache2.2\htdocs” Save following code in the file:<?php echo “Hello world” ?> From any browser go to “localhost/first.php” • • .

Basic PHP Syntax:  <?php //This is a comment /* This is a comment block */ ?> <html> <body> <?php </body> </html> echo "Hello World". ?> .

     numbers or arrays. . PHP is a Loosely Typed Language: In PHP. like text strings. $varName = value.PHP Variables  Variables are used for storing values. a variable does not need to be declared before adding a value to it. and _ )  A variable name should not contain spaces. All variables in PHP start with a $ sign symbol. 0-9. Naming Rules for Variables  A variable name must start with a letter or an underscore "_"  A variable name can only contain alpha-numeric characters and underscores (a-z. A-Z.

 <?php $txt1="Hello World!". ?>The output of the code above will be:  Hello World! What a nice day!  . $txt2="What a nice day!".  The concatenation operator (.Below. echo $txt.  The Concatenation Operator: There is only one string operator in PHP.) is used to put two string values together. " " . ?>  o/p==Hello World. echo $txt1 .A string can be used directly in a function or it can be stored in a variable.String Variables in PHP String variables are used for values that contain characters. the PHP script assigns the text "Hello World" to a string variable called $txt:  <?php $txt="Hello World". $txt2.

?> The output of the code above will be:  12 .The strlen() function  The strlen() function is used to return the length of a string.  <?php echo strlen("Hello world!").

this function will return the position of the first match.  If a match is found. If no match is found.  Let's see if we can find the string "world" in our string:  <?php echo strpos("Hello world!". ?> The output of the code above will be:  6 .The strpos() function  The strpos() function is used to search for character within a string."world"). it will return FALSE.

5 1 2 0 x=6 x=4 % ++ -- .PHP Operators Arithmetic Operators: Operator + * / Description Example Addition x=2 x+2 Subtraction x=2 5-x Multiplication x=4 x*5 Division 15/5 5/2 Modulus 5%2 (division 10%8 remainder) 10%2 Increment x=5 x++ Decrement x=5 x-- Result 4 3 20 3 2.

y x=x%y .= %= Example x=y x+=y x-=y x*=y x/=y x.Assignment Operators Operator = += -= *= /= .=y x%=y Is The Same As x=y x=x+y x=x-y x=x*y x=x/y x=x.

Comparison Operators Operator == Description is equal to Example 5==8 returns false != <> > < >= <= is not equal is not equal is greater than is less than is greater than or equal to is less than or equal to 5!=8 returns true 5<>8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true .

Logical Operators Operator && Description and Example x=6 y=3(x < 10 && y > 1) returns true x=6 y=3(x==5 || y==5) returns false x=6 y=3!(x==y) returns true || or ! not .

else statement .....PHP If.else statement .Else Statements In PHP we have the following conditional statements:  if statement .use this statement to execute some code if a condition is true and another code if the condition is false  if..use this statement to select one of many blocks of code to be executed .elseif.use this statement to select one of several blocks of code to be executed  switch statement ...use this statement to execute some code only if a specified condition is true  if...

if ($d=="Fri") echo "Have a nice weekend!".Example Syntax: <html> <body> <?php $d=date("D"). ?> </body> </html> .

An array with a numeric index  Associative array . In PHP. which can store multiple values in one single variable. storing the cars in single variables could look like this:  $cars1=“Audi". a variable will hold only one value.  An array is a special variable. for example).  If you have a list of items (a list of car names.An array containing one or more arrays .PHP Arrays  A variable is a storage area holding a number or text. The problem is. $cars2="Volvo". there are three kind of arrays:  Numeric array .An array where each ID key is associated with a value  Multidimensional array . $cars3="BMW".

$cars[0] . $cars[1]="Volvo".Numeric Arrays  <?php $cars[0]=“Audi". ?>  The code above will output: First Car is Audi . $cars[3]="Toyota". echo “First car is:” . $cars[2]="BMW". “BMW”). $cars2 = array (“Audi”.

$ages['Peter'] . ‟John‟=>30 . . each ID key is associated with a value <?php $ages['Peter'] = "32".".Associative Arrays • An associative array. ?> • Output Peter is 32 years old. $ages2=array(„Peter‟=>32 . $ages['Joe'] = "34". $ages[„John'] = "30". " years old. ‟joe‟=>34). echo "Peter is " .

“array3"=>array ( “P". . “Q".Multidimensional Arrays In a multidimensional array. “array2"=>array ( “Z" ). “R" ) ). “C" ). “B". each element in the main array can also be an array $arrayExample = array ( “array1"=>array ( “A".

we have the following looping statements:  while ..PHP Loops In PHP. and then repeats the loop as long as a specified condition is true  for .loops through a block of code while a specified condition is true  do.while ..loops through a block of code a specified number of times  foreach .loops through a block of code once.loops through a block of code for each element in an array .

$i .Example Syntax:  <html><body> <?php $i=1. $i++. } ?> </body></html>  Output: The number is 1 The number is 2 The number is 3 . "<br />". while($i<=3) { echo "The number is " .

$i<=3. ?> <br /> <?php } ?> </body></html> Output:  The number is 1 The number is 2 The number is 3 .The for Loop Example:  <html><body> <?php for ($i=1. $i . $i++) { echo "The number is " .

Syntax:  function functionName($par1.PHP Functions Create a PHP Function:  A function will be executed by a call to the function. $par2.) { code to be executed. } PHP function guidelines:  Give the function a name that reflects what the function does  The function name can start with a letter or underscore (not a number) . ….

?> </body> </html> Output:  My name is Vishal Shujalpurkar . $name. } writeName(“Visahl shujalpurkar”).Example   A simple function that writes name when it is called: <html> <body> <?php function writeName($name) { echo “My name is “ .

PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms. Example: The example below contains an HTML form with two input fields and a submit button:  <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> . like user input.

php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>  <?php echo $_GET[„fname‟]. ?> .  Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. Example:  <form action="welcome.PHP $_GET Function  The built-in $_GET function is used to collect values from a form sent with method="get".

because the variables are displayed in the URL. .When to use method="get"?  When using method="get" in HTML forms. It should not be used with values exceeding 2000 characters. all variable names and values are displayed in the URL. it is possible to bookmark the page. This can be useful in some cases.  Note: This method should not be used when sending passwords or other sensitive information!  However.  Note: The get method is not suitable for very large variable values.

PHP $_POST Function  The built-in $_POST function is used to collect values from a form sent with method="post". by default (can be changed by setting the post_max_size in the php. Example:  <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>  <?php echo $_POST[„fname‟].ini file).  Note: However. .  Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. there is an 8 Mb max size for the POST method.

it is not possible to bookmark the page.  However.When to use method="post"?  Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. because the variables are not displayed in the URL. .

. and $_COOKIE.  The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.The PHP $_REQUEST Function  The PHP built-in $_REQUEST function contains the contents of both $_GET. $_POST.

it will send the cookie too. Each time the same computer requests a page with a browser. you can both create and retrieve cookie values. A cookie is a small file that the server embeds on the user's computer.PHP Cookies  A cookie is often used to identify a user. With PHP. How to Create a Cookie?  The setcookie() function is used to set a cookie.  Note: The setcookie() function must appear BEFORE the <html> tag. .

path.  Example We specify that the cookie should expire after one hour:  <?php setcookie("user". ?> <html> .. value. domain).. . expire.Syntax  setcookie(name.. time()+3600). "Alex Porter"..

How to Retrieve a Cookie Value?  The PHP $_COOKIE variable is used to retrieve a cookie value. // A way to view all cookies print_r($_COOKIE). Example:  <?php // Print a cookie echo $_COOKIE["user"]. ?> .

time()-3600). ?> . Delete example:  <?php // set the expiration date to one hour ago setcookie("user". "".How to Delete a Cookie?  When deleting a cookie you should assure that the expiration date is in the past.

PHP Sessions • • Starting a PHP Session • • • session_start() function is used to start Session $_SESSION[„name']=value $var = $_SESSION[„name'] unset($_SESSION[„name']) unsets the session variable session_destroy() will reset session and you will lose all stored session data. Store and Retrieve Session Variable • Destroying a Session • • .

Optional. Specifies the format of the timestamp Timestamp . Default is the current date and time • Format the Date o o o d .Represents a month (01 to 12) Y .Represents the day of the month (01 to 31) m . Specifies a timestamp.Required.PHP Date() Function • date( format . timestamp ) o o Format .Represents a year (in four digits) .

m. "<br />".d") . echo date("Y. "<br />".PHP Date() example • Example <?php echo date("Y/m/d") . echo date("Y-m-d"). ?> • Output 2009/05/11 2009.05.11 2009-05-11 .

php"). but the script will continue execution require() . ?> <h1>Welcome to my home page!</h1> </body></html> .PHP Include File • Server Side Includes (SSI) • • • PHP provides two functions for SSI include() .generates a warning. and the script will stop <html><body> • Example <?php include("header.generates a fatal error.

mode ) function is used to open files in PHP The fclose($file) function is used to close an open file The feof($file) function checks if the "end-of-file" (EOF) has been reached • Closing a File • • Check End-of-file • • Reading a File • The fgets($file) function is used to read a single line • The fgetc($file) function is used to read a single .PHP File Handling • Opening a File • fopen( file_path .

or creates a new file if it doesn't exist w+ a Append. Starts at the beginning of the file Write only. or creates a new file if it doesn't exist Read/Write. Opens and clears the contents of file. Returns FALSE and an error if file already exists Read/Write.PHP File Modes Modes r r+ w Description Read only. Opens and writes to the end of the file or creates a new file if it doesn't exist Read/Append. Starts at the beginning of the file Read/Write. Opens and clears the contents of file. Creates a new file. Returns FALSE and an error if file already exists a+ x x+ . Preserves file content by writing to the end of the file Write only. Creates a new file.

PHP MySQL • Create a Connection $con=mysql_connect(servername.pa ssword).username. Run a SQL Query $result=mysql_query() Get the result $row=mysql_fetch_array($result) • • • • . Select Database mysql_select_db("db_name". Closing a Connection mysql_close($con).$con).

End .

Sign up to vote on this title
UsefulNot useful