Web Programming With PHP
Web Programming With PHP
Web Programming With PHP
8/18/2011
Mrunalini M
PHP is the most popular scripting language on the web Used to enhance web pages
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
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
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
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
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
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
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
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
<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
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
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
Reserved words
8/18/2011
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
Characters are single bytes String literals use single or double quotes
Mrunalini M 22
8/18/2011
Primitives-Contd..
Embedded variables are NOT interpolated Embedded escape sequences are NOT recognized
Embedded variables ARE interpolated Embedded escape sequences ARE recognized
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
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
8/18/2011
Mrunalini M
27
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
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
8/18/2011
Mrunalini M
32
Logical Operators
Boolean Operators
8/18/2011
Mrunalini M
33
8/18/2011
Mrunalini M
34
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
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
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
8/18/2011
Mrunalini M
49
Operator Precedence
++ -! * / % + - . < <= > >= == != === !== && || = += -= *= /= .= %= &= |= ^=
Constants in PHP
define() function is used to declare constants Syntax:
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
8/18/2011
Mrunalini M
53
8/18/2011
Mrunalini M
54
GET method
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
8/18/2011 Mrunalini M 59
ACTION contd..
8/18/2011
Mrunalini M
60
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
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
<html> <head> <title>A BASIC HTML FORM</title> <?PHP $username = $_POST['username']; print ($username); ?> </head>
8/18/2011 Mrunalini M 63
8/18/2011
Mrunalini M
64
8/18/2011
Mrunalini M
65
8/18/2011
Mrunalini M
66
8/18/2011 Mrunalini M 67
8/18/2011 Mrunalini M 68
<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
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
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 ; ?>"
8/18/2011
Mrunalini M
71
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
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
= = = =
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
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);
Another way to put values into an array is like this: $seasons = array();
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.
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; }
$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]; }
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";
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
$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>"; } } ?>
$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
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
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 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.
$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);
<?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.
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.
Open a connection to MySQL itself Specify the database we want to open Close the connection
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"; ?>
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"; }
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); } ?>
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
8/18/2011
Mrunalini M
118
$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
$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
8/18/2011
Mrunalini M
121
8/18/2011
Mrunalini M
122
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(); ?>
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
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( ); ?>
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.
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
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"; } } ?>
<?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; } ?>
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 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!
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.
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:
<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 >
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.
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
<?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( )
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.
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.
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.
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:
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).
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>
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
Finding occurrence of a string The strstr PHP string function is used to find the first occurrence. See below
$email = '[email protected]'; $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('[email protected]', 'e'); echo $domain; // This will print [email protected]
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"
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"
<?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