Sie sind auf Seite 1von 48

ISBN 978-0-557-04160-2

Published By: Lulu.com


Copyright Year: 2007
Copyright Scriptsez.net. All rights reserved.
The above information forms this copyright notice: © 2007 by Scriptsez.net. All rights
reserved.

ISBN 978-0-557-04160-2

  

 

Learn PHP
The EZ Way
Start Making PHP Applications in Minutes

Copyright Scriptsez.net



  


     

  
    

  !  "


  #$%&  '
 ()#&%%$% % *%!  +
 $&$ !  ,
" $-!.

  


 /  


 &- 0)1#(#% $ 
  $& % 
 0$% %& 
"  -$(  "
' (  )%) '
  $%1$()#&
+ 1)$( +
, ( # %)#0(1%) .
. )) 

 


 

 /  


 (%( %  
 &0%  

 



   ,


 # %$%1& ,
 )2 #%$&$ %)(( # %()#&% 
 # %$0)1#) &$  

   

"   "


"  ) "



  


 ! "


%
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

4 5 39  <6


34 56 4  534 7
4 :

9
9  @83=  :3 3 8<4  ;   564 
93;5; =93 7 3;7  8<<3? 5> 
34 56 3 74 
8937
6:;7?:
3=
3477  >4  7






  

Chapter

GETTING STARTED
WITH HTML
1 Getting Started With HTML

1.1 Basic Q and A’s:


What is HTML?
HTML (Hyper Text Markup Language) is a computer language devised to
allow website creation.
How does it Work?
HTML consists of a series of short codes (known as tags) typed into a
text-file by the site author. The text file is then saved as .html file, and
viewed through a browser like Internet Explorer. The browser reads the
text and translates it into visible form. You can use anything from notepad
to powerful graphical editor to create web pages.

"

  

What does these tags do?


These tags separate normal text from HTML code. In short, tags are
words between <> for example, <b> is a tag. These simple tags apply
formatting to the text, look at the code below:

<b>This is bold text</b> and this is not

When the above code is saved as .html file, and opened in your browser
then it will display:

This is bold text and this is not


Tags are not case sensitive, for example use of <B> and <b> will not
make any difference.
Is there anything HTML can’t do?
Yes, HTML can only make static pages (it can provide information to the
surfer but can not take information from the visitor). For example, if you
want the visitor to write comments about your web page, then you need to
have a server sided language to process this request.

1.2 Learning HTML


This part of the chapter will provide enough information about HTML
language to you to be able to write PHP programs.

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>

'

  

BODY part begins with <BODY> and ends with </BODY>


Making a basic Web page:
<HTML>
<HEAD> </HEAD>
<BODY> </BODY>
</HTML>

Adding title of web page:

<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.

1.3 Formatting the text:


Now we will do some formatting to the webpage:
To make the text look bold, add the text in between <b></b> tags.
For Example:
<HTML>
<HEAD>
<TITLE>This is my First Web page</TITLE>
</HEAD>
<BODY> <b>My first Web page</b>
</BODY>
</HTML>

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:

<font size=”4” color=”#FFCC00”><b><i>Some Text</i></b></font>

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>

To change the line:


Use <br> to change the line, for example you want to display the text
HELLO at the first line and Welcome to my webpage in the next line, then
add <br> after HELLO
For Example:
HELLO<br> Welcome to my webpage

1.4 Adding Images:


To add an image, use <img> tag
For example:
<img src=”http://www.scriptsez.net/logo.gif”>

,

  

This code will display image logo.gif on your webpage.


To change the height and width of image use:
<img src=”http://www.scriptsez.net/logo.gif” width=”20” height=”20”>

1.5 Adding Links:


To add links to your webpage, use:
<a href=”http://www.yahoo.com”>Click Here</a>

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>

To make the link open in new window, use:


<a href=”http://www.scriptsez.net” target=”_blank”>
<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!

2.1 Basic Q & A’s


What is PHP?

PHP, which stands for "Hypertext Preprocessor", is a server-side, HTML


embedded scripting language used to create dynamic Web pages. Much
of its syntax is borrowed from C, Java and Perl with some unique features
thrown in. The goal of the language is to allow Web developers to write
dynamically generated pages quickly.



  

How does PHP Work?

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.

What are the advantages of PHP over other Server Sided


Languages?

PHP offers excellent connectivity to many databases including MySQL,


Informix, Oracle, Sybase, Solid, PostgreSQL, and Generic ODBC. The
popular PHP-MySQL combination (both are open-source products) is
available on almost every UNIX host. Being web-oriented, PHP also
contains all the functions to do things on the Internet - connecting to
remote servers, checking email via POP3 or IMAP, url encoding, setting
cookies, redirecting, etc.

What do PHP Code look like?

PHP is a rather simple language. Much of its syntax is borrowed from C


except for dealing with the types of variables. You don't need to think of
the types of variables at all - you just work with their values, not their
types. And you don't have to declare variables before you use them.

Things to remember:



  

1. An HTML web page containing PHP code should be save as .php


not as .html
2. A php code starts with <?php and ends with ?>
3. Each instruction in PHP code must end with semicolon (;)

2.2 Make your first PHP Web page


Here is a sample:
<HTML>
<HEAD>
<TITLE>My first PHP Script</TITLE>
</HEAD>
<BODY>
<?php
echo “The text is written with PHP”;
?>
</BODY>
</HTML>

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.

2.3 Sending Mail with PHP


PHP can be used to send emails, for this purpose, PHP mail() function is
used. Many web servers have this feature enabled.
To send email you must have a subject, a message, recipient and sender.
Let us provide the value of each of the variables:



  

<?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.

2.4 Displaying Date and Time


PHP has many built in functions, mail function used above is one of them.
You can use PHP date function to display the time.
<?php
$time=date("D M d Y");
echo “$time”;
?>



  

Unlike javascript, the time displayed is the time on servers PC clock.

2.5 Checking File size


You can check the size of any file within the directory or in any
subdirectory.
Lets say we want to get the size of the file, which exists in the same
directory, lets say its name is index.html, then:
<?php
$filesize=filesize("index.html");
echo “$filesize”;
?>

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”;
?>

In the round function, there are two parameters:

"

  

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.

2.6 PHP if and else conditions


PHP has support for conditional sentences. For example, if you would like
to run different output upon different conditions then you can use if and
else condition.
In the following code we will display “Pass” if the value of a variable is
greater than or equal to 60, and “Fail” if the output is less than 60.

<?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”;
}
?>

2.7 Sending data using Forms


In the above examples we have declared the values within the PHP code,
what if user wants to input the value? We use forms to let user input the
data.
A form code is an HTML tag which begins with <form> and ends with
</form>
First we create a form, which asks the user a value, and then we output
the user whether it is positive, neutral or negative:
<HTML>
<HEAD>
<TITLE>PHP FORM</TITLE>
</HEAD>
<BODY>
<?php
if($action==”validate”){
if($variab >”60”){
echo “Positive”;
}elseif($variab ==”60”){
echo “Neutral”;
}else{
echo “Negative”;
}
}
?>
<form method=post action=”?action=validate”>
Please input the value: <input type=text name=variab> <input type=submit
value=”Check”>



  

</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.

2.8 Uploading Files


PHP supports file uploading to server. First we create a form just like we
did before. This form asks the user for the file which the user wants to
upload, an example of code would be:
<HTML>
<HEAD>
<TITLE>PHP FILE UPLOAD</TITLE>
</HEAD>
<BODY>
<?php
if($action==”upload”){
//Maximum allowable filesize
$max_filesize=”1000”;
//Check Filesize
$filesize=(($HTTP_POST_FILES['picture']['size'])/1024);
//Compare the filesize with Maximum allowable filesize

+

  

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>

In the above code you can see additional parameter


enctype=”multipart/form-data”
It is required when file is uploaded.
$HTTP_POST_FILES['picture']['size']) is pre-defined constant in PHP, it provides
filesize in bytes, so it is divided by 1024 to convert it into Kb.
copy($HTTP_POST_FILES['picture']['tmp_name'],$HTTP_POST_FILES['picture'][
'name']);

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).

,

  

2.9 File and directory functions


PHP supports checking the existence of files and directories, to check
whether a file exists in your server or not, use the following code:

<?php
$file=”my_webpage.php”;
if(file_exists($file)){
echo “File $file Exists”;
}else{
echo “File $file does not exist”;
}
?>

Similarly, you can check the directory using:

<?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>”;
}
?>

Output of above code will be:

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:



  

echo “This is $i line<BR>”;

Since the value of $i is 1, so the script prints:


This is 1 line.
Now, the script goes to the third parameter of for loop, $i++
It means, whatever the value of $i is, add one more to it. So now, the
value of $i is 2. It the goes to parameter number 2, since the value of $i is
still less than five, it again goes inside the loop and prints the line. It
continues until value of $i becomes greater than 5 and the loop ends.

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

3.1 Basic Q & A’s


What is a Database?

A database is simply a method by which you can store information. Lets


say you want to store information of your employees name and address,
you can use database for this purpose, and stored values can be viewed
using PHP.
What is MySQL?
MySQL is an open source Relational Database Management System that
uses Structured Query Language. Information is stored in "Tables" which



  

can be thought of as the equivalent of Excel spreadsheets. A single


MySQL database can contain many tables at once and store thousands
of individual records. It's fast, reliable and flexible.
What is a Flat File Database?
A Flat File database is a simple text file used to store information, and is
most often used when you do not have access to a MySQL database, as
they require no server addons other than PHP. They are best for smaller
amounts of data than a MySQL database is capable of, and have fewer
handling functions, but are very handy for things like counters and guest
books.

3.2 Flat File Databases


Lets start by creating a simple raw visit counter which will count the number of
times a page has been opened.
<?php
//Read the file which contains raw hits information
$counter_file = file(“stats.txt”);
$current_stats = $counter_file[0];
//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);
//Output the last number of visits
echo “Number of Visitors: $new_stats”;
?>

In the line
$counter_file = file(“stats.txt”);



  

We assign stored value of stats.txt to a variable $counter_file


Then we read the value stored in the file, since the value is on the first
line of the file stats.txt so it is counted as zero line in PHP!
We make a new variable $current_stats and store the value which is on
the first line of stats.txt in it.
New statistics is of course 1 value additional to the old value, e.g. if it was
4 then now it should be 5.
Then we remove everything from the database file using the code:
$file_open=fopen(“stats.txt”,”w”);
and write the latest visit statistics
fwrite($file_open,$new_stats);
then we close the database file using:
fclose($file_open);
Then we output the latest visit information using:
echo “Number of Visitors: $new_stats”;
In the above example the line
$file_open=fopen(“stats.txt”,”w”);
opens a text file stats.txt and removes everything from it, if the file does
not exist then it first creates a file stats.txt
NOTE: TO RUN THE ABOVE CODE YOU MUST CREATE A TEXT FILE stats.txt
IN THE SAME DIRECTORY IN WHICH YOU PUT THE FILE WITH THE ABOVE
COUNTER CODE AND SET PERMISSION OF stats.txt TO CHMOD 777
CHMOD refers to setting access privileges to a file. It is required if your web
hosting is on Linux Server. CHMOD 777 means that a file is readable, write able
and executable.
To set the permission-using FTP just right click the file and select CHMOD.
Then select all the check boxes.

"

  

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”;
?>

In the above code,


$ip=getenv(REMOTE_ADDR);
Gets the IP address of the user, then the file in which last users IP
address is stored is read, if it matches the current users IP, then new
statistics is equal to the old statistics, i.e. number of visits remains same
else we open the file stats.txt add 1 to it and display the new stats, also
the new users IP address is recorded and previous user IP is discarded.
NOTE: TO RUN THE ABOVE CODE YOU MUST CREATE A TEXT FILE stats.txt
and ip.txt IN THE SAME DIRECTORY IN WHICH YOU PUT THE FILE WITH THE
ABOVE COUNTER CODE AND SET PERMISSION OF stats.txt and ip.txt TO
CHMOD 777

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+”);

is very much similar to

+

  

$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

.

  

at a time. So, anything before || is treated as a different value and


anything after || is a different value.
We had written name of the user before || so to output the name we use:
$info[0] variable, which means output the value which occurs just before ||
and info[1] means that the value which occurs after the first || similarly if
we would have added some other information after email we may have
written it as:
fwrite($store,”$name||$email||$any_other\n”);
Then we can recall this $any_other value by:
$info[2]
…and so on!
The line:
echo “Name: $info[0] <BR> Email: $info[1] <HR>”;
Outputs the name and email of each user.
It is not necessary to use || you can use any unique combination of
characters.
For example if you use @||@ as an identifier:
fwrite($store,”$name@||@$email\n”);
then you have to use:
$info = explode(“@||@” , $data_file[$i]);
instead.

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.

3.3 MySQL Databases


You have seen some useful features of TEXT based database, now lets
shift to MySQL database, MySQL database require that you have an



  

existing MySQL enabled account on your server, you should have a


MySQL database name, a MySQL login username and a password.
If you see a MySQL Database option on your control panel it means that
your server has support for MySQL Database, you can create database
login username and password from your web hosting control panel.
Method of creating a database login username and password will not be
discussed here and can easily be found by searching this topic on
Internet.
Before we create any script, create a file conf.php and add the following
code in it:
<?php
$db_host="localhost";
$db_name = "db_nm";
$database_user = "usereal";
$database_pass = "userpass";
?>

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";
}
}
?>



  

Save the above code as “add.php”


Make a file search.php and add the following code in it:
<?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");
//Search Engine Form
echo "<form method=post action=?action=search>";
echo "<center>Search Database</center><BR>";
echo "NAME: <input type=text name=sname>";
echo "<input type=submit value=SEARCH>";
echo "</form>";
//If action is search
if($action=="search"){
//Search the table search_tbl
$list=mysql_query("SELECT * FROM search_tbl WHERE name LIKE
'%$sname%'");
//count the number of search results found
$results=mysql_num_rows($list);
//If search Results is greater than or equal to 1 then
if($results>=1){
echo "$results search result(s) found";
while ($row=mysql_fetch_array($list)){
echo "<li><b>$row[name]</b><BR>Email:$row[email] Telephone: $row[tel]";
}
}else{
echo "Sorry, no result found.";



  

}
}
?>

You can see that the upper part of the code is same that is:

//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");
The first line:
include "conf.php";
Loads the file containing the database login information.
The second line connects to the database using the information contained
in conf.php the third line selects the database to perform actions with the
database.
The code:
$sql2= 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)");
Creates a table named “search_tbl” if it does not exist. A table in MySQL
Database is a place where information can be stored in its rows and
columns. The table that has just been created using the above code
contains 4 columns, first column names “op”, the second column name is
“name” the third column name is “email” and the last column name is
“telephone”. We have also defined the data type in each of the column

"

  

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.

Here is the MySQL counter Code:


<?php
//Get the IP address of the user and store it in variable ip
$user_ip=getenv(REMOTE_ADDR);
//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
$sql= mysql_query("CREATE TABLE counter(stats INT NOT NULL,ip TEXT NOT
NULL)");
//Get current information
$current_stat=mysql_query(“SELECT * FROM counter”);
$array=mysql_fetch_array($current_stat);



  

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.

4.1 Basic Q and A’s


What are the requirements of server?
Your server must have GD library installed, most of the PHP supported
servers do have GD library installed.

4.2 Creating Thumbnails


Start by making the thumbnail script, here is the code for creating
thumbnails:
<?php
//Specify the name of the original file whose thumbnail is required it must be in
same directory

,

  

$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=''>";
?>

.

  

In the first few lines of the code:


$dc=substr_count($sourceName,".");
$tmp=explode(".",$sourceName);
$type=$tmp[$dc];
we get the image type.
If image type is jpg then
$sourceImage = imagecreatefromjpeg($sourceName);
Copy the jpg image source into the variable $sourceImage
Now we want the height and width of the original image, so,
$sourceWidth = imagesx($sourceImage);
similarly, for height of the original image we use:
$sourceHeight = imagesy($sourceImage);
We have defined the width of the image but the height of the thumbnail is
defined according to the height of the original image, to avoid distortion of
the image.
$thumbh=($sourceHeight/ $sourceWidth)*$thumbWidth;
Now we want to create thumbnail:
$targetImage =ImageCreateTrueColor($thumbWidth,$thumbh);
Resize the thumbnail
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,
$thumbh, $sourceWidth, $sourceHeight);
Here,
Imagecopyresized is a predefined PHP function, 0,0,0,0 is the left, right, top

and bottom margin.


Now we want the output of the thumbnail in PNG format, so we use:
imagepng($targetImage, $thumbPath."".$thumbName,100);
100 is the quality of image which means 100% quality of the source
image, this will make the file size of the thumbnail larger, lowering the
quality of the image will make the file size smaller.
We can output the thumbnail in gif format by using:



  

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.

4.3 Converting images to different formats


With PHP, you can convert images into GIF, JPG or PNG format.
For this purpose, the same functions as used above will be used:
For example, lets say we want to convert main.jpg into png format, for this
purpose, we use the following code:
<?php
//Name of New PNG Image
$new_name="main.png";
//Name of Source Image
$sourceimg="main.jpg";
$image=getimagesize($sourceimg);
$width=$image[0];
$height=$image[1];
$targetImage =imagecreatetruecolor($width,$height);
//Since image is JPG format, so
$sourceImage = imagecreatefromjpeg($sourceimg);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$width,$height,imagesx($
sourceImage),imagesy($sourceImage));
imagepng($targetImage, $new_name);
echo “Image has been converted.”;
?>

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]



  

4.4 Creating your own images


PHP allows you to create your own images, it is very useful in generating
random numbers and alphabets which are used in signing up to prevent
Spam.
Follow the code below:
<?php
//Width of Image
$width=100;
//Height Of image
$height=28;
//Create a blank image
$image = imagecreatetruecolor($width,$height);
//Background Color
$background = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 1, 1, $width - 2, $height - 2, $background);
//Write some text on image
imagestring ($image, 3, 5, 6, "This is Text", $textColor);
//Specify Header Type
header('Content-type: image/jpeg');
//Create JPG image
imagejpeg($image);
?>

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

5.1 Basic Q and A’s


What is a PHP Session, what is the use of it?
With PHP Session, you can store arrays or variables between the script
executions. A session remains valid in a same browser window; if the
browser window is closed and script is reopened then previous session
no longer exists. Session is used to identify the user.

5.2 PHP Sessions


A PHP session requires initialization before it can store any information; it
can be initialized by using the following code:
session_start();

"

  

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

'

  

echo “You are successfully logged in <BR><a href=”?act=logout”>Logout</a>”;


}
}
?>

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.