You are on page 1of 175

An Overview of PHP

8/18/2011

Mrunalini M

What is PHP, and why do I need it?

PHP is the most popular scripting language on the web Used to enhance web pages

PHP is an acronym for Hypertext Preprocessor or Personal Home Page


Mrunalini M 2

8/18/2011

Origin of PHP

Rasmus Lerdorf A member of Apache group in1994 Developed to allow him to track visitors to his Web site Personal Home Page Tools Package: PHP is an open-source product from 1995
3

8/18/2011

Unique Features/Advantages

Performance:

Optimized memory manager Scripts written in php execute faster than those written in other scripting languages
Php is available for Unix, MSWindows, Mac OS and OS/2 PHP programs are Portable between different platforms

Portability

Unique Features/Advantages (Contd..)

Ease of use

Extremely sophisticated programming language Its Syntax is clear and consistent Its comes with exhaustive documentation for the 5000+ functions Easy to learn for both novice and experienced programmers
PHP is an open source project Developed by world-wide volunteers

Open Source

Unique Features/Advantages (Contd..)

Community Support

Php has good community support Access to creativity and imagination of hundreds of developers across the world Keep adding functionalities to PHP Extension Community Library (PECL) http://pecl.php.net Creativity keep adding to PHP Extension and Application Repository (PEAR) http://pear.php.net

Unique Features/Advantages (Contd..)

Third-Party Application Support

Supports wide range of different databases including MYSQL, PostgreSQL, Oracle, MS SQL Server Supports more than 15 different database engines It includes common API for Database access

Introduction to PHP

Similar to JavaScript, but on the server side server-side scripting language server-side scripts are special commands you must place in Web pages

Those commands are processed before the pages are sent from your Server to the Web browser of your visitor
A typical PHP file contains commands to be executed in the server in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags.

8/18/2011

Mrunalini M

Introduction to PHP- Contd..

PHP is an alternative to Perl, ASP.NET, JSP, and Allaires ColdFusion The PHP processor has two modes: copy (XHTML) and interpret (PHP)

8/18/2011

Mrunalini M

What Can You Do with PHP?

Form handling, File processing, and Database Access You can do things like create username and password login pages, check details from a form, create forums, picture galleries, surveys, and a whole lot more

8/18/2011

Mrunalini M

10

What you need to get started with PHP?

W
Windows

A
Apache

M
MySQL

P
PHP

L
Linux

A
Apache

P
MySQL PHP

8/18/2011

Mrunalini M

11

Syntactic Characteristics

PHP syntax is similar to that of JavaScript PHP is dynamically typed PHP is purely interpreted PHP code can be specified in an XHTML document internally or externally: Internally: <?php ... ?> Externally: include ("myScript.php") The file can have both PHP and XHTML
Mrunalini M 12

8/18/2011

What Do PHP pages Look Like?

Server-side scripts look a lot like HTML tags Instead of starting and ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically start with <?php or <? and will typically end with ?> <?php or <? is opening tag ?> is closing tag
Mrunalini M 13

8/18/2011

Creating my first PHP file


This is a regular HTML page: Eg: Mypage.html

<html> <head> <title>This is my page</title> </head> <body> This is the content of my page. </body> </html>

8/18/2011

Mrunalini M

14

Creating my first PHP file Contd..

Eg: Mypage.php
<html> <head> <title>This is my page</title> </head> <body> This is the content of my page. <?php print "Do you like it?"; ?> </body> </html>

8/18/2011

Mrunalini M

15

Creating my first PHP file Contd..


Eg: Mypage.php <html> <head> <title>This is my page</title> </head> <body> This is the content of my page. <?php print "<h1>Good Morning</h1>"; print "Do you like it?"; print "<br>"; print "<b>If not, please visit a different page.</b>"; print "<br>"; print "<h2>Good Day</h2>"; ?> </body> </html>

8/18/2011

Mrunalini M

16

General Syntactic Characteristics

Comments - three different kinds

// Like in javascript # like in perl /* like in many other programming languages */


and, break, case, class, continue, default, do, else, elseif, extends, false, for, foreach, function, global, if, include, list, new, not, or, require, return, static, switch, this, true, var, virtual, xor, while
Mrunalini M 17

Reserved words

8/18/2011

General Syntactic Characteristics-Contd..

PHP variables are case sensitive Reserved words and function names are not Statements are terminated with semicolon Compound statements are formed with braces

8/18/2011

Mrunalini M

18

Variables

Variables There are no type declarations $VarName An unassigned (unbound) variable has the value, NULL
The unset function sets a variable to NULL The IsSet function is used to determine whether a variable is NULL
Mrunalini M 19

8/18/2011

Variables-Contd..

error_reporting(15); prevents PHP from using unbound variables PHP has many predefined variables, including the environment variables of the host operating system

You can get a list of the predefined variables by calling phpinfo() in a script
Mrunalini M 20

8/18/2011

Variables-Contd..
<?php $first_number = 10; $direct_text = 'My variable contains the value of '; print ($direct_text . $first_number); ?> <?php $first_number = 10; print ('My variable contains the value of ' . $first_number); ?>
8/18/2011 Mrunalini M 21

Primitives

There are eight primitive types: Four scalar types: Boolean, integer, double, and string Two compound types: array and object

Two special types: resource and NULL


Integer & double are like those of other languages Strings

Characters are single bytes String literals use single or double quotes
Mrunalini M 22

8/18/2011

Primitives-Contd..

Single-quoted string literals (as in Perl)

Embedded variables are NOT interpolated Embedded escape sequences are NOT recognized
Embedded variables ARE interpolated Embedded escape sequences ARE recognized

Double-quoted string literals (as in Perl)

If there is a variable name in a doublequoted string but you dont want it interpolated, it must be back slashed

8/18/2011

Mrunalini M

23

Primitives-Contd..

For both single- and double-quoted literal strings, embedded delimiters must be back slashed
Boolean - values are true and false (case insensitive) 0 and "" and "0" are false; others are true
Mrunalini M 24

8/18/2011

Operators in PHP

The following categories of Operators

Assignment Operators Arithmetic Operators Comparison Operators String Operators

8/18/2011

Mrunalini M

25

Assignment Operators
Assignment operators are used to set a variable equal to a value or set a variable to another variable's value. Such an assignment of value is done with the "=", or equal character. Example: $my_var = 4; $another_var = $my_var;

8/18/2011

Mrunalini M

26

Arithmetic Operators

Usual C based programming language arithmetic operators +, -, *, /, %, ++ and --

8/18/2011

Mrunalini M

27

Exercise: Class Work

Write a php program to demonstrate the arithmetic operators.

Example

<?php
$addition = 2 + 4; $subtraction = 6 - 2; $multiplication = 5 * 3; $division = 15 / 3; $modulus = 5 % 2; echo "Perform addition: 2 + 4 = ".$addition."<br />"; echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />"; echo "Perform multiplication: 5 * 3 = ".$multiplication."<br />"; echo "Perform division: 15 / 3 = ".$division."<br />"; echo "Perform modulus: 5 % 2 = " . $modulus . ". Modulus is the remainder after the division operation has been performed. In this case it was 5 / 2, which has a remainder of 1.";

?>
Mrunalini M 29

8/18/2011

Comparison Operators

Assume: $x = 4 and $y = 5;
Operator == != < > <= >= English Equal To Not Equal To Less Than Greater Than Less Than or Equal To Example Result $x == $y false $x != $y true $x < $y $x > $y true false

$x <= $y true

Greater Than or Equal To $x >= $y false

8/18/2011

Mrunalini M

30

String Operators
<?php $a_string = "Hello"; $another_string = " Bill"; $new_string = $a_string . another_string; echo $new_string . "!"; ?>

8/18/2011

Mrunalini M

31

Combination Arithmetic & Assignment Operators


Operator += -= *= /= %= .= English Plus Equals Minus Equals Multiply Equals Divide Equals Modulo Equals Example $x += 2; $x -= 4; $x *= 3; $x /= 2; $x %= 5; Equivalent Operation $x = $x + 2; $x = $x - 4; $x = $x * 3; $x = $x / 2; $x = $x % 5;

Concatenate Equals $my_str.="hello"; $my_str = $my_str . "hello";

8/18/2011

Mrunalini M

32

Logical Operators

Boolean Operators

&& (and) || (or) ! (not)

8/18/2011

Mrunalini M

33

Example- Logical Operators


$sky = "sunny"; $temperature = 65; if ( !( ( sky == "cloudy" ) || ( $temperature < 50 ) ) ) { echo "Nice day."; } else { echo "Lousy day."; }

8/18/2011

Mrunalini M

34

Program Flow Control Statements


if, elseif, else switch while Do..while for foreach break continue

8/18/2011 M Mrunalini, MSRIT 35

if, elseif, else


if ( ) { } elseif ( ) { } else { }

8/18/2011

Mrunalini M

36

if/else an example
$number_three = 3; if ( $number_three == 3 ) { echo "The if statement evaluated to true"; } else { echo "The if statement evaluated to false"; }

8/18/2011

Mrunalini M

37

switch
switch ( ) { case condition1: break; case condition2 : break; }

8/18/2011

Mrunalini M

38

Exercise-Class Work
Write a php program to display library timings in a week using SWITCH statement Display- Today is: WeekDay open from 9:00am to 9:00pm open from 9:00am to 5:00pm closed

Switch example
print "\nLibrary Hours with \"switch\statements:\n"; print " Today is: $weekDay\n"; switch ($weekDay) { case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": $openHours = "open from 9:00am to 9:00pm"; break; case "Saturday": $openHours = "open from 9:00am to 5:00pm"; break; case "Sunday": $openHours = "closed"; break; default: $openHours = "not at here"; } print " The library is $openHours\n";

8/18/2011

Mrunalini M

40

while
while (condition) { }

8/18/2011

Mrunalini M

41

While Example
$a = 2; while ( $a < 100 ) { echo " $a"; $a *= $a; }

8/18/2011

Mrunalini M

42

Do.. While
do { } while (condition)

8/18/2011

Mrunalini M

43

Do.. While example


<html> <body> <?php $test=0; do { print "This is do while loop"; } while ($test); ?> </body> </html>
8/18/2011 Mrunalini M 44

for
<?php for ( $n = 1; $n < 10; $n++) { echo "$n<BR>"; } ?>

8/18/2011

Mrunalini M

45

foreach
<?php $tree = array("trunk", "branches", "leaves"); foreach ($tree as $part) { echo "Tree part: $part "; } ?>

8/18/2011

Mrunalini M

46

break

Is used to end the execution of a for, switch, or while statement

8/18/2011

Mrunalini M

47

continue
This statement is used to skip the rest of the current loop. <?php for ( $n = 1; $n < 10; $n++) { echo "$n<BR>";
if ($n == 5) continue; echo "This statement is skipped when $n = 5.<BR>";

} ?>
8/18/2011 Mrunalini M 48

Difference between Break & Exit


Break; can be used to end the execution of the current case. It can also be used to break out of for loops and while loops. Exit; terminates the execution entire script, and may be used anywhere within the script.

8/18/2011

Mrunalini M

49

Operator Precedence
++ -! * / % + - . < <= > >= == != === !== && || = += -= *= /= .= %= &= |= ^=

Constants in PHP
define() function is used to declare constants Syntax:

define(identifier, value); define(PI, 3.14);

Example:

Exercises
1.

Write PHP script to display prime numbers in a given range Write PHP script to display Library timings using if..else and switch

2.

8/18/2011

Mrunalini M

52

Working with HTML Forms


<html> <head> <title>A BASIC HTML FORM</title> </head> <body> <FORM NAME ="form1" METHOD =" " ACTION = ""> <INPUT TYPE = "TEXT" VALUE ="username"> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login"> </FORM> </body> </html>

8/18/2011

Mrunalini M

53

The Method Attribute of HTML Forms


The Method attribute is used to tell the browser how the form information should be sent. The two most popular methods you can use are GET and POST.

8/18/2011

Mrunalini M

54

GET method

<FORM NAME ="form1" METHOD ="GET" ACTION = "">

What do you observe?

8/18/2011

Mrunalini M

55

GET contd..

The thing to notice here is the address bar. After basicForm.php, we have the following: ?Submit1=Login This is a consequence of using the GET method. The data from the form ends up in the address bar. You'll see a question mark, followed by form data. In the image above, Submit1 was the NAME of the button, and Login was the VALUE of the button (the text on the button). This is what is being returned by the GET method. You use the GET method when the data you want returned is not crucial information that needs protecting.
Mrunalini M 56

8/18/2011

POST method

<FORM NAME ="form1" METHOD ="POST" ACTION = ""> What do you observe?

8/18/2011

Mrunalini M

57

POST Contd..

The ?Submit1=Login part from the previous section is now gone! That is because we used POST as the method. Using POST means that the form data won't get appended to the address in the address bar for all to see.

8/18/2011

Mrunalini M

58

The ACTION Attribute of HTML Forms


The Action attribute is crucial. It means, "Where do you want the form sent?". If you miss it out, your form won't get sent anywhere. You can send the form data to another PHP script, the same PHP script, an email address, a CGI script, or any other form of script.

8/18/2011 Mrunalini M 59

ACTION contd..

<Form Name ="form1" Method ="POST" ACTION = "basicForm.php">

8/18/2011

Mrunalini M

60

The Submit Button of a HTML FORM

<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">

You don't need to do anything special with a Submit button all the submitting is done behind your back. As long as SUBMIT has an ACTION set, then your data will get sent somewhere.

8/18/2011

Mrunalini M

61

Getting values from a Text Box with PHP

To get at the text that a user entered into a text box, the text box needs a NAME attribute.
<INPUT TYPE = "Text" VALUE ="username" NAME = "username">

The NAME of our textbox is "username It's this name that we will be using in a PHP script. To return data from a HTML form element, you use the following strange syntax: $_POST['formElement_name'];

8/18/2011

Mrunalini M

62

Getting values from a Text Box (Contd..)

You can assign this to a variable:


$Your_Variable = $_POST['formElement_name'];

<html> <head> <title>A BASIC HTML FORM</title> <?PHP $username = $_POST['username']; print ($username); ?> </head>
8/18/2011 Mrunalini M 63

How does it work?


The $_POST[] is an inbuilt function you can use to get POST data from a form. If you had METHOD = "GET" on your form $username = $_GET['username']; $_GET[], $_POST[]

8/18/2011

Mrunalini M

64

Simple Example on Usage of Text Box Values


if ($username = = msrit") { print ("Welcome to MSRIT!"); } else { print ("You're not a member of MSRIT"); }

8/18/2011

Mrunalini M

65

Checking if the Submit Button of a HTML Form was Clicked

if (isset($_POST['Submit'])) { } Looks a bit messy!

8/18/2011

Mrunalini M

66

Checking the Submit button click


But it actually consists of three parts: if ( ) { } isset( ) $_POST['Submit'] isset( ):This is an inbuilt function that checks if a variable has been set or not In between the round brackets, you type what you want isset( ) to check For us, this is $_POST['Submit']

8/18/2011 Mrunalini M 67

Checking the Submit button click


if (isset($_POST['Submit'])) { $username = $_POST['username']; if ($username = = "letmein") { print ("Welcome back, friend!"); } else { print ("You're not a member of this site"); } }

8/18/2011 Mrunalini M 68

Setting ACTION to a different PHP Page

<html> <head> <title>A BASIC HTML FORM</title> </head> <body> <Form name ="form1" Method ="POST" Action="submitForm.php"> <INPUT TYPE = "TEXT" VALUE ="username" Name ="username"> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login"> </FORM> </body> </html>

8/18/2011

Mrunalini M

69

Create new page


Now create the following page, and call it submitForm.php. <?PHP $username = $_POST['username']; if ($username = = msrit") { print ("Welcome to MSRIT!"); } else { print ("You're not a member of this site"); } ?>
Mrunalini M 70

8/18/2011

Keeping the data as the user entered

To post the details back to the form, and thus keep the data the user has already typed out, you can use this:
VALUE="<?PHP print $username ; ?>"

The line of code is just this: <?PHP print $username ; ?>

8/18/2011

Mrunalini M

71

Keeping the data the user entered (Contd..)


You also need to amend your PHP code in the HEAD section to include an else statement: if (isset($_POST['Submit1'])) { $username = $_POST['username']; if ($username = = "letmein") { print ("Welcome back, friend!"); } else { print ("You're not a member of this site"); } } else { $username =""; }
Mrunalini M 72

8/18/2011

Keeping the data the user entered (Contd..)

New line of HTML for our textbox reads like this:

<INPUT TYPE = 'TEXT' Name ='username' VALUE="<?PHP print $username ; ?>">

8/18/2011

Mrunalini M

73

Exercises

Exercise1 Add two text boxes and a Submit button to a HTML form. Invite the user to enter a first name and surname. When the button is clicked, print out the person's full name. Don't worry about what is in the text boxes after the button is clicked. Exercise2 Using the same form as the previous exercise, display the first name and surname in the textboxes, instead of printing them out. Exercise3 Suppose your web site has only 5 users. Create a HTML form to check if a visitor is one of the 5 users. Display a suitable message.
Mrunalini M 74

8/18/2011

PHP and Radio Buttons

A Radio Button is a way to restrict users to having only one choice

The HTML Form code for Radio Button


<FORM name ="form1" method ="post" action ="radioButton.php"> <Input type = 'Radio' Name ='gender' value= 'male' <?PHP print $male_status; ?> >Male <Input type = 'Radio' Name ='gender' value= 'female' <?PHP print $female_status; ?> >Female <Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button"> </FORM>

The PHP code for Radio Button


<?PHP $male_status = 'unchecked'; $female_status = 'unchecked'; if (isset($_POST['Submit1'])) { $selected_radio = $_POST['gender']; if ($selected_radio == 'male') { $male_status = 'checked'; } else if ($selected_radio == 'female') { $female_status = 'checked'; }}?>

PHP and Check Boxes


Like Radio buttons, checkboxes are used to give visitors a choice of options Radio Buttons restrict users to only one choice You can select more than one option with Checkboxes

The HTML Form code for Check Boxes


<body> <FORM NAME ="form1" METHOD ="POST" ACTION ="checkBoxes.php"> <Input type = 'Checkbox' Name ='ch1' value ="net" <?PHP print $ch1; ?> >Visual Basic .NET <Input type = 'Checkbox' Name ='ch2' value="word" <?PHP print $ch2; ?> >Microsoft Word <Input type = 'Checkbox' Name ='ch3' value="excel" <?PHP print $ch3; ?> >Microsoft Excel <Input type = 'Checkbox' Name ='ch4' value="web" <?PHP print $ch4; ?> >Web Design <Input type = 'Checkbox' Name ='ch5' value="php" <?PHP print $ch5; ?> >PHP for the Beginner <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books"> </FORM> </body>

PHP code for Check Boxes


<html> <head> <title>Checkboxes</title> <?PHP $ch1 = 'unchecked'; $ch2 = 'unchecked'; $ch3 = 'unchecked'; $ch4 = 'unchecked'; $ch5 = 'unchecked'; if (isset($_POST['Submit1'])) { if (isset($_POST['ch1'])) { $ch1 = $_POST['ch1']; if ($ch1 == 'net') { $ch1 = 'checked'; } }

PHP code for Check Boxes (Contd..)


if (isset($_POST['ch2'])) { $ch2 = $_POST['ch2']; if ($ch2 == 'word') { $ch2 = 'checked'; } } if (isset($_POST['ch3'])) { $ch3 = $_POST['ch3']; if ($ch3 == 'excel') { $ch3 = 'checked'; } } if (isset($_POST['ch4'])) { $ch4 = $_POST['ch4'];

PHP code for Check Boxes (Contd..)


if ($ch4 == 'web') { $ch4 = 'checked'; } } if (isset($_POST['ch5'])) { $ch5 = $_POST['ch5']; if ($ch5 == 'php') { $ch5 = 'checked'; } } } ?> </head>

Scalar Arrays in PHP


$Order_Number1 $Order_Number2 $Order_Number3 $Order_Number4

= = = =

"Black shoes"; "Tan shoes"; "Red shoes"; "Blue shoes";

Arrays (Contd..)

With an array, you can just use a single name $Order_Number = array( ); You can use two basic methods to put something into an array

Method One Type between the round brackets

The first method involves typing your values between the round brackets of array(). In the code below, we're setting up an array to hold the seasons of the year: $seasons = array("Autumn", "Winter", "Spring", "Summer"); So the name of the array is $seasons. Between the round brackets of array(), we have typed some values. Each value is separated by a comma: ("Autumn", "Winter", "Spring", "Summer") Arrays work by having a position, and some data for that position. In the above array, "Autumn" is in position zero, "Winter" is in position 1, "Spring" is in position 2, and "Summer" is in position 3.

Arrays (Contd..)

The first position is always zero, unless you tell PHP otherwise. The position is know as a Key. The Key then has a value attached to it. You can specify your own numbers for the Keys. If so, you do it like this: $seasons = array(1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer"); So you type a number for your key, followed by the equals sign and a right angle bracket ( => ).

Arrays (Contd..)
You can have numbers for the values of your keys $Array_Name = array(10, 20, 30, 40);

Method two Assign values to an array

Another way to put values into an array is like this: $seasons = array();

$seasons[]="Autumn"; $seasons[]="Winter"; $seasons[]="Spring"; $seasons[]="Summer";

Arrays - Method 2 (Contd..)

Here, the array is first set up with $seasons = array(); This tells PHP that you want to create an array with the name of $seasons. To store values in the array you first type the name of the array, followed by a pair of square brackets: $seasons[] After the equals sign, you type out what you want to store in this position. Because no numbers were typed in between the square brackets, PHP will assign the number 0 as the first key: 0=> "Autumn", 1=> "Winter", 2=> "Spring", 3=> "Summer" This is exactly the same as the array you saw earlier.

Arrays - Method 2 (Contd..)


If you want different numbers for your keys, then simply type them between the square brackets: $seasons[1]="Autumn"; $seasons[2]="Winter"; $seasons[3]="Spring"; $seasons[4]="Summer"; PHP will then see your array like this: 1=> "Autumn", 2=> "Winter", 3=> "Spring", 4=> "Summer"

Arrays (Contd..)

This method of creating arrays can be very useful for assigning values to an array within a loop. Here's some code: $start = 1; $times = 2; $answer = array(); for ($start; $start < 11; $start++) { $answer[$start] = $start * $times; }

Getting at the Values Stored in PHP Arrays


<?php $seasons = array("Autumn", "Winter", "Spring", "Summer"); print $seasons[0]; ?> You can also assign this value to another variable: $key_data = $Array_Name[0]; print $key_data;

$seasons = array("Autumn", "Winter", "Spring", "Summer"); print print print print $seasons[0]; $seasons[1]; $seasons[2]; $seasons[3];

Or you could do it like this: for ($key_Number = 0; $key_Number < 4; $key_Number++) { print $seasons[$key_Number]; }

PHP Associative Arrays - Using Text as Keys


Array keys don't have to be numbers They can be text. This can help you remember what's in a key, or what it's supposed to do When you use text for the keys, It is called an Associative array; when you use numbers for the keys, It is called a Scalar array. Here's an array that sets up first name and surname combinations: $full_name = array( ); $full_name["David"] = "Gilmour"; $full_name["Nick"] = "Mason"; $full_name["Roger"] = "Waters"; $full_name["Richard"] = "Wright";

PHP Arrays and For Each Loops


how to access each element in Associative array? - with the For Each loop $full_name = array( ); $full_name["David"] = "Gilmour"; $full_name["Nick"] = "Mason"; $full_name["Roger"] = "Waters"; $full_name["Richard"] = "Wright";

foreach ($full_name as $key_name => $key_value) { print "Key = " . $key_name . " Value = " . $key_value . "<BR>"; }

the first line of the loop is this: foreach ($full_name as $key_name => $key_value) { Notice that the name of the loop is one word: foreach and NOT for each. Next comes the round brackets. Inside of the round brackets, we have this: $full_name as $key_name => $key_value You start by typing the name of the array you want to loop round. For us, that was $full_name. Next is this: as $key_name => $key_value This means, "Get the Key and its Value from the array called $full_name. The Key is called $key_name in the script above, and the value is called $key_value. But these are just variable names

A PHP "Times Table" Program-Exercise

Code for Times Table program


<?PHP

$times = 2;
if (isset($_POST['Submit1'])) { $start = $_POST['txtStart']; $end = $_POST['txtEnd']; $times = $_POST['txtTimes']; for($start; $start <= $end; $start++) { $answer = $start * $times; print $start . " multiplied by " . $times . " = " . $answer . "<BR>"; } } ?>

Sorting Array Values in PHP


$full_name = array(); $full_name["Roger"] = "Waters"; $full_name["Richard"] = "Wright"; $full_name["Nick"] = "Mason"; $full_name["David"] = "Gilmour"; To sort this array, you just use the asort( ) function asort($full_name); The letter "a" tells PHP that the array is an Associative one

Sorting Array Values in PHP (Contd..)

sort()- Sorts scalar array in Ascending order asort()- Sorts associative array in Ascending order ksort()-Sorts keys in Ascending order rsort()- Sorts scalar array in reverse order arsort()- Sorts associative array in reverse order krsort()- Sorts keys in reverse order

Get a Random Key from an Array

You can grab a random key from an array. This could be useful in games of chance. Here's a simple script that simulates a single dice throw: <?PHP $numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6); $random_key = array_rand($numbers, 1); print $random_key; ?> You start off with the function array_rand( ). In between the round brackets, you need two things: the name of your array, and how many random keys you want to grab.

The count function in PHP


The count( ) function is useful when you want to return how many elements are in your array $seasons = array("Autumn", "Winter", "Spring", "Summer");

$array_count = count($seasons);
for ($key_Number = 0; $key_Number < $array_count; $key_Number++) { print $seasons[$key_Number]; }

Exercises
Set up an array and print out the values 2. Set up an array with your own Keys 3. Set up an array with mixed values 4. Assign values to an array: using Method Two 5. Looping round values in an array 6. Looping round values in an array: example 2 7. Using text as Keys 8. Looping round an Associative array using For Each 9. Sorting Arrays (Associative) 10. Sorting Arrays (Scalar)
1.

Strings- Changing Case in PHP


$full_name = 'bill gates'; $full_name = ucwords($full_name); converts the first letter of every word to uppercase If you just want to convert the first letter of a string (for a sentence, for example), then you can use ucfirst( ) $full_ sentence = ucfirst($full_ sentence); $change_to_lowercase = "CHANGE THIS"; $change_to_lowercase = strtolower($change_to_lowercase);

$change_to_uppercase = "change this"; $change_to_uppercase = strtoupper($change_to_lowercase);

Trimming White Space in PHP


<?PHP $space = " username "; $letCount = strlen($space); print $letCount; ?> To remove the white space, you can use the trim( ) function. Change your script to this: <?PHP $space = trim(" username "); $letCount = strlen($space); print $letCount; ?> Two related function are ltrim( ) and rtrim( ). The first one, ltrim( ), removes space from the beginning of a string; the second one, rtrim( ), removes space from the end of a string.

Finding String Positions with the PHP strpos Function

The syntax for the strpos function is: strpos(string_to_search, string_to_find, start) You need to supply at least the first two. The third, start, is optional. Here's a simple example. $full_name = "bill gates"; $letter_position = strpos($full_name, "b"); print $letter_position;

When you run the script, a value of 0 is returned. That's because PHP considers the first character of the string to be at position 0, the second character at position 1, the third at position 2, etc. Since we were searching for the letter "b", and "bill gates" begins with this letter, a value of 0 is returned.

$letter_position = strpos($full_name, "b"); $letter_position = strpos($full_name, "B"); $full_name = "bill gates"; $letter_position = strpos($full_name, "B"); if ($letter_position = = = false) { print "Character not found " ; } else { print "Character found"; }

The triple equals operator ( = = = ) not only checks for a value, but what type of value it is: integer, string, Boolean, etc. If a string is not found, you need to use this operator, just in case the character you're searching for is at position 0.

Script that checks which of four browsers the user has:


$agent = $_SERVER['HTTP_USER_AGENT']; if ( strpos(strtoupper($agent), 'MSIE')) { print "Internet Explorer"; } else if (strpos(strtoupper($agent), 'FIREFOX')) { print "Firefox"; } else if (strpos(strtoupper($agent), 'KONQUEROR')) { print "Konqueror"; } else if (strpos(strtoupper($agent), "LYNX")) { print "Lynx"; } else { print $agent; }

How to access a MySQL Database with PHP code

The approach we'll take has three steps:


1.
2. 3.

Open a connection to MySQL itself Specify the database we want to open Close the connection

we'll use the following inbuilt functions:


mysql_connect( ) mysql_select_db() mysql_close()

Step 1 - Open a connection to MySQL

The first job is to actually connect to MySQL. As it's name suggests, mysql_connect( ) does exactly that. Here's the code we're going to be using. But this is just to get your started <?PHP $user_name = "root"; $password = ""; $server = "127.0.0.1 or local host $db_handle =mysql_connect($server, $user_name, $password); print "Connection to the Server opened"; ?>

Step 2 - Specify the database you want to open

You use the mysql_select_db( ) function to specify which database you want to open. The function then returns a true/false value. If it finds your database, a value of true is returned; if your database can't be found then a value of false is returned. $database=student; $db_handle =mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle ); if ($db_found) { print "Database Found"; } else { print "Database NOT Found"; }

Step 3 - Close the connection


Closing a connection to a database is quite easy. If you've used a file handle, as above, you just do this: mysql_close($db_handle);

Reading Records from a MySQL Database with PHP

To read records from a database, the technique is usually to loop round and find the ones you want. To specify which records you want, you use something called SQL. This stands for Structured Query Language. This is a natural, noncoding language that uses words like SELECT and WHERE.

Sample code
<?PHP $user_name = "root"; $password = ""; $database = student"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "SELECT * FROM stud"; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . "<BR>"; print $db_field[sname'] . "<BR>"; print $db_field[sno'] . "<BR>"; print $db_field[m1'] . "<BR>"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?>

Adding Records to a MySQL Database with PHP


1.

2.
3.

4.
5.

Open a connection to MySQL Specify the database we want to open Set up a SQL Statement that can be used to add records to the database table Use mysql_query( ) again, but this time to add records to the table Close the connection

8/18/2011

Mrunalini M

117

Set up a SQL Statement to add records to the database


<?PHP $user_name = "root"; $password = ""; $database = student"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO stud(sname, sno, m1,m2,m3) VALUES ('bill', mca05', 50,78,90)"; $result = mysql_query($SQL); mysql_close($db_handle); print "Records added to the database"; } else { print "Database NOT Found "; mysql_close($db_handle); } ?>

8/18/2011

Mrunalini M

118

Create a Database Table using SQL and PHP

$SQL="CREATE TABLE AddressBook ( ID int(7) NOT NULL auto_increment, First_Name varchar(50) NOT NULL, Surname varchar(50) NOT NULL, email varchar(50), PRIMARY KEY (ID), UNIQUE id (ID) )"; mysql_query($SQL);

8/18/2011

Mrunalini M

119

Updating a Record in a Database Table using SQL and PHP

$SQL = "UPDATE AddressBook SET email = 'new_email_address' WHERE First_Name = 'Bill' AND Surname = 'Gates'"; You can also update an entire column, and change all the values: UPDATE AddressBook SET Surname = LOWER(Surname);

8/18/2011

Mrunalini M

120

Deleting a Record in a Database Table with SQL and PHP


If you want to delete a record in a table, use the DELETE Keyword. Like this: $SQL = "DELETE FROM AddressBook WHERE First_Name = 'Bill' AND Surname = 'Gates'";

8/18/2011

Mrunalini M

121

Using WHERE to limit the data returned


$SQL = "SELECT * FROM AddressBook WHERE First_Name = 'Bill' AND Surname = 'Gates'"; SQL = "SELECT * FROM AddressBook WHERE ID >= '10' ";

8/18/2011

Mrunalini M

122

PHP User Authentication-Walkthrough

Get the username and password from textboxes on a form Open a connection to a database Validated the username and password Check to see if any rows were returned from the database If rows are returned, set a session variable to 1 If no rows are returned, set a session variable to a blank string Built up an error message throughout the code

$uname = $_POST['username']; $pword = $_POST['password']; $user_name = "root"; $pass_word = ""; $database = "login"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $pass_word); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { } else { $errorMessage = "Error logging on"; }

We're selecting all the records in the database where the incoming username and password match the database table fields called L1 and L2: $SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = $pword"; Next, issue the SQL command using mysql_query( ): $result = mysql_query($SQL); We need to check what is returned by the mysql_query() function. The value in $result will either be true (if any records are returned) or false (if none are returned). We're checking to see if there were any errors when the SQL command was issued against the database table. If so, put something in the error message variable:

if ($result) { } else { $errorMessage = "Error logging on"; } If the SQL command was issued successfully, you can see how many rows were returned from the database table. The inbuilt function mysql_num_rows( ) is used for this. If no rows were returned, then that tells you that there's something wrong with either the username or password. $num_rows = mysql_num_rows($result); Next, we test the $num_rows variable to see if it's greater than zero. If it is, then you have a successful logon. If not, then it's invalid.

if ($num_rows > 0) { $errorMessage= "logged on "; } else { $errorMessage= "Invalid Logon"; } In the above code, the number of rows returned could be greater than 1. That would mean that 2 or more people have the same username and password. If you have a website where each user has to be unique, then you obviously want to check if $num_rows = 1. For some websites, it doesn't really matter if 2 or more people have the same login details

Setting a Session

So that a user can be remembered across different web pages, you can use something called a Session. A session is simply the time spent at a particular site or sites. You can store values with sessions, and these values will be available to all pages on the site. When you close your browser, the sessions will end. There are quite a lot of ways to use sessions, but we're only interested in saving a value so that it can be referred to across different pages.

What the code does is to set up a session variable. The value in the variable will be 1, if the user logs on successfully. To set up a session variable, you need to issue the start command: session_start( ); This starts a PHP session. To set up a session variable that you can use to store values, you use this: $_SESSION[ ] In between the square brackets of $_SESSION, you type the name of your variable. Like all variable names, you can call it almost anything you like. Storing values in the session variable is just the same as storing values in a normal variable: $_SESSION['login'] = "1"; After the script runs, you'll have a session variable called 'login' that is set to a value of 1, if the user is OK. You can then use the "header" function to redirect the user to the page on your site for members, page1.php in the code above. header ("Location: page1.php");

On all pages of your site that you want to secure, you'll need to check if the user was successfully logged on or not. After all, what's to stop non members from simply typing the address of the page in their browsers? If you haven't set any checks, then the page will load, whether they are a member or not. To stop this happening, you can check the session variable that you set up on the login page.

In page1.php you need to check for user validation <?PHP session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ?>

User Logout
<A HREF = page2.php>Log out</A> On logout page2.php, <?PHP session_start(); session_destroy(); ?>

Register a New User with PHP Code


$uLength = strlen($uname); $pLength = strlen($pword); if ($uLength >= 10 && $uLength <= 20) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>"; } if ($pLength >= 8 && $pLength <= 16) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>"; }

Register a New User with PHP Code (contd..)


Before checking the username and password against the database, we can check to see if the error message is blank: if ($errorMessage = = "") { } If it's blank, then everything is ok. In which case the rest of the code is executed. If it's not OK, then the user will see the text of the error message displayed. Inside of the if statement for the error message check, we just set up the database code like we did before: if ($errorMessage = = "") { $user_name = "root"; $pass_word = ""; $database = "login"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $pass_word); $db_found = mysql_select_db($database, $db_handle);

Register a New User with PHP Code (contd..)


if ($db_found) { $SQL = "SELECT * FROM login WHERE L1 = $uname"; $result = mysql_query($SQL); $num_rows = mysql_num_rows($result); if ($num_rows > 0) { $errorMessage = "Username already taken"; } else { $SQL = "INSERT INTO login (L1, L2) VALUES ($uname, $pword)"; $result = mysql_query($SQL); mysql_close($db_handle); session_start(); $_SESSION['login'] = "1"; header ("Location: page1.php"); } } }

Other considerations for your User Authentication pages


Some more things worth considering on your login/signup pages: Test if the users is already logged in. That way, they can't sign up repeatedly without closing down the browser Set a cookie for logins, instead of using sessions. You then need to write code to read the cookie data back for every protected page on your site. Collect other information, and store it in your database tables: date and time of login, IP address, etc User's forget their usernames and password. You'll need a link to send them the details. However, don't forget to add some extra security here! Something like a password reminder (memorable date, favourite teacher, etc) is recommended. Enumeration attacks are quite a common way for malicious users to try and gain access to your site. This is when the attacker can simply sit at his/her pc screen and enter the username and password over and over again, looking for "error message" clues. To thwart this type of attack, you might want to limit how long a user has to log on to your site. A good way to do this is by setting a session to end after so many minutes. For more such script ideas: http://www.weberdev.com/get_example-4267.html

An Introduction to PHP Functions


What is a Function? A function is just a segment of code, separate from the rest of your code. You separate it because it's nice and handy, and you want to use it not once but over and over. It's a chunk of code that you think is useful, and want to use again. <?PHP function display_error_message( ) { print "Error Detetceted"; } display_error_message( ); ?>

PHP Variable scope and functions

There's a thing called scope in programming. This refers to where in your scripts a variable can be seen. If a variable can bee seen from anywhere, it's said to have global scope. In PHP, variables inside of functions can't be seen from outside of the function. And functions can't see variables if they are not part of the function itself.

<?PHP $error_text = "Error Detetceted"; display_error_message( ); function display_error_message( ) { print $error_text; } ?> Run the script, and you'll get a PHP error message about " Undefined variable".

Likewise, try this script: <?PHP display_error_message( ); print $error_text; function display_error_message( ) { $error_text = "Error message"; } ?> This time, the variable is inside the function, but we're trying to print it from outside the function. You still get an error message.

The correct version: <?PHP display_error_message( ); function display_error_message( ) { $error_text = "Error message"; print $error_text; } ?> Here, we have both the variable and the print statement set up inside of the function. The error message now prints.

PHP Functions and Arguments


Arguments Pass the variable over to your functions by typing them inside of the round brackets of the function name. <?PHP $error_text = "Error message"; display_error_message($error_text); function display_error_message($error_text) { print $error_text; } ?>

Try it like this: $error_text = "Error message"; display_error_message( ); You'll get an error message from PHP. Something like this: "Warning: Missing argument 1 for display_error_message( )" That's telling you that your function has been set up to take an argument, but that you've left the round brackets empty when you tried to call the function. Your functions can have more than 1 argument. Just separate each argument with a comma. Like this: function error_check($error_text, error_flag) { } To call this function, you'd then need to hand it two arguments: $error_text = "Error message"; error_flag = 1; error_check($error_text, error_flag); So, to recap: To pass something to a function, create an argument To call a function that has an argument, don't leave the round brackets empty

A PHP Function to check for blank Textboxes


If you remember the script that we wanted to create earlier it was this:

Get the text that a user entered in a textbox on a form Trim any blank spaces from the left and right of the text Check that what you have left is not a blank string

Here's a script that does all three items on our list: <?PHP $user_text = trim("Bill Gates"); display_error_message($user_text); function display_error_message($user_text) { if ($user_text == "") { print "Blank text box detected"; } else { print "Text OK"; } } ?>

Returning a Value from a PHP Function

<?PHP $total_spent = 120; $order_total = calculate_total($total_spent); print $order_total; function calculate_total($total_spent){ $discount = 0.1; if ($total_spent > 100) { $discount_total=$total_spent - ($total_spent * $discount); $total_charged = $discount_total; } else { $total_charged = $total_spent; } return $total_charged; } ?>

Here's the script:

Call by Value
<?PHP $Variable_Value = 10; print "Before the function call = " . $Variable_Value . "<BR>"; example($Variable_Value); print "After the function call = " . $Variable_Value; function example($Variable_Value) { $Variable_Value = $Variable_Value + 10; print "Inside of the function = " . $Variable_Value . "<BR>"; } ?> Output: Before the function call = 10 Inside of the function = 20 After the function call = 10

Call By Reference
<?PHP $Variable_Value = 10; print "Before the function call = " . $Variable_Value . "<BR>"; example($Variable_Value); print "After the function call = " . $Variable_Value;

function example(&$Variable_Value) {

$Variable_Value = $Variable_Value + 10; print "Inside of the function = " . $Variable_Value . "<BR>"; } ?> Output: Before the function call = 10 Inside of the function = 20 After the function call = 10

PHP Server Variables


PHP stores a list of information about the server. To get at the values in Server Variables, the syntax is this: $_SERVER['Server_Variable'] This will include things like, the browser the visitor is using, the IP address, and which web page the visitor came from. Here's a script to try with those three Server Variables. $referrer = $_SERVER['HTTP_REFERER']; $browser = $_SERVER['HTTP_USER_AGENT']; $ipAddress = $_SERVER['REMOTE_ADDR']; print "Referrer = " . $referrer . "<BR>"; print "Browser = " . $browser . "<BR>"; print "IP Adress = " . $ipAddress; These are useful if you want to log your stats, or to ban a particular IP address!

Server Variables (Contd..)

The server variables are held in an array (associative), so you can use a foreach loop to get a list of all available ones. Try this script:
<?PHP foreach($_SERVER as $key_name => $key_value) { print $key_name . " = " . $key_value . "<br>"; } ?>

What the script does is to loop round all the server variables and print out the keys and values in the SERVER array.

HTTP Header() Function

When you request a web page be brought back to your browser, you're not just bringing back the web page. You're also bringing back something called a HTTP HEADER. This is some extra information, such as type of programme making the request, date requested, should it be displayed as a HTML document, how long the document is, and a lot more besides. One of the things HTTP HEADER also does is to give status information. This could be whether the page was found (404 errors), and the location of the document. If you want to redirect your users to another page, here's an example:

<?PHP header("Location: http://www.google.com"); ?> <html> <body> </body> </html>

The PHP Include( ) Function


Being able to include other files into your HTML code, or for your PHP scripts, is a useful thing. The include( ) function allows you do this. Suppose you have a text file that you want to include in a web page that you've already got up and running. You could copy and paste the text from the file straight into you HTML. Or you could use the include( ) function.

<HTML> <HEAD> <TITLE>Include files</TITLE> </HEAD> <BODY> <H3>Normal text here </H3> Normal text written in a HTML Editor <H3>Include File here</H3> <?PHP include "textfile.txt" ; ?> </ BODY> </ HTML >

HTML special security

what the htmlspecialchars( ) function does turns the HTML into the special character codes.
$first_name = $_POST['first_name']; $first_name = htmlspecialchars($first_name); echo $first_name;

A function similar to htmlspecialchars( ) is htmlentities( ). Instead of the above, you can do this:
$first_name = $_POST['first_name']; $first_name = htmlentities($first_name); echo $first_name;

The difference between the two is that htmlentities( ) will check for non English language characters, such as French accents, the German umlaut, etc. So if you think your attacker might launch an attack in a language that is not English, then use this.

HTML special security (Contd..)

A third security option for your HTML forms is to use the strip_tags( ) function. It will, as its name suggests, strip all HTML for you. You can, however, tell this function to ignore HTML that you consider harmless, or that you want to include. Here's the syntax: strip_tags($string, html_tags_to_ignore) So the first thing you need to provide the strip_tags( ) function with is the string of text you're trying to check. The second thing, html_tags_to_ignore, is optional. If you leave this off then the function will strip all tags. Here's two example to try: $first_name = $_POST['first_name']; $first_name = strip_tags($first_name); echo $first_name; More on security and HTML forms can be found here: http://www.secguru.com/param/commonly_asked_cross _site_scripting_questions

Introduction to Working with Files in PHP


<?PHP $file_contents = readfile("dictionary.txt"); print $file_contents; ?> If you had a folder called files in your directory, you could do this: $file_to_read = "files\dictionary.txt"; print readfile($file_to_read); The readfile( ) function is useful if all you want to do is open up a file and read its contents file_get_contents(file_to_read); Another function that just reads the contents of a file is file_get_contents( )

Opening a file with fopen( ) in PHP

A better method to open files is with fopen( ). This function gives you more options that, such as setting whether the file is for reading only, for writing to as well, and a few more options. <?PHP $file_contents = fopen("dictionary.txt", "r"); print $file_contents; fclose($file_contents); ?> fopen( ) doesn't actually read the contents of a file. All it does is to set a pointer to the file you want to open. It then returns what's call a file handle. All you're doing is telling PHP to remember the location of the file. The "r" on the end means "open this file for reading only".

use fgets( ). This will read a specified number of character on a single line of text. It's typically used to loop round and read each line of text. When you're using fgets( ), you also need to check when the end of the file has been reached. This is done with the inbuilt function feof - file, end of file. <?PHP $file_handle = fopen("dictionary.txt", "r"); while (!feof($file_handle)) { $line_of_text = fgets($file_handle); print $line_of_text . "<BR>"; } fclose($file_handle); ?>

Another point to bear in mind about fgets is that it can take (and often does) a second argument the size of the line to read: fgets($file_handle, line_size); The line size needs to be in bytes. The default is 1024. But this line size is only optional in PHP version 4.2 and above If you're really packing a lot of information into each line, then just increase the number for line size.

File Open Modes

The other options.

Mode r r+ w

w+ a

a+ b

Meaning Use this to read a file only. The pointer is set to the start of the file. Use this to read and write to a file. The pointer is set to the start of the file. Use this to write to a file only. It will erase the entire contents of the file you have open. If no file exists with your chosen name, then it will create one for you Same as "w", but used to read and write. Use this to write to a file only, and append data to the end of the file. Doesn't erase contents, in other words. Same as "a", but with read access as well. Force PHP to open the file in binary mode.

Writing to files in PHP

fwrite():

file_put_contents( ) It is used in the same way as fwrite(), but has an optional third parameter: file_put_contents($file_handle, $file_contents, context); The context option can be FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX. So to append to the file, just do this: file_put_contents($file_handle, $file_contents, FILE_APPEND);

<?PHP $file_handle = fopen("testFile.txt", "w"); $file_contents = "Some test text"; fwrite($file_handle, $file_contents); fclose($file_handle); print "file created and written to"; ?>

PHP Cookies
What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

How to Create a Cookie?


The setcookie() function is used to set a cookie. The setcookie() function must appear BEFORE the <html> tag. Syntax:

setcookie(name, value, expire);

Examples

In the example below, we will create a cookie named "user" and assign the value msrit" to it. We also specify that the cookie should expire after one hour:

<?php setcookie("user", msrit", time()+3600); ?> <html> .....

The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Examples (contd..)
You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html> ..... In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>

In the following example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>

How to Delete a Cookie?


When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> What if a Browser Does NOT Support Cookies? If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms

PHP Simple Mail


The simplest way to send an email with PHP is to send a text email. In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail: <?php $to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>

More on Strings (Examples)

Finding length of a PHP string using strlen


$str = 'test string'; $len = strlen('$str'); echo $len; // this will output 11

Checking substring existence using strpos PHP string function strpos can be used to check for substring existence. See example below:
$str = 'test string'; $sub_str = 'str'; if (strpos($str, $sub_str) === false) echo "Substring not found"; else echo "Substring exist in given string";

Note the use of === operator because == will not work as expected since the return position can be 0 (start of string). The offset value can be used here to specify from where to start searching. see example below:
$str = 'abcdefabcdef'; echo strpos($str, 'a', 1); // will print 6 not 0

More on Strings (Examples) Contd..


Finding occurrence of a string The strstr PHP string function is used to find the first occurrence. See below
$email = 'user@domain.com'; $domain = strstr($email, '@'); echo $domain; // this will print '@domain.com'

So strstr will return part of the string, starting from the given substring. If given substring does not exist, it will return FALSE. This string function is case-sensitive. For case-insensitive searches stristr is used , see below: Function strrchr(string str, char chr) is used to find the last occurrence of a character. This function returns the portion of string which starts at the last occurrence of given character and goes up to the end. see example below:
echo strrchr("abcdexyz", "e"); // will print exyz echo substr(strrchr("module.filename.html", "."),1); // will print html $domain = stristr('USER@EXAMPLE.com', 'e'); echo $domain; // This will print ER@EXAMPLE.com

More on Strings (Examples) Contd..


Return part of a string: Substring The PHP function substr( string string, int start [, int length]) can be used to return part of a given string specified by start and length parameters. see examples below: echo substr("abcdef", 1); // will output "bcdef" , start 1 to end. echo substr("abcdef", 1, 3); // will output "bcd", 1 to 3 echo substr("abcdef", 0, 4); // will output "abcd" echo substr("abcdef", 0, 8); // will output "abcdef" Using curly braces we can also return a character at given position. For example

We can also use negative value of start parameter to return part from the end of string. see examples below:

$string = 'abcdef'; echo $string{0}; // will print a echo $string{3}; // will print d

substr("abcdef", -1); // returns "f" substr("abcdef", -2); // returns "ef" substr("abcdef", -3, 1); // returns "d"

More on Strings (Examples) Contd..

Also negative value of length parameter can be used. In this case it will omit that many characters from the end of the string. See below:
echo substr("abcdef", 0, -1); // will omit 1 char from the end and returns "abcde" echo substr("abcdef", 2, -1); // returns "cde" echo substr("abcdef", 4, -4); // returns "" echo substr("abcdef", -3, -1); // returns "de"

More on Files (Examples)

<?php $file="WARNING-WIN.TXT"; //The file you want to save echo "Copy File <b>$file</b>"; if(!@copy($file, "c:/Apache/htdocs/$file.bak")){ //Name of the saved file echo "<p>File $file not found"; }else{ echo "<p>The file \" $file \", successfully saved"; } ?>

Reading And Using Files <? function average($filename) { $path = c:/allfiles/college"; $x= -1; if($file = fopen("$path/$filename", "r")) { while(!feof($file)) { $therate = fgetss($file, 255); $x++; $count = $count + $therate; } fclose($file); } $average = ($count / $x); print($average); } ?>

Exercises

Examples in web pages

You might also like