Professional Documents
Culture Documents
ISBN 978-0-557-04160-2
Learn PHP
The EZ Way
Start Making PHP Applications in Minutes
Copyright Scriptsez.net
!"
%
34 56 34 3 77 8937 :5 7434 :
9
9
6:;7 :5 8<<3 5
9 ==8
%& ;>?
6:;7 <4 88>; 49 4377 ;>?
%
345644 4:3
543=4%&7
543===8 4
7 5473988;3= 34?;:3
@<8;4&>=
4 44
Chapter
GETTING STARTED
WITH HTML
1 Getting Started With HTML
"
When the above code is saved as .html file, and opened in your browser
then it will display:
An HTML web page consists of two parts, the HEAD part and the BODY
part. HEAD part comes before BODY part.
In the HEAD part, you define how the content in the body part of the web
page will be displayed. HEAD part contains the title of the web page, and
formatting of the text, which will be displayed on the body part of the web
page.
All HTML pages begin with <HTML> and end with </HTML>
HEAD part begins with <HEAD> and ends with </HEAD>
'
<HTML>
<HEAD>
<TITLE>This is my First Web page</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
Above code will display a blank web page with the title
“This is my First Web page”
Now, lets come to the BODY part. The body part as discussed above
contains the content of the web page.
To display some text in a web page, just add the text in between the body
tag.
<HTML>
<HEAD>
<TITLE>This is my First Web page</TITLE>
</HEAD>
<BODY> My first Web page
</BODY>
</HTML>
The above code will not only display the title “This is my First Web page”
but will also display the text “My first Web page” on the webpage.
Similarly, to make the text look italic, use <i></i> instead of <b></b>
You can also display the text both bold and italic by using <b><i></i></b>
similarly to underline the text use tag <u></u>
For Example:
<HTML>
<HEAD>
<TITLE>This is my First Web page</TITLE>
</HEAD>
<BODY> <b><i>My first Web page</i></b>
</BODY>
</HTML>
To make the text size larger or smaller, use the <font> tag.
<font size=”4” color=”#FFCC00”>Some text</font>
+
The value 4 determines the size of text that will be displayed and the
value of color gives color to text.
To display this text bold and italic, you can use <b></b> and <i></i> tags
in between font tag.
For Example:
The above code will display the formatted text bold and italic.
To bring the text at center of the web page, use <center></center> tag.
For Example:
<center>
<font size=”4” color=”#FFCC00”><b><i>Some text</i></b></font>
</center>
,
Similarly you can add links to images as well by adding image tag inside
link tag.
Example:
<a href=”http://www.scriptsez.net”>
<img src=”http://www.scriptsez.net/logo.gif”>
</a>
.
Chapter
PHP Basics
2 PHP BASICS
In this chapter you will be able to get know how of PHP language, how it
works and how you can make php scripts easily!
In an HTML page, PHP code is enclosed within special PHP tags. When
a visitor opens the page, the server processes the PHP code and then
sends the output (not the PHP code itself) to the visitor's browser. It
means that, unlike JavaScript, you don't have to worry that someone can
steal your PHP script.
Things to remember:
Save the above code in blank file as webpage.php and run this file in your
browser, you will see the following output:
This text is written with PHP
As you might have noticed that the php code starts with <?php and ends
with ?>
To output we use echo just like in C language.
<?php
//Sender Email
$sender=”admin@scriptsez.net”;
//Receiver Email
$receiver=”user@scriptsez.net”;
//Subject of email
$subject=”Hi!, this is my first email sending Script”;
//Message
$message=”Hi,\n This is the message of the email.”;
//Email Header
$mailheaders="Return-path: Your Name <$sender>\n";
$mailheaders.="From: Your Name <$sender>\n";
$mailheaders.="Reply-To: $sender\n";
//Now Send Email
$sendmail=mail($receiver, $subject, $message, $mailheaders);
//Check whether mail is sent or not
if($sendmail){
echo “Email has been sent”;
}else{
echo “Email could not be sent”;
}
?>
The sentence that begins with // are the comments, they can be inserted
in a code but are unreadable by PHP.
The above function filesize() displays the size of file in bytes, you can
convert it into Kilobytes by dividing the output by 1024.
<?php
$filesize=filesize("index.html");
$filesizeinkb=$filesize/1024;
echo “$filesizeinkb”;
?>
To round off the value to two decimal places just use the round()
function.
<?php
$filesize=filesize("index.html");
$filesizeinkb=$filesize/1024;
$rounded_value=round($filesizeinkb,2);
echo “$rounded_value”;
?>
"
round (Parameter1,Parameter2);
Parameter 1 is the numeric value that we want to round off and
Parameter 2 is the number of decimal places up to which the number will
be rounded off.
<?php
//Give the value of variable
$value=”75”;
if($value>=”60”){
echo “Pass”;
}else{
echo “Fail”;
}
?>
You can use elseif condition if there are more than two possibilities.
For Example in the code below, we will display “Positive” when variable is
greater than 60 and “Neutral” when variable is equal to 60 and “Negative”
when variable is less than 60, so,
<?php
//Give the value of variable
$value=”60”;
if($value>”60”){
echo “Positive”;
}elseif($value==”60”){
'
echo “Neutral”;
}else{
echo “Negative”;
}
?>
</form>
</BODY>
</HTML>
In the above code, within the form code, we have described the type of
input, the first one is TEXT and the other one is SUBMIT type.
The TEXT type displays a text box through which the user inputs the
value, and submit type displays a submit button which upon pressing
submits the input data.
There are several input types, namely:
Hidden: which contains the value in it but is not visible on the page.
Radio: which displays the radio button.
Select: which displays pull down menu with all the available options.
And many more.
+
If ($filesize<=$max_filesize){
copy($HTTP_POST_FILES['picture']['tmp_name'],$HTTP_POST_FILES['picture'][
'name']);
echo “File has been uploaded”;
}else{
echo “Filesize is greater than $max_filesize Kb”;
}
}
?>
<form method=post action=”?action=upload” enctype=”multipart/form-data”>
Select File: <input type=file name=picture> <input type=submit
value=”UPLOAD”>
</form>
</BODY>
</HTML>
copy function copies the file from temporary upload directory to your
defined directory. In the above code script will upload the file to the folder
in which you have the script, to upload the file in a sub directory inside
your script directory, use the following code:
copy($HTTP_POST_FILES['picture']['tmp_name'],”sub_dir/”.$HTTP_POST_FILE
S['picture']['name']);
Above code will upload the file to sub_dir folder (it must already exist).
,
<?php
$file=”my_webpage.php”;
if(file_exists($file)){
echo “File $file Exists”;
}else{
echo “File $file does not exist”;
}
?>
<?php
$directory=”dir”;
if(is_dir($directory)){
echo “Folder $directory Exists”;
}else{
echo “Folder $directory does not exist”;
}
?>
.
2.10 Loop
Loops are very common in any program. Loop is a repetitive task
assigned to script. Two most common types of loop are “for” and “while”.
For Loop
Here is a sample of a “for” loop:
<?php
for($i=1;$i<=5;$i++){
echo “This is $i line<BR>”;
}
?>
This is 1 line
This is 2 line
This is 3 line
This is 4 line
This is 5 line
Same text is print five times only the line number changes each time.
For loop consists of three parameters each separated by “;” semicolon.
Parameter 1 $i=1 is executed only once.
Parameter 2 $i<=5 is the condition which must be meet to go inside the
loop.
In the above code $i=1, $i is a variable to which I have assigned a value
of 1. The script then checks whether $i is less than or equal to 5, if the
condition is true, then script goes inside the loop. The code inside the
loop is:
While Loop
While loop is similar to for loop, but it only has one parameter.
Look at the code below:
<?php
$i=1;
while($i<=5){
echo “This is line $i<BR>”;
$i++;
}
?>
You can see that initial value of $i is defined outside the loop. Then while
loops checks for the value of $i, if it is less than or equal to 5 then it goes
inside the loop. Inside the loop, the value of $i is increased by 1, so the
loop continues until the value of $i becomes greater than 5.
If you do not increase the value of $i inside the loop, then loop will
continue endlessly, and can cause your system to crash.
Chapter
Using Database
3 USING DATABASE
In the line
$counter_file = file(“stats.txt”);
"
Above code counts raw visits, it means that if a user refreshes this page
100 times it will count it as 100 visits, which is true in case of raw visits
but what if you want to count each user visit as a single hit (which is
called unique visit), for this purpose we will use users IP address to
recognize the user so that one user is counted as 1 hit.
We will require two files one which stores last users IP address (we name
it ip.txt) and other, which stores users statistics (stats.txt).
<?php
//Get the IP address of the user and store it in variable ip
$ip=getenv(REMOTE_ADDR);
//Read the file which contains raw hits information
$counter_file = file(“stats.txt”);
$current_stats = $counter_file[0];
//Read the file which contains last users IP address
$ip_file = file(“ip.txt”);
$previous_ip = $ip_file[0];
//Compare last ip with current users IP
if($ip==$previous_ip){
$new_stats = $current_stats;
}else{
//New ststistics is Old Statistics + 1
$new_stats = $current_stats+1;
//Now write this information to the database file
//Open the file and make it blank
'
$file_open=fopen(“stats.txt”,”w”);
//Write latest statistics to file
fwrite($file_open,$new_stats);
//Close the file
fclose($file_open);
//Now Open ip file
$new_ip= fopen(“ip.txt”,”w”);
//Write current user IP in it
fwrite($new_ip,$ip);
//Close the file
fclose($new_ip);
}
//Output the last number of visits
echo “Number of Visitors: $new_stats”;
?>
Lets move on and make a user form which asks for users to enter their
name and email, which we store in the database.
<HTML>
<HEAD>
<TITLE>Database User Form</TITLE>
</HEAD>
<BODY>
<form method=post action=”?action=submit_info”>
Name: <input type=text name=”name”><BR>
Email: <input type=text name=”email”><BR>
<input type=submit value=”Submit”>
</form>
<?php
//Start of PHP Coding
//If action is submit_info then
if($action==”submit_info”) {
//Open the file file.txt and take the cursor at the end of file
$store=fopen(”file.txt”,”a+”);
//write the submitted information
fwrite($store,”$name||$email\n”);
//Close the file
fclose($store);
//Notify the user that his information has been submitted
echo “<HR>Information has been successfully submitted.”;
}
?>
</BODY>
</HTML>
The <form> code is an HTML code through which name and email fields
are submitted it has been discussed in 3rd chapter.
In the above PHP code if statement has been used, it means that if a
particular condition is meet then the code in between the “{“ and “}” will be
allowed to run.
The line:
$store=fopen(”file.txt”,”a+”);
+
$file_open=fopen(“stats.txt”,”w”);
used in the previous counter example but in this case “a+” has been used
instead of “w” which means that the file should already exist and
everything written in the file will not be deleted instead it moves the cursor
to the last line of the file.
The code below:
fwrite($store,”$name||$email\n”);
writes name and email of the user, notice that I have used || in between
$name and $email I will tell you useful purpose of this in the next example
where we will retrieve the information from the text file.
\n in the above code moves the cursor to one line below the line on which
data has been entered (it is just like pressing enter key), so that next time
the data will be entered on a blank new line instead of continuing it from
the same line.
The code:
fclose($store);
as described previously, closes the opened file.
NOTE: TO RUN THE ABOVE CODE YOU MUST CREATE A TEXT FILE file.txt IN
THE SAME DIRECTORY IN WHICH YOU PUT THE FILE WITH THE ABOVE USER
FORM CODE AND SET PERMISSION OF file.txt TO CHMOD 777
Now lets retrieve the data from the text file, which users have submitted.
<?php
//Store all the information of file.txt in variable
$data_file=file(“file.txt”);
//Start the loop
for($i=0;$i<sizeof($data_file);$i++){
$info = explode(“||” , $data_file[$i]);
echo “Name: $info[0] <BR> Email: $info[1] <HR>”;
}
?>
,
The above code displays name and email of all the users.
Here is the description of the code:
On line:
$data_file=file(“file.txt”);
We store all the information of file.txt in the variable which we have
named $data_file
On the line:
for($i=0;$i<sizeof($data_file);$i++){
We have started a loop which scans all the lines of the file in which we
have used a variable $i and given it a value 0 since 0 is considered as first
line in PHP. Then we have provided a condition upon which the loop will
end that is:
$i<sizeof($data_file)
It means that the loop will continue to do its specified task until the value
of $i is equal to total number of lines minus one (since the last line is left
blank).
Now,
$i++
means that every time the condition inside the loop is over it increases the
value of $i by 1 that is if it was zero and after loop condition ran now it is 1
then the condition is again checked whether it is less than total number of
lines. The loop continues to run until the value of $i becomes equal to the
total number of lines.
The line
$info = explode(“||” , $data_file[$i]);
Assigns the value of $i line to string $info and tells this variable to
separate the values whenever you see || this is what is called an ARRAY,
and array is a variable which can hold more than one piece of information
.
Now you have learnt how to make counters and user forms,
don’t just limit it to these two applications, you can create
uncountable number of applications with these simple functions
that have been described.
In the above code, replace the value of $db_host value, i.e. localhost to
your own host, well, it is mostly localhost on most of the servers you may
not need to change it. Provide the value of your database name, i.e.
replace
db_nm to your own database name, similarly provide your database
username and password information, save this file. We will use this file for
connecting with database in script.
Now lets create your first MySQL Database script:
Let us start by making a search engine:
<?php
//Load Database Login information file
include "conf.php";
//Connect to database or give error if failed
$db=mysql_connect($db_host,$database_user,$database_pass) or
die("<b>MySQL Error:</b> Unable to connect to database please check that you
have provided the correct <li>Database Login username<li>Database Login
Password");
//Select the database
mysql_select_db($db_name,$db)or die("<b>MySQL Error:</b> Unable to select
database please check that you have provided the correct <li>Database name");
//Create table if not exists
$sqlm= mysql_query("CREATE TABLE search_tbl(op INT NOT NULL
AUTO_INCREMENT PRIMARY KEY,name TEXT NOT NULL,email TEXT NOT
NULL,telephone INT(18) NOT NULL)");
echo "<form method=post action=?action=add_entry>";
echo "<center>ADD AN ENTRY</center><BR>";
echo "NAME: <input type=text name=name><BR>";
echo "EMAIL: <input type=text name=email><BR>";
echo "TELEPHONE: <input type=text name=tel maxlength=18><BR>";
echo "<input type=submit value=SUBMIT>";
echo "</form>";
//If action is add_entry
if($action=="add_entry"){
//Check whether all the fields are filled
if($email!="" && $name!="" && $tel!=""){
$insert=mysql_query("INSERT INTO search_tbl SET
name='$name',email='$email',telephone='$tel’");
if($insert){
//If entry has been inserted into database, then output the message
echo "<BR>Entry has been successfully added.";
}
}else{
echo "Please fill all the fields";
}
}
?>
}
}
?>
You can see that the upper part of the code is same that is:
"
that is acceptable for it, the column op can only store integer values, NOT
NULL means that if no value is specified it will take some value by itself it
will not be left blank, AUTO_INCREMENT means that the value will
increase by one from the row above it. For example, If it was 1 in the row
above it then it will now be 2. The column name is TEXT type, that is, we
can store text as well as numeric values in it. Telephone is again INT but
we have here defined that int value can be as long as 18 characters.
From the next line of add.php, search entry addition form is created. The
next portion adds the search entry to the database.
The code:
$insert=mysql_query("INSERT INTO search_tbl SET
name='$name',email='$email',telephone='$tel’”);
Inserts the submitted information to the database, that is, it creates a new
row in the database and adds $name in column name, $email in column
email and $tel in column telephone.
Now lets discuss the code of “search.php”
The line:
$list=mysql_query("SELECT * FROM search_tbl WHERE name LIKE
'%$sname%'");
lists all the rows in the table “search_tbl” which have the name similar to
the $name variable.
The code:
$results=mysql_num_rows($list);
Counts all the rows which meet the search criteria.
Now we want the output of the searched rows for this purpose, while loop
has been used.
Which will continue until all the fetched rows have been processed.
For each searched row of the table, we define:
$row=mysql_fetch_array($list)
'
so $row becomes an array, and we can now output our desired column
value, to show the output of the values of column “name”, “email” and
“telephone”, we use:
$row[name]
$row[email]
$row[telephone]
Of course to show the output we use it inside echo.
You can now create a MySQL Counter, instead of text-based database,
use MYSQL. You have to create table for the counter with two columns,
one containing hits statistics and the other containing the IP address of
the visitor.
if($array[ip]==$user_ip){
$cstats=$array[stats];
}else{
//Add 1 to current stats
$cstats=$array[stats]+1;
$updt=mysql_query(“UPDATE counter SET ip=’$user_ip’,stats=’ $cstats’”);
}
//Output the Result
echo “Total Number of visiors: $cstats”;
?>
+
Chapter
Image Handling
4 Image Handling
With PHP, you can create thumbnails, convert images into different
formats and even create your own images.
,
$sourceName = "logo.gif";
//Specify the path where thumbnail is generated
$thumbPath =”.”;
//Name of the created thumbnail
$thumbName = "test_thumbnail.png";
// Intended width of thumb
$thumbWidth = 60;
//Get the image type
$dc=substr_count($sourceName,".");
$tmp=explode(".",$sourceName);
$type=$tmp[$dc];
if($type=="jpg"){
$sourceImage = imagecreatefromjpeg($sourceName);
}elseif($type=="gif"){
$sourceImage = imagecreatefromgif($sourceName);
}elseif($type=="png"){
$sourceImage = imagecreatefrompng($sourceName);
}
//Get the width of original image
$sourceWidth = imagesx($sourceImage);
//Get Height of Original Image
$sourceHeight = imagesy($sourceImage);
//Generate Thumbnail Height
$thumbh=($sourceHeight/$sourceWidth)*$thumbWidth;
//Create Thumbnail
$targetImage =ImageCreateTrueColor($thumbWidth,$thumbh);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,
$thumbh,imagesx($sourceImage),imagesy($sourceImage));
//Generate PNG thumbnail
imagepng($targetImage, $thumbPath."".$thumbName,100);
// By now, the thumbnail is copied into the $thumbpath
// as the file name specified in $thumbName, so display
echo "<img src=\”$thumbpath/$thumbName\” alt=''>";
?>
.
imagegif($targetImage, $thumbPath."".$thumbName,100);
we can also output in jpg format by using:
imagejpeg($targetImage, $thumbPath."".$thumbName,100);
The last line outputs the thumbnail.
Since the target image size is same as that of the source image, so we
have used:
$image=getimagesize($sourceimg);
So, $image becomes an array, and width of the image is:
$ image[0] and height is $image[1]
The line:
$background = imagecolorallocate($image, 255, 255, 255);
Specifies the background color of the image.
The line:
imagefilledrectangle($image, 1, 1, $width - 2, $height - 2, $background);
Fills the image with the background color, leaving 1 px from the left, 1
from the top and 1 from the right and one from the bottom so that it
appears as a black border.
The following code:
imagestring ($image, 3, 5, 6, "This is Text", $textColor);
Writes the text “This is Text” on the image 3 is the size of the text (It
ranges from 1 to 5), 5 is the left margin and 6 is the top margin.
Chapter
PHP Sessions
5 PHP Sessions
"
Remember that it must come before header (output) is sent, or else it will
not be initialized.
If we want to store the value of a variable, say $name, the code which
stores the value of $name variable will be:
$_SESSION[‘name’] = “Any Value”;
To remove the variable from this session, use:
unset($_SESSION[‘name’]);
To end the current session, you can use:
session_destroy();
One of the most useful feature of PHP sessions is in validating whether
user is logged in or not, here is the example:
<?php
session_start();
//Password of login access
$pass=”admin”;
if($act==”logout”){
session_destroy();
}
if($act==”login”){
if($pass==$password){
$_SESSION['verify']=$pass;
}else{
echo “Wrong Password.<BR>”;
}
}
if (!isset($_SESSION['verify'])){
echo “Please login<BR>”;
echo “<form method=post action=’?act=login’>”;
echo “Password: <input type=password name=’password’> <input type=submit
value=’Login’></form>”;
}else{
if($_SESSION['verify']==$pass){
//Logged in message and content
'
In the above code, you can see that the line that starts the session is:
session_start();
As mentioned earlier that this code comes before any output is sent.
Password of login is stored in variable $admin and its value is admin
If there is a request for logout then:
session_destroy();
the above function destroys the login session if it exists.
Now if there is a request for logging in, then:
User input password is validated if password entered is equal to the
“admin” then a session variable is set:
$_SESSION['verify']=$pass;
The name of this session variable is “verify” and its value is the value of
password.
The code:
if (!isset($_SESSION['verify'])){
checks whether any session variable having name “verify” exists or not, if
it does not exists then a user login form appears.
If the “verify” session variable exists, then the value of this variable is
matched with the password using code:
if($_SESSION['verify']==$pass){
If it matches then message “You are successfully logged in” is
displayed as well as a logout link, user can click this link to log out and
destroy the session.