Learn Php Ez Way 2ed
-
Upload
slaughtlander -
Category
Documents
-
view
223 -
download
0
Transcript of Learn Php Ez Way 2ed
-
8/14/2019 Learn Php Ez Way 2ed
1/48
ISBN 978-0-557-04
-
8/14/2019 Learn Php Ez Way 2ed
2/48
Published By: Lulu.comCopyright Year: 2007Copyright Scriptsez.net. All rights reserved.
The above information forms this copyright notice: 2007 by Scriptsez.net. All rightsreserved.
ISBN 978-0-557-04160-2
-
8/14/2019 Learn Php Ez Way 2ed
3/48
-
8/14/2019 Learn Php Ez Way 2ed
4/48
/HDUQ3+3WKH(=:D\
3DJHRI
$%2877+(%22.
*(77,1*67$57(':,7++70/
%$6,&4$1'$6
/($51,1*+70/ )250$77,1*7+(7(;7
$ '',1*,0$*(6
$ '',1*/,1.6
3+3%$6,&6
%$6,&4$6
0$.(
-
8/14/2019 Learn Php Ez Way 2ed
5/48
/HDUQ3+3WKH(=:D\
3DJHRI
$ERXW7KH%RRN
7KLV ERRN LV LQWHQGHG WR SURYLGH ZHE GHVLJQHUV ZKR QHYHU KDYH DQ\
NQRZOHGJH RI ZHE SURJUDPPLQJ EHIRUH QRU WKH\ KDYH DQ\ FRQFHSW RI
+70/ ODQJXDJHWKHNQRZOHGJHRI PRVW SRSXODU VHUYHU VLGHG ODQJXDJH
3+3
7KLVERRNVVWDUWVZLWKWKHEDVLFVRI+70/DQGWKHEDVLFFRQFHSWVRI3+3
WRGDWDEDVHGULYHQDSSOLFDWLRQVRI3+3DORQJZLWKH[DPSOHV0XFKVWUHVV
KDV EHHQ JLYHQ WR PDNH WKLV ERRN HDVH IRU EHJLQQHUV DQG WKRVH ZKR
QHYHU KDYH DQ\ H[SHULHQFH RI ZULWLQJ SURJUDPV $ ORW RI ERRNV DUH
DYDLODEOH FRYHULQJ GHWDLOHG 3+3 SURJUDPPLQJ EXW WKLV ERRN LQWHQGV WR
SURYLGHWKHNQRZOHGJHZKLFKLVQHHGHGWRJHW\RXVWDUWHG
-
8/14/2019 Learn Php Ez Way 2ed
6/48
/HDUQ3+3WKH(=:D\
3DJHRI
Chapter
GETTING STARTED
WITH HTML
1 Getting Started With HTML
1.1 Basic Q and As:
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.
-
8/14/2019 Learn Php Ez Way 2ed
7/48
/HDUQ3+3WKH(=:D\
3DJHRI
What does these tags do?
These tags separate normal text from HTML code. In short, tags are
words between for example, is a tag. These simple tags apply
formatting to the text, look at the code below:
This is bold text 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 and will not
make any difference.
Is there anything HTML cant 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 languageto process this request.
1.2 Learning HTMLThis 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 and end with
HEAD part begins with and ends with
-
8/14/2019 Learn Php Ez Way 2ed
8/48
/HDUQ3+3WKH(=:D\
3DJHRI
BODY part begins with and ends with
Making a basic Web page:
Adding title of web page:
This is my First Web page
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.
This is my First Web page
My first Web page
-
8/14/2019 Learn Php Ez Way 2ed
9/48
/HDUQ3+3WKH(=:D\
3DJHRI
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 tags.
For Example:
This is my First Web page
My first Web page
Similarly, to make the text look italic, use instead of
You can also display the text both bold and italic by using
similarly to underline the text use tag
For Example:
This is my First Web page
My first Web page
To make the text size larger or smaller, use the tag.
Some text
-
8/14/2019 Learn Php Ez Way 2ed
10/48
/HDUQ3+3WKH(=:D\
3DJHRI
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 and tags
in between font tag.
For Example:
Some Text
The above code will display the formatted text bold and italic.
To bring the text at center of the web page, use tag.
For Example:
Some text
To change the line:
Use
to change the line, for example you want to display the textHELLO at the first line and Welcome to my webpage in the next line, then
add
after HELLOFor Example:
HELLO
Welcome to my webpage1.4 Adding Images:
To add an image, use tag
For example:
-
8/14/2019 Learn Php Ez Way 2ed
11/48
/HDUQ3+3WKH(=:D\
3DJHRI
This code will display image logo.gif on your webpage.
To change the height and width of image use:
1.5 Adding Links:
To add links to your webpage, use:
Click Here
Similarly you can add links to images as well by adding image tag inside
link tag.
Example:
To make the link open in new window, use:
-
8/14/2019 Learn Php Ez Way 2ed
12/48
/HDUQ3+3WKH(=:D\
3DJHRI
Chapter
PHP Basics
2 PHP BASICSIn 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 & As
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.
-
8/14/2019 Learn Php Ez Way 2ed
13/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
-
8/14/2019 Learn Php Ez Way 2ed
14/48
/HDUQ3+3WKH(=:D\
3DJHRI
1. An HTML web page containing PHP code should be save as .php
not as .html
2. A php code starts with
3. Each instruction in PHP code must end with semicolon (;)
2.2 Make your first PHP Web page
Here is a sample:
My first PHP Script
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
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:
-
8/14/2019 Learn Php Ez Way 2ed
15/48
/HDUQ3+3WKH(=:D\
3DJHRI
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.
-
8/14/2019 Learn Php Ez Way 2ed
16/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
The above function filesize() displays the size of file in bytes, you can
convert it into Kilobytes by dividing the output by 1024.
To round off the value to two decimal places just use the round()
function.
In the round function, there are two parameters:
-
8/14/2019 Learn Php Ez Way 2ed
17/48
/HDUQ3+3WKH(=:D\
3DJHRI
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.
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,
-
8/14/2019 Learn Php Ez Way 2ed
18/48
/HDUQ3+3WKH(=:D\
3DJHRI
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 and ends with
First we create a form, which asks the user a value, and then we output
the user whether it is positive, neutral or negative:
PHP FORM
Please input the value:
-
8/14/2019 Learn Php Ez Way 2ed
19/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
PHP FILE UPLOAD
-
8/14/2019 Learn Php Ez Way 2ed
20/48
/HDUQ3+3WKH(=:D\
3DJHRI
If ($filesize
Select File:
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).
-
8/14/2019 Learn Php Ez Way 2ed
21/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
Similarly, you can check the directory using:
-
8/14/2019 Learn Php Ez Way 2ed
22/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
Output of above code will be:
This is 1 line
This is 2 line
This is 3 line
This is 4 lineThis 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
-
8/14/2019 Learn Php Ez Way 2ed
23/48
/HDUQ3+3WKH(=:D\
3DJHRI
echo This is $i line
;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:
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.
-
8/14/2019 Learn Php Ez Way 2ed
24/48
/HDUQ3+3WKH(=:D\
3DJHRI
Chapter
Using Database
3 USING DATABASE
3.1 Basic Q & As
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
-
8/14/2019 Learn Php Ez Way 2ed
25/48
/HDUQ3+3WKH(=:D\
3DJHRI
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.
In the line
$counter_file = file(stats.txt);
-
8/14/2019 Learn Php Ez Way 2ed
26/48
/HDUQ3+3WKH(=:D\
3DJHRI
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.
-
8/14/2019 Learn Php Ez Way 2ed
27/48
/HDUQ3+3WKH(=:D\
3DJHRI
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).
-
8/14/2019 Learn Php Ez Way 2ed
28/48
-
8/14/2019 Learn Php Ez Way 2ed
29/48
/HDUQ3+3WKH(=:D\
3DJHRI
Name:
Email:
The 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 beallowed to run.
The line:
$store=fopen(file.txt,a+);
is very much similar to
-
8/14/2019 Learn Php Ez Way 2ed
30/48
/HDUQ3+3WKH(=:D\
3DJHRI
$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.
-
8/14/2019 Learn Php Ez Way 2ed
31/48
/HDUQ3+3WKH(=:D\
3DJHRI
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
-
8/14/2019 Learn Php Ez Way 2ed
32/48
/HDUQ3+3WKH(=:D\
3DJHRI
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]
Email: $info[1] ;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.
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
Now you have learnt how to make counters and user forms,dont just limit it to these two applications, you can createuncountable number of applications with these simple functionsthat have been described.
-
8/14/2019 Learn Php Ez Way 2ed
33/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
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:
-
8/14/2019 Learn Php Ez Way 2ed
34/48
/HDUQ3+3WKH(=:D\
3DJHRI
$db=mysql_connect($db_host,$database_user,$database_pass) or
die("MySQL Error: Unable to connect to database please check that you
have provided the correct Database Login usernameDatabase Login
Password");
//Select the databasemysql_select_db($db_name,$db)or die("MySQL Error: Unable to select
database please check that you have provided the correct 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 "";
echo "ADD AN ENTRY
";echo "NAME:
";echo "EMAIL:
";echo "TELEPHONE:
";echo "";
echo "";
//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 "
Entry has been successfully added.";}
}else{
echo "Please fill all the fields";
}
}
?>
-
8/14/2019 Learn Php Ez Way 2ed
35/48
/HDUQ3+3WKH(=:D\
3DJHRI
Save the above code as add.php
Make a file search.php and add the following code in it:
-
8/14/2019 Learn Php Ez Way 2ed
36/48
/HDUQ3+3WKH(=:D\
3DJHRI
}
}
?>
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("MySQL Error: Unable to connect to database please check that you
have provided the correct Database Login usernameDatabase Login
Password");
//Select the database
mysql_select_db($db_name,$db)or die("MySQL Error: Unable to select
database please check that you have provided the correct 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 containedin 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
-
8/14/2019 Learn Php Ez Way 2ed
37/48
/HDUQ3+3WKH(=:D\
3DJHRI
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)
-
8/14/2019 Learn Php Ez Way 2ed
38/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
-
8/14/2019 Learn Php Ez Way 2ed
39/48
/HDUQ3+3WKH(=:D\
3DJHRI
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;
?>
-
8/14/2019 Learn Php Ez Way 2ed
40/48
/HDUQ3+3WKH(=:D\
3DJHRI
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 As
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:
-
8/14/2019 Learn Php Ez Way 2ed
41/48
-
8/14/2019 Learn Php Ez Way 2ed
42/48
-
8/14/2019 Learn Php Ez Way 2ed
43/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
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]
-
8/14/2019 Learn Php Ez Way 2ed
44/48
/HDUQ3+3WKH(=:D\
3DJHRI
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:
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);
-
8/14/2019 Learn Php Ez Way 2ed
45/48
/HDUQ3+3WKH(=:D\
3DJHRI
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.
-
8/14/2019 Learn Php Ez Way 2ed
46/48
/HDUQ3+3WKH(=:D\
3DJHRI
Chapter
PHP Sessions
5 PHP Sessions5.1 Basic Q and As
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();
-
8/14/2019 Learn Php Ez Way 2ed
47/48
-
8/14/2019 Learn Php Ez Way 2ed
48/48
/HDUQ3+3WKH(=:D\
echo You are successfully logged in
Logout;}
}
?>
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.