Download - PHP Tutorial for Beginners

Transcript
Page 1: PHP Tutorial for Beginners

PHP tutorial for beginners

Introduction to PHPMy first PHP pageDisplaying date and timeForms and responding to them (GET and POST)Using arraysOpen/Read filesHandling sessions (simple password protection)Random number and text (random password)Learn about your server: php variablesHow to create images with PHPPattern Syntax

Hypertext Pre-processor: What is PHP?

What is PHP?

Hypertext Pre-processor (PHPs) is a server-side scripting language, and server-sidescripts are special commands you must place in Web pages. Those commands are processed before the pages are sent from your Server to the Web browser of your visitor. A typical PHP files will content commads to be executed in the server in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags.

When you type a URL in the Address box or click a link on a Web page, you're asking a Web server on a computer somewhere to send a file to the Web browser (sometimes called a "client") on your computer. If that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did before the Web server sent it. After receiving the file, your Web browser displays its contents as a combination of text, images, and sounds. In the case of an PHP page, the process is similar, except there's an extra processing step that takes place just before the Web server sends the file. Before the Web server sends the PHP file to the Web browser, it runs all server-side scripts contained in the page. Some of these scripts display the current date, time, and other information. Others process information the user has just typed into a form, such as a page in the Web site's guestbook

To distinguish them from normal HTML pages, PHP files are usually given the ".php" extension.

What Can You Do with PHP?

There are many things you can do with PHP.

• You can display date, time, and other information in different ways.

Page 2: PHP Tutorial for Beginners

• You can make a survey form and ask people who visit your site to fill it out, send emails, save the information to a file, etc

What Do PHP pages Look Like?

The appearance of an PHP page depends on who or what is viewing it. To the Web browser that receives it, an Active Server Page looks just like a normal HTML page. If a visitor to your Web site views the source code of an PHP page, that's what they see: a normal HTML page. However, the file located in the server looks very different. In addition to text and HTML tags, you also see server-side scripts. This is what the PHP page looks like to the Web server before it is processed and sent in response to a request.

What Do PHP pages Look Like?

Server-side scripts look a lot like HTML tags. However, instead of starting and ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically start with <?php or <? and will typically end with ?>. The <?php or <? are called anopening tags, and the ?> is called a closing tag. In between these tags are the server-side scripts. You can insert server-side scripts anywhere in your Web page--even inside HTML tags.

Do You Have to Be a Programmer to Understand Server-Side Scripting?

There's a lot you can do with server-side scripts without learning how to program. For this reason, much of the online Help for PHP is written for people who are familiar with HTML but aren't computer programmers.

Creating my first PHP file

In this page we will add PHP scripting languaje codes to our regular HTML page, we will learn how to write texts and how to concatenete them and write some special characters, and we will start using variables.

In our fisrt step to learn PHP scripting languaje we will modify a regular HTML page and we will add to it PHP commads.

Bellow we will find a regular HTML page:

mypage.html

<html><head><title>This is my page</title>

Page 3: PHP Tutorial for Beginners

</head>

<body>This is the content of my page.

</body>

</html>

To create a PHP page using the page above as our model, the first important action is to rename our file. In our case we will name the file "mypage.php". When a file with ".php" extension is placed in the server and the corresponding url is visited, the server will process the file before sending it to the client, so that all PHP commands will be processed. We may just change the name of our file as propoused and save it to our server (without any additional changes), and when visiting the corresponding URL the result will be exactly the same (because there is nothing to be processed in the page) .

To this renamed page ("mypage.php") we will add a small PHP command within <?php opening tag and ?> closing tag.

mypage.php

<html><head><title>This is my page</title></head>

<body>This is the content of my page. <?phpprint "Do you like it?";?>

</body>

</html>

When visiting the page, the server will process the page to execute all PHP commands in the page, which will be located within <?php opening tag and ?> closing tags. In our case "print" command will write to the resulting page the text contained between brakets ("Do you like it?"). Often, instead of print command, echo command is used to output string. At the end of the line we will add ";" (otherway we will get an error). We may use "echo" command instead of "print", and the result will be identical.

We may also include all the php commands in one line by placing the code bellow in our page.

Page 4: PHP Tutorial for Beginners

<?php print "Do you like it?"; ?>

Between opening and closing tags we may include several lines with executable commands as shown bellow (we must write ";" at the end of each line):

mypage.php

<html><head><title>This is my page</title></head>

<body>This is the content of my page. <?phpprint "Do you like it?";print "<br>";print "<b>If not, please visit a different page.</b>";print "<br>";print "<h1>Goodbay</h1>";?>

</body>

</html>

Additionaly we may add several opening and closing tags within our page with executable commands.

mypage.php

<html><head><title>This is my page</title></head>

<body <?php print "bgcolor=#FFFFFF"; ?>><?phpprint "Hello!<br>";?>This is the content of my page. <?phpprint "Do you like it?";

Page 5: PHP Tutorial for Beginners

print "<br>";print "<b>If not, please visit a different page.</b>";print "<br>";print "<h1>Goodbay</h1>";?>

</body>

</html>

As sown in the example above we may add PHP scripts within HTML tags.

Concatenation of strings

Check the codes bellow:

Code 1

<?phpprint "Hello!<br>";print "I am Joe";?>

Code 2

<?phpprint "Hello!<br>"."I am Joe";?>

The pages containing any of the codes above will be exactly the same. We have just put both lines in one, and to do that we have use a point between the two texts we want to show in our pages. The point used in Code 2 will concatenated both strings.

Writing some special characters

Check the codes bellow:

The code The output

Use "\n" to add a line break <pre><?php print "AA\nBB\nCC\nDD\nEE";?></pre>

Use "\n" to add a line break AABBCCDDEE

Use "\"" to add brakets<br> Use "\"" to add brakets

Page 6: PHP Tutorial for Beginners

<?php print "He said \"Hello\" to John";?>

He said "Hello" to John

Using variables: first step

With PHP we may also use variables. The variables used in PHP will always start with "$", as for example $i, $a, $mydata, $my_name etc. There are some words which we are not allow to use as a name for a variable, but as we probably do not know which ones are they, our best decission will be to use very descriptive variable names:

$my_favorite_song$my_counter$usernameetc

In the example bellow we have write a PHP page using some variables:

mypage.php

<?php$my_name="Joe";$my_hello_text="Hello everybody!";$year_create=2002;?>

<html><head><title>This is <?php print $my_name; ?>´spage</title></head>

<body>

<?php print $my_hello_text; ?>

This page was written in <?php print $year_create; ?>.</body>

</html>

In this example, we have defined three variables (line 2, 3 and 4) and we have included the information in the variable latter within the HTML code.

Page 7: PHP Tutorial for Beginners

Check those variables carefully: $my_name, $my_hello_text and $year_create has not been defined in advance (we have add a value to the variables the first time they have used them in the file, without letting know the program we will used it in advance), and the values do not contain the same kind of content:

$my_name, $my_hello_text are strings$year_create is a number

We may also use variables in the following ways:

The code The output

<?php $year_create=2002;print "This page was written in ".$year_create;?>

This page was written in 2002

<?php $year_create=2002;print "This page was written in $year_create"; ?>

This page was written in 2002

<?php $the_text="This page was written in ";$year_create=2002;print $the_text.$year_create; ?>

This page was written in 2002

<?php $the_text="This page was written in ";$year_create=2002;print "$the_text$year_create"; ?>

This page was written in 2002

Displaying link of the day

Displaying Date and Time

The date and time we will show how to display in this tutorial is the one specified by the server which is hosting our pages. In case you want to display a different date or time (p. e., your clients are mostly from Belgium but your server is located in US and you want to display the local time in Belgium) you will find how to do it latter on this page.

In the table bellow we have include the PHP code necessary to display one by one all the time and date related information. By copying the code in the first column to your page

Page 8: PHP Tutorial for Beginners

you will get the data which is explained in the third column. The column in the middle is the value of those data the day we were preparing this page.

Code Output

<?php print date("a"); ?> pm "am" or "pm"

<?php print date("A"); ?> PM "AM" or "PM"

<?php print date("d"); ?> 15 Day of the month: 01 to 31

<?php print date("D"); ?> TueDay of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat

<?php print date("F"); ?> October Month: January, February, March...

<?php print date("h"); ?> 03 Hour: 01 to 12

<?php print date("H"); ?> 15 Hour: 00 to 23

<?php print date("g"); ?> 3 Hour: 1 to 12

<?php print date("G"); ?> 15 Hour: 0 to 23

<?php print date("i"); ?> 26 Minutes: 00 to 59

<?php print date("j"); ?> 15 Day of the month: 1 to 31

<?php print date("l"); ?> Tuesday Day of the week: Sunday, Monday, Tuesday...

<?php print date("L"); ?> 0 Is it a leap year? 1 (yes) or 0 (no)

<?php print date("m"); ?> 10 Month: 01 to 12

<?php print date("n"); ?> 10 Month: 1 to 12

<?php print date("M"); ?> Oct Month: Jan, Feb, Mar, Apr, May...

<?php print date("s"); ?> 03 Seconds: 00 to 59

<?php print date("S"); ?> thOrdinal: 1st, 2st, 3st, 4st... Need to be used with a numeric time/date value. See latter.

<?php print date("t"); ?> 31 Number of days in the month: 28 to 31

<?php print date("U"); ?> 1034691963 Seconds since 1970/01/01 00:00:00

<?php print date("w"); ?> 2 Day of the week: 0 (Sunday) to 6 (Saturday)

<?php print date("Y"); ?> 2002 Year (four digits)

<?php print date("y"); ?> 02 Year (two digits)

<?php print date("z"); ?> 287 Day of the year: 0 to 365

<?php print date("Z"); ?> -21600Difference in seconds from Greenwhich meridian

As shown in the table the commands we are using in all case are "print" (in order to show the values to the visitor) and "date" (which will allow us to get the data corresponding to the string code we are using between brakets).

So we already know how to obtain the data and how to show it in our page, but if we

Page 9: PHP Tutorial for Beginners

want to display different values simultaneously, we have at least three option:

The code Output

<?php print date("Y"); ?>:<?php print date("m"); ?>: <?php print date("d"); ?>

2002:10:15

<?php print date("Y").":".date("m").":".date("d"); ?> 2002:10:15

<?php print date("Y:m:d"); ?> 2002:10:15

The first option is very easy to understand (we have just copied the code from the table one by one). The second option concatenates the data basically in the same way, and the third one is probably the most useful system, but the one we must understand before using it.

Command "date" will get the data we want to display, and that data is specified by the string used within data (in our case: "Y:m:d"). Each character in this string may or may not have a meaning depending upon there is or there is not a value asociate with that letter (see the first table in this page). In our case some characters will be replaced by its corresponding value:

Y: m:d

Year (four digits)no meaningMonth: 01 to 12no meaningDay of the month: 01 to 31

Check this usefull examples:

The code Output

<?php print date("Y:m:d H:i") ?> 2002:10:15 15:26

<?php print date("l dS of F Y h:i:s A"); ?>

Tuesday 15th of October 2002 15:26:03 PM

The time is <?php print date("H:i") ?>.

That means it's <?php print date("i") ?>minutes past <?php print date("H") ?> o'clock.

The time is 15:26. That means it's 26 minutes past 15 o'clock.

Take care when using date command or you may get unwanted data as shown in the first row in the table bellow (use the code in second row instead):

Page 10: PHP Tutorial for Beginners

The code Output Character with meaning

<?php print date("Today is l"); ?>

WETo15pm02 2603 Tuesday

The following characters have a meaning: T, d, a, y, i, s, l

<?php print "Today is ".date("l"); ?>

Today is Tuesday Only data asociated to "l" (day of the week) is requested

Example: Link of the Day

What if you wanted to have a link that points to a different page every day of the week? Here's how you can do that. First, create one page for each day of the week and name them "Sunday.htm," "Monday.htm," and so on.

To make the link, copy the code bellow to your page

<a href= <?php print date("l"); ?>.htm>Link of the Day</a>

Place the code in your ".php" page where you want it to appear. When you click this link in your browser, it will take you to the "Link of the Day".

Using "S" with date comand.

Lets suppose we are using the code bellow in different consecutive days:

Day Code Output

2002/01/01 <? php print date("nS of F"); ?> 1st of January

2002/01/02 <? php print date("nS of F"); ?> 2nd of January

2002/01/03 <? php print date("nS of F"); ?> 3rd of January

2002/01/04 <? php print date("nS of F"); ?> 4th of January

The "S" character included within command date will allow us to show "st", "nd", "rd" or "th" values depending on the number preceding the character "S".

Displaying local time

In this tutorial we will consider our server is located in a different time zone from the one our clients are located at (a Belgium related site is in a server located is USA for example).

Page 11: PHP Tutorial for Beginners

First we must know the time in the server. We will create a text file with the code bellow, and we will copy it to our server:

Time in server: <?php print date("H:i") ?>

Then we will visit our page and we will get the time in the server. Let suppose the time is 16:00

Second, we will calculate the difference in hours between local time and the time in server. Let suppose the time in Belgium is 20:00, so the difference is 4 hours.

To get the local time we will use the code in the table bellow:

<?php$differencetolocaltime=4;$new_U=date("U")-$differencetolocaltime*3600;print date("H:i", $new_U); ?>

Lets explain this code:

• We have create a variable named $differencetolocaltime, and we have stablish the value for this variable (4)

• In third line of the script we have create a variable named $new_U, and the value for this variable will be 'date("U")' (Seconds since 1970/01/01 00:00:00) to which we have substracted the difference of hours between the two time zones (in our case 4 hours, which is the value for the variable $differencetolocaltime, has been multiplied by 3600, which is the number of seconds in one hour)

• In the last step we have write to the document the new hour and time by using "date" command to which we have let know the exact date (specified by $new_U) from which we want to get the time (if it is not specified, as for example when using 'date("H:i")', the time and date in the server will be displayed as shown before in this page).

GET and POST methods and how to get info from them

Page 12: PHP Tutorial for Beginners

There are two ways we may get info from users by using a form: GET and POST methods. Additionally, GET method may be used for other purposes as a regular link. Let´s check both methods

Post methodGet methodAn example: three versions

POST method

This method will be indicated in the form we are using to get information from user as shown in the example bellow

<form method="POST" action="GetandPost.php"> Your name<BR><input type=text name=thename size=15><BR>Your age<BR><input type=text name=theage size=15><BR><input type=submit value="Send info"></form>

Your name

Your age

Send info

Does not work

When submitting the form we will visit the URL bellow (will be different when using GET method):

http://www.phptutorial.info/learn/GetandPost.phpWhen getting information from the form in the response page we will use $_POST command

Code Output

<?php print $_POST["thename"]; ?> John

<?php print $_POST["theage"]; ?> 30

<?php $thename=$_POST["thename"]; $theage=$_POST["theage"];

print "Hi ".$thename.", I know you are ".$theage." years old";?>

Hi John, I know you are 30 years old

GET method

Page 13: PHP Tutorial for Beginners

This method may be used exactly as in the example above, but the URL we will visit after submission will be diferent.

In the example bellow we have removed the word "POST" and "GET" has been written instead.

<form method="GET" action="GetandPost.php"> Your name<BR><input type=text name=thename size=15><BR>Your age<BR><input type=text name=theage size=15><BR><input type=submit value="Send info"></form>

Your name

Your age

Send info

Does not work

When submitting the form we will visit the URL bellow:

http://www.phptutorial. info/learn/GetandPost.php?thename=John&theage=30When getting information from the form in the response page we will use $_GETcommand.

Code Output

<? print $QUERY_STRING; ?> thename=John&theage=30

<?php print $_GET["thename"]; ?> John

<?php print $_GET["theage"]; ?> 30

<?php $thename=$_GET["thename"]; $theage=$_GET["thename"];

print "Hi ".$thename.", I know you are ".$theage." years old";?>

Hi John, I know you are 30 years old

An example: three versions

Get method may be used for additonal porposes. Although Post method is not used in this example, a similar page may be create. In the example bellow it is shown data in different ways depending on $QUERY_STRING or $_GET values obtained from the the url visited.

Page 14: PHP Tutorial for Beginners

Getandpostexample.php

<html><body bgcolor=FFFFFF><pre><b>Information about my friends</b>

<?php if ($QUERY_STRING=="showall") { ?>Anna From London. StudentPaolo From Roma. StudentAndoni From Donosti. Student

<a href=Getandpostexample.php>Hide data</a><?php }else{ ?><?php if ($_GET["name"]=="Anna") { ?>Anna From London. Student <?php }else{ ?><a href=Getandpostexample.php?name=Anna>Anna</a><?php } ?><?php if ($_GET["name"]=="Paolo") { ?>Paolo From Roma. Student<?php }else{ ?><a href=Getandpostexample.php?name=Paolo>Paolo</a><?php } ?><?php if ($_GET["name"]=="Andoni") { ?>Andoni From Euskadi. Student<?php }else{ ?><a href=Getandpostexample.php?name=Andoni>Andoni</a><?php } ?><p><a href=Getandpostexample.php?showall>Show all data</a>

<?php } ?></pre>

</body></html>

The previous code and this one will produce the same result. Just compare them: instead of using open and close tags each time, print command is used. Line breaks ("\n") are included within the text to be printed.

Page 15: PHP Tutorial for Beginners

Getandpostexample2.php

<?php// this code is always shown print "<html>\n<body bgcolor=FFFFFF>\n";print "<pre>\n<b>Information about my friends</b>\n"; if ($QUERY_STRING=="showall") { print "\nAnna\n From London. Student"; print "\nPaolo\n From Roma. Student"; print "\nAndoni\n From Euskadi. Student"; print "\n<a href=Getandpostexample.php>Hide data</a>";}else{

if ($_GET["name"]=="Anna") { print "\nAnna\n From London. Student"; }else{ print "\n<a href=Getandpostexample.php?name=Anna>Anna</a>"; }

if ($_GET["name"]=="Paolo") { print "\nPaolo\n From Roma. Student"; }else{ print "\n<a href=Getandpostexample.php?name=Paolo>Paolo</a>"; }

if ($_GET["name"]=="Andoni") { print "\nAndoni\n From Euskadi. Student"; }else{ print "\n<a href=Getandpostexample.php?name=Andoni>Andoni</a>"; }

print "\n<a href=Getandpostexample.php?showall>Show all data</a>";

}

?> </pre></body></html>

This third version uses three variables named $Anna, $Paolo and $Andoni, which are defined in first tree lines of the code. Using variables may be a very interesting option in cases like this one.

Getandpostexample3.php

<?php

Page 16: PHP Tutorial for Beginners

// Variables are defined for each person$Anna = "\nAnna\n From London. Student";$Paolo = "\nPaolo\n From Roma. Student";$Andoni = "\nAndoni\n From Euskadi. Student";

// this code is always shown print "<html>\n<body bgcolor=FFFFFF>\n";print "<pre>\n<b>Information about my friends</b>\n"; if ($QUERY_STRING=="showall") { print $Anna.$Paolo.$Andoni; print "\n<a href=Getandpostexample.php>Hide data</a>";}else{

if ($_GET["name"]=="Anna") { print $Anna; }else{ print "\n<a href=Getandpostexample.php?name=Anna>Anna</a>"; }

if ($_GET["name"]=="Paolo") { print $Paolo; }else{ print "\n<a href=Getandpostexample.php?name=Paolo>Paolo</a>"; }

if ($_GET["name"]=="Andoni") { print $Andoni; }else{ print "\n<a href=Getandpostexample.php?name=Andoni>Andoni</a>"; }

print "\n<a href=Getandpostexample.php?showall>Show all data</a>";

}?> </pre></body></html>

PHP tutorial: Using arrays

Introduction

Page 17: PHP Tutorial for Beginners

Working with Arrays Selecting values from a array Creating a table from data in a string Simple keyword search

Introduction

Instead of having our information (variables or numbers) in variables like $Mydata1, $Mydata2, $Mydata3 etc, by using arrays our information may be contained in an unique variable. Very often, we will create an array from data obtained from a table with only one column. Let´s check an example:

array.asp

<html> <title>My Array</title> <body>

<?php $MyData [0] = "0" $MyData [1] = "1" $MyData [2] = "2" $MyData [3] = "3" $MyData [4] = "4" $MyData [5] = "5" $MyData [6] = "6" $MyData [7] = "7" $MyData [8] = "8" $MyData [9] = "9"

print $MyData [5]; ?>

</body> </html>

1 2 3 4 5 6 7 8 9 10

11

12

13

14

15

16

17

18

19

20

Original table for the array in the script

MyData

0 1

1 4

2 7

3 3

4 4

5 5

6 6

7 7

8 8

9 9

In the response page we will print the value assigned to $MyData [5] in the array. The response page will return 5.

Page 18: PHP Tutorial for Beginners

21

An array may be created from a two dimentional table. Let´s check an example:

array2.php

<html> <title>My Array</title> <body>

<?php $MyData [0][0] = "1"; $MyData [0][1] = "2"; $MyData [0][2] = "3"; $MyData [1][0] = "4"; $MyData [1][1] = "5"; $MyData [1][2] = "6"; $MyData [2][0] = "7"; $MyData [2][1] = "8"; $MyData [2][1] = "9";

print $MyData [1][2]; ?>

</body> </html>

We may consider the table bellow as the source of information to create an array named $Mydata.

MyData 0 1 2

0 1 2 3

1 4 5 6

2 7 8 9

Lines 6-14. Values have assigned to the array.

Line 16. In the response page we will send the value assigned to $MyData [1][2] in the array. The first number will be the row and the second one the column, so that in our case the response page will show the value "6"

It is also possible to define an array with more dimensions as for example $MyData [5][5][5][5][5].

Working with Arrays

In the examples above we have defined all the values within the script one by one, but this assignation may be done in a different way, as it is described in the example bellow:

array3a.php Resulting page<pre> <? $Thearray= array ("Zero","one","two","three","four","five","six","seven","eight","nine") ?>

Thearray[0]: <? print $Thearray[0]; ?> Thearray[1]: <? print $Thearray[1]; ?> Thearray[2]: <? print $Thearray[2];?> Thearray[3]: <? print $Thearray[3]; ?>

Thearray(0): Zero Thearray(1): pne Thearray(2): two Thearray(3): three Thearray(4): four Thearray(5): five Thearray(6): six Thearray(7): seven Thearray(8): eight

Page 19: PHP Tutorial for Beginners

Thearray[4]: <? print $Thearray[4]; ?> Thearray[5]: <? print $Thearray[5]; ?> Thearray[6]: <? print $Thearray[6]; ?> Thearray[7]: <? print $Thearray[7]; ?> Thearray[8]: <? print $Thearray[8]; ?> Thearray[9]: <? print $Thearray[9]; ?>

</pre>

Thearray(9): nine

In this example the array has been defined as comma separated element (the first element in the array is element 0 !). The array command has been used to define the array.

We may want to generate an array from a data in a text. In the example bellow, each word in a text will be stored in an array (one word in each element of the array), and them the array will be printed out (with command print_r), and finally word number 5 will be shown:

array3b.php Resulting page<pre> <? $TheText="zero one two three four five six seven eight nine"; $Thearray=split (" ",$TheText) ;

print_r ($Thearray);?>

<hr>The element number 5 is : <? print $Thearray[5]; ?>

</pre>

Array( [0] => zero [1] => one [2] => two [3] => three [4] => four [5] => five [6] => six [7] => seven [8] => eight [9] => nine)The element number 5 is : five

In this example we have defined the variable $TheText, and whithin this variable we have include several words separated by spaces.

In the next line, we have splitted the variable $TheText into an array named $Thearray. Split command have been used to brake $TheText and " " (space) has been used as a delimiter to separate the substrings.

In the response page we have printed the array by using command print_r, and element number 5 has been printed out.

It may happend to have a string we want to split, but we do not know how many substrings we may get. In that case we may use command sizeof to discover how many

Page 20: PHP Tutorial for Beginners

elements are in our array, and them we may use that value to write them by using a foreach control structure (see example below).

array4.php Resulting page<pre> <? $TheText="my dog is very nice and my cat is barking"; $Thearray=split (" ",$TheText) ;?>

How many words do I have in $TheArray? <? print sizeof ($Thearray); ?>

<? Foreach ($Thearray as $key =>$val){ print "<br>Word number $key is $val"; } ?>

</pre>

How many words do I have in $TheArray?10

Word number 0 is myWord number 1 is dogWord number 2 is isWord number 3 is veryWord number 4 is niceWord number 5 is andWord number 6 is myWord number 7 is catWord number 8 is isWord number 9 is barking

Selecting values from a array

In the next example we will count number of element in the array containing the word "o". Two methods will be used

array5.php Resulting page <pre><?$MyArray [0] = "Zero";$MyArray [1] = "One";$MyArray [2] = "Two";$MyArray [3] = "Three";$MyArray [4] = "Four";$MyArray [5] = "Five";$MyArray [6] = "Six";$MyArray [7] = "Seven";$MyArray [8] = "Eight";$MyArray [9] = "Nine";

?><b>Method 1</b>:Number of strings containing "o" (case sensitive) <? $counter=0;

Method 1:Number of strings containing "o" (case sensitive) 3 Number of strings containing "o" (case insensitive) 4

Method 2:Number of strings containing "o" (case

Page 21: PHP Tutorial for Beginners

foreach ($MyArray as $key =>$val){ if (substr_count ($val,"o")>0){$counter++;} } print $counter; ?> Number of strings containing "o" (case insensitive) <? $counter=0; foreach ($MyArray as $key =>$val){ if (substr_count ($val,"o")>0 or substr_count($val,"O")>0){$counter++;} } print $counter; ?>

<b>Method 2</b>:Number of strings containing "o" (case sensitive) <? $MyNewArray=preg_grep ("/(o)/",$MyArray); print sizeof ($MyNewArray); ?>

Find strings containing "o" (case insensitive) <? $MyNewArray=preg_grep ("/(o|O)/",$MyArray); print sizeof ($MyNewArray); ?> </pre>

sensitive) 3Find strings containing "o" (case insensitive) 4

In the first method, we check all elements in the array (by using foreach control structure), and in each element we will count number of times the letter "o" is present ( by using command substr_count and a variable named $counter). At the end of the process $counter is printed out.

In the second method a new array is created from $MyArray by using a preg_grep command. This command will extract to the new array ($MyNewArray) the elements contained in array the original array by using a pattern. Learning about pattern syntax is very important for mediu and advances programers. Here, we just want to let the visitor know this concept. The second method will print the size of the newly created array, which is the number of elements containing the letter "o" within array $MyArray.

Creating a table from data in a string

Page 22: PHP Tutorial for Beginners

In order to undertand this script we will consider we have a table like the one bellow, and that this table was the original source of information we used to create our table:

Peter student Chicago 123

John teacher London 234

Sue Manager Sidney 789

From the table we got this three lines by separeting the values by commas:

Peter,student,Chicago,123 John,teacher,London,234 Sue,Manager,Sidney,789

And finaly we conected the three lines by separeting the values with "/":

Peter,student,Chicago,123/John,teacher,London,234/Sue,Manager,Sidney,789

The string obtained was saved to a variable named $Mydata in the script bellow. The resulting page will show a table similar to the original one. This script is not limited by number of rows or columns (the maximun amount of then is calculate each time we run the script), so we may change information stored in variable $Mydata, and a table with correct dimensions will be created.

Createatable.php

<?$Mydata="Peter,student,Chicago,123/John,teacher,London,234/Sue,Manager,Sidney,789";Createtable($Mydata);

function CreateTable($Mydata){ $MyRows=split ("/", $Mydata); $NumberRows=sizeof($MyRows); print "<table border=1>"; // start printing out the table

// data contained in each element at array $myRows // is printed to one line of the table foreach ($MyRows as $row){ $datainrow=split (",", $row); print "<tr>"; // start printing a row foreach ($datainrow as $val){ print "<td>$val</td>"; // print data in the row } print "</tr>"; // end printing the row } print "</table>"; // end printing out the table }

Page 23: PHP Tutorial for Beginners

?>

This script may be used for several porpouses: we may generate $Mydata by filtering values from an array as shown bellow:

<?$query="Chicago";

$Myclients [0]="Peter Smith,Chicago,Manager,123";$Myclients [1]="John Smith,New York,Accountant,124";$Myclients [2]="George Smith,Chicago,Administration,245";$Myclients [3]="Sam Smith,Dallas,Consultant,567";

$Mydata=="";foreach ($Myclients as $val){ if (substr_count ($val,$query)>0){$Mydata.=$val."/";}}

Createtable($Mydata);?>

This code in combination with Createtable() function in the previus example will display only the clients from Chicago. The $query variable may be obtained from a form.

Simple keyword search

In this example, in our first visit a form asking for a keyword will be display. After submitting the keyword Redirect() function will be activated.

In function Redirect we have create an array named $Websites. This array contains the url of websites and a its short description. In case the query string is included in the description of the site, the visitor will be redirected to the corresponding URL.

search.php

<?if ($_POST){ // check whether info has been posted $query=$_POST["query"]; Redirect($query);

Page 24: PHP Tutorial for Beginners

}else{ // if no info has been posted, print the form print "<form method=post action=search.php>"; print "<input type=text name=query>"; print "<input type=Submit value=Search>"; print "</form>";}

function Redirect($query){

// Array containing containing URLs and descriptions $Websites [0]["url"] = "http://www.phptutorial.info"; $Websites [0]["description"] = "Main page of PHPTutorial.info";

$Websites [1]["url"] = "http://www.phptutorial.info/scripts/Contact_form.html"; $Websites [1]["description"] = "Contact form script";

$Websites [2]["url"] = "http://www.phptutorial.info/scripts/Hit_counter.html"; $Websites [2]["description"] = "Simple hit counter script";

$Websites [3]["url"] = "http://www.phptutorial.info/iptocountry/"; $Websites [3]["description"] = "Free script and databse for country identification based on IP address";

// find query string within description of websites foreach ($Website as $key=> $val){ if (substr_count($Website [$key]["description"],$query)>0){ //next line will redirect the user to the corresponding url header ("Location: ".$Website [$key]["url"]); exit; } }

}?>

PHP: Open, Read and Create files

Open and Read content from a text fileCreate and Write to a text fileRead and Write compressed files (.gz)Example: Save IP address and referrer of our page

Page 25: PHP Tutorial for Beginners

NOTE: To work with files, correct permissions are required. Change permissions to 777 to try the code bellow. Other way, you will get errors.

Open and Read content from a text file

Example 1: This one will be the basic code we need to open a text file. The file is defined in line 2, it is read in lines 3-5, and content of the file is outputted in line 7.

12345678

<?php $filename="myfile.txt";$tempvar = fopen($filename,"r");$content=fread($tempvar, filesize ($filename));fclose($tempvar);

print "<pre>$content";?>

Line 2: a variable name $filename is defined. It contains the name of the file we will work with. In this case, the file is located in the same directory where the script is located. In case the file is located in a different location we may defined $filename as:

$filename="subdir/myfile.txt"; // the file is located in a directory named "subdir" within current directory

$filename="/var/www/html/mydir/myfile.txt";

// This is the absolute location within the hard disk

$filename=$_SERVER["DOCUMENT_ROOT"]."/mydir/myfile.txt";

// This is the location relative to document root (the folder containing the website files).

Line 3: a variable named $tempvar is created. This variable (this object) is used to open our file by using a command named fopen. Command fopen is used with two parameters: the name of our file (and the path to it when necessary, as shown above), and second parameter ("r") to indicate what we will do with the file. In this case, "r" means "read".

Line 4: in this line two new commands and a new variable ($content) are used. Command fread will be used to read our object ($tempvar), and command filesize is used to let know to fopen to what extent we want to read our file. In this case, the file will be read completely: filesize($filename) characters of file will be read.

Let's check some modifications of line 4:

Page 26: PHP Tutorial for Beginners

$content=fread($tempvar, 100); // only the first 100 characters will be read

$content=fread($tempvar, 1000000); // the first 1000000 characters will be read. In case the file is shorter, it will be read completely. // although a big number may be used in this procedure, it is not convenient. // a big number (1000000) means a lot of memory will be allocated for this task even though it s not necessary.

Line 5: $tempvar is closed.

Line 7: $content (the variable containing the text in the file read in lines 3-5) is outputted.

Example 2: This code is shorter than the one above, but the same results will be obtained (only for PHP version 4.3 or above).

1234567

<?php $filename="myfile.txt";

$content=file_get_contents ($filename);

print "<pre>$content";?>

Line 4: Command file_get_contents will read the entire file to variable $content.

Example 3: Let's suppose we have a file with different kind of information in each line (a name in the first line, the last name in the second one, and the age in the third one), and we want to use them separately. This one will be the script we may use:

1234567891011

<?php $filename="myfile.txt";

$lines= file ($filename);

print "<pre>$content";?>

Your first name is <? print $lines[0]; ?><BR> Your last name is <? print $lines[1]; ?><BR> Your are <? print $lines[2]; ?> years old<BR>

Line 2: A variable named $filename is defined. It contains the name of the file we will read.

Page 27: PHP Tutorial for Beginners

Line 4: Command file is used to transfer the content of the file to an array named $lines. Each element within array $lines will content one line of the line.

Line 9-11: Content of array $lines is printed out.

$lines [0] is the content in first line of the file $filename.$lines [1] is the content in second line of the file $filename.$lines [2] is the content in third line of the file $filename.etc.

Create and Write to a text file

Example 4: The basic code we need to create a file is very similar to that one we have used to open a file in example 1:

1234567891011

<?$thetext="Write this text in the file";

$filename="myfile.txt";

$tempvar = fopen($filename,"w");fwrite($tempvar, $thetext);fclose($tempvar);

print "The text has been saved";?>

Line 2: a variable name $thetext is defined, and it contains the text to be saved in the file.

Line 4: $filename is the file (including path if necessary) where $thetext will be saved.

Line 6-8: Similar to example 1, but in this case $filename is opened for writing ("w"), and in line 7, $thetext is written to the file.

In case the file already exists, it will be overwritten.In case the file does not exist, it will be created.

Line 10: the output.

Example 5: very similar to example 4, but in line 6 the file is open for appending text to it ("a").

Page 28: PHP Tutorial for Beginners

1234567891011

<?$thetext="Write this text in the file";

$filename="myfile.txt";

$tempvar = fopen($filename,"a");fwrite ($tempvar, $thetext);fclose($tempvar);

print "The text has been saved";?>

Example 6: This code is shorter than example 4, but the same results will be obtained (only for PHP version 5 or above).

123456789

<?php $thetext="Write this text in the file";

$filename="myfile.txt";

file_put_contents ($filename, $thetext);

print "<pre>$content";?>

Line 6: Command file_put_contents will write the entire $thetext to file $filename. In case the file does not exist, it will be created, and in case the file already exists, it will be overwrited.

Read and Write compressed files (.gz)

In case we are using files to store information for internal use of our website, it may be interesting to work with compressed files. The following factors may be considered when using compressed files:

• A compressed file will save hard disk space.• Reading or writing to a compressed file is faster than Reading or writing non-

compressed files. • For big files about 2/3 of the time is saved by using gz compressed files.

Page 29: PHP Tutorial for Beginners

The basic structure of the code used to open and write a compressed file is similar to that one used for text files above. In the table bellow is shown this basic structure.

open_gz_file.php

<?php $filename="myfile.gz;$tempvar = gzopen($filename,"r");$content=gzread($tempvar, filesize ($filename));gzclose($tempvar);

print "<pre>$content";?>

write_gz_file.php

<?$thetext="Write this text in the file";

$filename="myfile.gz";

$tempvar = gzopen($filename,"w");gzwrite($tempvar, $thetext);gzclose($tempvar);

print "The text has been saved";?>

append_gz_file.php

<?$thetext="Write this text in the file";

$filename="myfile.gz";

$tempvar = gzopen($filename,"a");gzwrite($tempvar, $thetext);gzclose($tempvar);

print "The text has been saved";?>

Save IP address and referrer of our page

Let's suppose we want to record the IP address and Referrer of all visitors to our page. The script bellow may be placed within the code of our page and it will create two files to store both data: "ips_file.txt" to store IP addresses and "ref_file.txt" to store referrers.

Page 30: PHP Tutorial for Beginners

Additionally, this script may be use to track number of times users from a specific IP address visits our page.

To use this code written permission must be available in the directory containing the file with this code (in order to create the files).

123456789101112131415161718192021222324252627

<?// save ip$ip=$_SERVER["REMOTE_ADDR"];if ($ip!=""){ $ipfile= "ips_file.txt"; $allips = file_get_contents ($ipfile); if (strpos($allips," $ip ")>0){ $allips = preg_replace ("/ $ip /"," $ip x",$allips); $tempvar= fopen($ipfile, "w"); fwrite ($tempvar, $allips); fclose($tempvar); }else{ $tempvar = fopen($ipfile, "a"); fwrite ($tempvar, " $ip x\n"); fclose($tempvar); }}

// save referrer$ref=$_SERVER["HTTP_REFERER"];if (strpos($ref,"mydomain.com")==0 and $ref!=""){ $refffile= "ref_file.txt"; $tempvar = fopen($refffile, "a"); fwrite ($tempvar, $ref."\n"); fclose($tempvar);}?>

Lines 2-13: saves the IP addresses to the file "ips_file.txt". Check the typical content of this file below.

Line 3: Get the IP address of visitors and stores the value in variable $ip.Line 4: If $ip has been obtained, lines 5-16 are processed.Line 5: Defines the name of the file containing the IP addresses.Line 6: Reads the content of the file to variable $allips. Line 7: Checks whether the IP of visitor has been already save in the file. If so, lines 8-11 are processed. If not, lines 13-15 are processed.Lines 8-11: In line 8, a replacement in the variable containing the content of the file "ips_file.txt" is performed (variable $allips). This replacement will

Page 31: PHP Tutorial for Beginners

place a “x” after the IP address already recorded in the variable. In lines 13-15 the file "ips_file.txt" is overwritten with the content in the variable.

The typical content of file "ips_file.txt" will be the one bellow, where the number of "x" after each IP indicates number of visits from that specific IP to our file.

ips_file.txt

150.150.150.150 x 150.150.150.151 xxxxxxx 150.150.150.152 xxx 150.150.150.153 x 150.150.150.154 xxxxxxxxx

Lines 19-26: saves the referrer to the file "ref_file.txt". Check the typical content of this file below.

Line 20: Get the referrer of visitor and stores the value in variable $ref.Line 21: The following are checked: Check whether the referrer site is our own site (whether "mydomain.com" is within the variable $ref); if so, next three lines are not processed.Check whether the value of $ref is different to "" (so whether a value exists); if no value is contained in the variable $ref, next three lines are not processed.Line 22-25: the value at $ref is appended to file ref_file.txt.

The typical content of file "ref_file.txt" will be the one bellow:

ref_file.txt

http://search.yahoo.com/search?p=myqueryhttp://www.myreferrer.com/main.htmlhttp://search.yahoo.com/search?p=myquery2http://www.google.com/search?q=a+diferent+queryhttp://www.myreferrer2.com/dir/file33.html

PHP: Session

The first time a user accesses to a our pages some connections and disconnections took place. During this process the server and the client will interchange information to identify each other. Due to this exchange of information our server will be able to identify a specific user and this information may be use to assign specific information to each specific client. This relationship between computers is call a session. During the time a session is active, it is possible to assign information to a specific client by using Session

Page 32: PHP Tutorial for Beginners

related commands. After a few minutes, the session will expire, so that information will be lost.

We will use two examples to explain sessions:

Showing number of times we have visit a page during a sessionPassword protection using sessions

Showing number of times we have visit a page during a session

counter.php

<?session_start();$counter++;print "You have visited this page $counter times during this session";session_register("counter"); ?>

123456

In the example above each time we visit the page "counter.php" during a session we will show the message:

You have visited this page XXX times during this session

Where XXX is the number of time we have visited the page (reload to increase the number by one).

In line 2 of the script we have start a session, we have definned a variable named $counter and its value has been increased by one (in line 3; $counter++ is equivalent to $counter= $counter+1), we have print a text (including the variable $counter) and finally we have register the session (we have included the name of our variable without "$" when using the latter command). Each time we visit this page the value for $counter will be increased by one.

This example will count the number of visits of each visitor; the value of the counter will be specific for each visitor.

In this example we have create a variable names $counter, but we may create additonal variables to save information from our visitors (p.e. $the_color, $the_age, etc) and we will need to register all of them (p.e. session_register("the_color"), session_register("The_age"), etc).

Page 33: PHP Tutorial for Beginners

We may include the code above in several pages (p.e in page1.php, pahe2.php, etc), so that we will get the number of pages we have visit on that site during the active session.

Password protection using sessions

Let's suppose we want to allow specific user to access the information on our site. We will create a page named "index.php" to allow visitors to identify themselves, and additional pages (page1.php, page2.php...) which restricted access.

In this example we will consider two users (with usernames Joe or Peter) and the corresponding passwords(hi or hello).

index.php

<?php if ($_POST["username"]=="") { ?>

<html> <title>Our private pages</title> <body> In order to access this pages fill the form below:<BR> <form method="post" action="index.php"> Username: <input type="text" name="username" size="20"><BR> Password: <input type="password" name="password" size="15"><BR> <input type="Submit" value="Submit"> </form> </body> </html>

<?php }else{ $username=$_POST["username"]; $password=$_POST["password"];

session_start(); if ($username=="Joe" AND $password=="hi"){ $permission="yes";} if ($username=="Peter" AND $password=="hello"){ $permission="yes";}

$username=$_POST["username"]; session_register("permission"); session_register("username");

if ($permission=="yes"){ ?>

<html> <title>Our private pages</title> <body>

1234567891011121314151617181920212223242526272829303132

Page 34: PHP Tutorial for Beginners

Hi, you are allow to see these pages: <BR> <A HREF="page1.php">Page 1</A><BR> <A HREF="page2.php">Page 2</A> </body> </html>

<?php }else{ ?>

Error in username or password

<?php } ?><?php } ?>

3334353637383940414243

Let's explain how this page works:

In line 1 it is checked whether information is submitted throw a form. If the answer is negative ($_POST["username"]==""), a form is displayed asking for username and password.

After filling the form and submitting it, as $_POST["username"] is not "", the script will jump to line 15. In line 16 and 17 user entered values for "username" and "password" are saved to variables $username and $pasword.

In lines 19 and 20 it is checked whether the username and password provided is one of the authorized ones. If so, variable $permission is set up as "yes". We may add several lines as the ones in lines 19 and 20 to add authorized usernames and passwords. then commands bellow are executed (lines 20-25)

As shown in the the example "Showing number of times we have visit a page during a session" upper in this page, between lines 18 and 24 we will set up session related variables after session_start() and we will register these variables (so that we will be able to keep that information in the server during the time the session is active).

Finally, if username and password are correct, a response page with links is send to the visitor (lines 29-37). In this example, if the username or password are incorrect the response page will include the text in line 40.

Now, let's suppose the user clicks in the link "Page 1" (page1.php). The code of page1.php will be the following one:

page1.php

<?php 1

Page 35: PHP Tutorial for Beginners

session_start();if ($permission=="yes") { ?>

<html> <title>Page 1</title> <body> Hi, welcome to Page 1 <BR> This page is empty at the moment, but it will be very interesting in the next future

</body> </html>

<?php }else{ ?>

You are not allowed to access this page

<?php } ?>

2345678910111213141516171819

In lines 1-4 it is check whether the value for "$permission" is "yes". If the answer is positive a page with information is send to the client. If the answer is negative, the text in line 17 is send.

NOTES:

• Using session to keep information from visitors is suitable for sites with a limited number of visitors. For sites with a bigger number of visitors it is preferable to keep the information in the clients computer (by using cookies).

PHP: random numbers and random selection of text

Random selection of number From a range From a serie of numbers

Randon selection of text: links

Generate a random password

Random numbers IA randon selection within a range

Page 36: PHP Tutorial for Beginners

We will obtain a random number between a minimum and a maximum value.

12345678910

<?php

$min = 10000;$max = 99999;

$number = mt_rand($min, $max);

print $number;

?>

Lines 3 and 4: the minimum and the maximum are set up.

Line 6: the random number is selected by using mt_rand () command . Alternatively, rand () command may be used, but mt_rand () command is superior. The random number is stored in variable $number.

Line 8: $number is outputted.

Random numbers IIA randon selection of a number from a serie of numbers.

We will select one number from an array which contains several numbers (independent numbers, not related).

123456789

<?php

$the_numbers = array(5,22,31,45,52,66,78);

shuffle ($the_numbers);

print $the_numbers[0];

?>

Line 2: the number (options) for our selection are included in an array.

Line 5: The order of the elements contained in the array are randomly mixed, so a new order is obtained.

Page 37: PHP Tutorial for Beginners

Line 7: The first number will be outputted (the randomly selected one).

Random selection of text

The links will be contained into an array, and one of them will be selected.

Option 1:

12345678910111213141516

<?

$text[0]="<a href=link1.html>link 1</a>";$text[1]="<a href=link2.html>link 2</a>";$text[2]="<a href=link3.html>link 3</a>";$text[3]="<a href=link4.html>link 4</a>";$text[4]="<a href=link5.html>link 5</a>";$text[5]="<a href=link6.html>link 6</a>";

$n=sizeof($text)-1;

$number = mt_rand (0, $n );

print $text[$number];

?>

Lines 3 to 8: an array is defined, where each value of the array is text.

Line 10: number of elements in the array are obtained.

Line 12: a random number between 0 and number of texts is selected

Line 14: By using the selected number, the corresponding text is outputted. .

Option 2:

123456789

<?

$text[0]="<a href=link1.html>link 1</a>";$text[1]="<a href=link2.html>link 2</a>";$text[2]="<a href=link3.html>link 3</a>";$text[3]="<a href=link4.html>link 4</a>";$text[4]="<a href=link5.html>link 5</a>";$text[5]="<a href=link6.html>link 6</a>";

Page 38: PHP Tutorial for Beginners

1011121314

shuffle ($text);

print $text[0];

?>

Lines 3 to 8: an array is defined, where each value of the array is text.

Line 10: The order of the elements contained in the array $text are randomly mixed, so a new order is obtained.

Line 12: The first text is outputted (being the first is a randon selection).

Generate a random password

The basic idea is very simple:

• a string variable contains all the posible characters we may use to obtain the random password/text.

• a number between 0 and the length of the string will be randomly selected. The number is used to select one character from the string.

• the process is repeated as many times as the length of the password we want to obtain.

12345678910111213141516

<?php

$passwordlength=10;

$str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYZ";$max = strlen($str)-1;

$password="";for ($i=0; $i<$passwordlength; $i++){ $number = mt_rand(0,$max); $password.= substr($str,$number,1);}

print $password;

Page 39: PHP Tutorial for Beginners

?>

Line 3: The length of the password is defined (a 10 characters length password in this example)

Line 5: $str is the variable containing all the characters allowed in the password.

Line 6: $max is basically the length of $str (1 is substracted to avoid problems latter).

Line 8: the variable $password is set up.

Lines 9-12: The password weill be selected in those lines. The cicle is repited up to the maximum length of the password. Line 10: a random number is selected between o and thye length of %str. Line 11: one character from variable $str is selected by using command substr() and added to variable $password.

Line 14: The password is outputted.

Learn abour your server: php variables

The server which is hosting your site (we will supose in this tutorial you have an account with an ISP, so you are not controling the server) may provide you a lot of useful information. In the next table we have a very simple code which will allow us to get a huge amount of information from the server.

askyourserver.php

<form method=post action=askyourserver.php?a=1&b=2&c=3> Name: <input type=text name=name><br>Age: <input type=text name=age><br><input type=submit value=submit></form>

<hr>

<?phpprint phpinfo();?>

Page 40: PHP Tutorial for Beginners

When visiting this page you will find a form in the top an a huge amount of information bellow, but in order to get even more information, fill the form and submit it. Then we will look to the response page.

In the response page you will get the PHP version instaled in your server and aditional information about the computer and how it has been set up to support .

Additionaly, and we will focus on this part of the information provided, in the last part of the response page we will find a section on PHP variables. Depending on the PHP version installed in the server, we may find sligtly different data in that table. We do believe printing this response page is very useful, so we recoment so.

We have extract one of the lines from the PHP variables obtained from that section of the response page to show you how to use it.

PHP_SELF /mydir/askyourserver.php

So we have a variable and its associated value (in this case the relative path to our page).

Let suppose we want to show in our php page that information. For example in the page "askyourserver.php" above, we want the action of our form to be entered automatically, so that it will work exactly in the same way with a different file name (file1.php, file2.php, etc.). So we want to get this:

<form method=post action="relative path to our script">

We know PHP_SELF variable will provide us that information, so we will make a small transformation of the variable name from PHP_SELF to $PHP_SELF, and we will used the latter one in our php page as in the example bellow:

pagename.php (you may change the name of the file)

<form method=get action=<?php print $PHP_SELF; ?>>Name: <input type=text name=name><br>Age: <input type=text name=age><br><input type=submit value=submit></form>

<hr>

Hi <?php print $_GET["name"]; ?>, I know you are <?php print $_GET["age"]; ?> years old.

Page 41: PHP Tutorial for Beginners

So in the response page the form will point back to the same page. Additionally, in this response page we have adding two php codes which will be used to add the information entered in the form within the response page. To learn more about responding to forms you may go to this page.

Depending on the PHP version installed on the server we may used $_GET["name"] or $HTTP_GET_VARS["name"] (in older versions of PHP). Anyway, the result will be the same (just use that one you will find in the list of PHP variables obtained from "askyourserver.php" above).

Selected PHP variables

We have select some PHP variables we consider more likely to be used by a beginner and we have put all them in the script bellow. In the right cell of the table you will find some useful ways to use them.

getphpvariables.php

<form method=post action=<?php print $PHP_SELF; ?>?a=1&b=2&c=3> Name: <input type=text name=name><br>Age: <input type=text name=age><br><input type=submit value=submit><br></form>Please fill the form and submit it.

<hr>

Lets get some info:<p>PHP_SELF: <?php print $PHP_SELF; ?>

<p>The value of variable "a" (get method): <?php print $_GET["a"]; ?><p>Value of variable "b" (get method): <?php print $_GET["b"]; ?><p>Value of variable "c" (get method): <?php print $_GET["c"]; ?><p>Value of variable "name" (post method): <?php print $_POST["name"]; ?><p>Value of variable "age" (post method): <?php print $_POST["age"]; ?>

Example

Check Get and Post here

Languaje specific response

Example comming soonExample comming

Page 42: PHP Tutorial for Beginners

<p>Language(s) selected in the browser: <?php print $HTTP_ACCEPT_LANGUAGE; ?>

<p>Host: <?php print $HTTP_HOST; ?><p>Referer: <?php print $HTTP_REFERER; ?><p>Browser of the visitor: <?php print $HTTP_USER_AGENT; ?><p>Path to our file: <?php print $PATH_INFO; ?><p>Query string: <?php print $QUERY_STRING; ?><p>Remote address: <?php print $REMOTE_ADDR; ?><p>Remote host: <?php print $REMOTE_HOST; ?><p>Name of script: <?php print $SCRIPT_NAME; ?><p>Name of server: <?php print $SERVER_NAME; ?><p>Local address: <?php print $LOCAL_ADDR; ?><p>Path: <?php print $PATH_TRANSLATED; ?>

soonExample comming soonExample comming soonExample comming soonExample comming soonExample comming soonExample comming soonExample comming soonExample comming soonExample comming soon

Some of the values you will get from this script will be the same.

The data may be obtained in different ways as for example those ones: <?php print $QUERY_STRING; ?> <?php print $_SERVER["QUERY_STRING"]; ?>

PHP: Create images

In this tutorial we will show how to create images with PHP.

Requeriments: GD library must be installed in the server (probably it is installed). Procedure: We will show small pieces of code, and the resulting figures. The code will be explained line by line. New lines will be added to the code so that the complexity of the image increases.

Create new images Code 1: create a 200x200 square Code 2: draw lines Code 3: draw rectangles Code 4: draw ellipses Code 5: draw arcs Code 6: add text to the imageManipulate images Code 7: rotate images

Page 43: PHP Tutorial for Beginners

Code 8: resize images Code 9: get a portion of the image Code 10: modify an existing imageImages on the fly Code 11: create and show images on the fly

Code 1: create a 200x200 square (and a bit more)

1234567891011

<?phpcreate_image();print "<img src=image.png?".date("U").">";

function create_image(){ $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow imagepng($im,"image.png"); imagedestroy($im);}?>

Lanes 1 and 11: opening and closing tags for phpLane 2: request to execute function create_image(), which is located in lines 5 to 10. The function will create the image.Lane 3: print out the html code necessary to display the newly created image.

• The image is named "image.png".• We have added to the end of the image a "?" and a value -date("U")- which will

allow us to avoid to show images in the cache of the browse. • date ("U") will add to the image name a number (seconds since 1970/01/01

00:00:00). As this number is different each time we create a new image, we will avoid the browser to show an image stored in the cache ones and again; the images "image.png?1034691963" and "image.png?1034691964" will be considered different by the browser, and they will be retrieved from the server.

Lanes 5 to 10: contains the function which will create the new images.

• Line 6: $im is the variable which will be used to store the image.

Page 44: PHP Tutorial for Beginners

• imagecreate() will start the creation process. imagecreatetruecolor() may be used instead• "@" is used before imagecreate() to avoid displaying errors (just in case).• Parameters within imagecreate(200,200) are the dimensions of the new image

o The first number is the width in pixels.o The second number is the height in pixels.

• In this case we have created a 200x200 pixels image• In case the image can not be created, and error is shown (die command).

• Line 7: We will define a color to be used as background color of the image, and a variable to contain it ($background_color).

• When using imagecreate() command in line 6, the first color defined will be considered as the background color of the image. In case imagecreatetruecolor() command is used instead, the background color will be black (but we may latter draw a colored square area with a different color and the dimensions of the image).• The imagecolorallocate() command is used to define colors and "reserve" them for future use. RGB color model is used

imagecolorallocate($im, 255, 255, 0):

amount of red: 255 (the maximum).amount of green: 255 (the maximum).amount of blue: 0 (the minimum).

• Lane 8: imagepng() will save the info at $im (the image) in the file "image.png". Other image types may be created by using commands imagegif(), imagewbmp(), imagejpeg(), or imagetypes(). In this tutorial we have selected png due to its open source nature.

• Lane 9: we have finish using the information at variable $im, so we will destroy it with imagedestroy() to free any memory associated to it.

Code 2: draw lineslines 9 to 11 added to code 1 above

Page 45: PHP Tutorial for Beginners

12345678910111213141516

<?phpcreate_image();print "<img src=image.png?".date("U").">";

function create_image(){ $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imageline ($im, 5, 5, 195, 5, $red); imageline ($im, 5, 5, 195, 195, $blue); imagepng($im,"image.png"); imagedestroy($im);}?>

Lanes 9 and 10: new colors are added to the image (as explained earlier for line 7).Lane 11: horizontal line is draw.Lane 12: diagonal line is draw.

To draw lines imageline() command is used. Check the picture bellow to understand the parameters used with this command.

Page 46: PHP Tutorial for Beginners

imageline ($im, X1, Y1, X2, Y2, $color);

where X1, Y1, X2 and Y2 are the positions within the image.

For example, the red line starts at X1=5 and Y1=5and ends at X2=195 and Y2=5

Code 3: draw rectanglessimilar to code 2, but lines 11 and 12 has been changed

12345678910111213141516

<?phpcreate_image();print "<img src=image.png?".date("U").">";

function create_image(){ $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imagerectangle ($im, 5, 10, 195, 50, $red); imagefilledrectangle ($im, 5, 100, 195, 140, $blue);

Page 47: PHP Tutorial for Beginners

imagepng($im,"image.png"); imagedestroy($im);}?>

Lane 11: a red rectangle is drawn (only the outer line)..Lane 12: a blue rectangle is drawn (a filled one).

To draw the rectangles, position of upper left corner and bottom right corner are considered. Check the picture bellow to understand the parameters used with those commands.

imagerectangle ($im, X1, Y1, X2, Y2, $color);imagefilledectangle ($im, X1, Y1, X2, Y2, $color);

For example, the red rectangle starts at X1=5 and Y1=10and ends at X2=195 and Y2=50

Code 4: draw ellipsessimilar to code 2, but lines 11 and 12 has been changed

Page 48: PHP Tutorial for Beginners

12345678910111213141516

<?phpcreate_image();print "<img src=image.png?".date("U").">";

function create_image(){ $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imageellipse($im, 50, 50, 40, 60, $red); imagefilledellipse($im, 150, 150, 60, 40, $blue); imagepng($im,"image.png"); imagedestroy($im);}?>

Lane 11: a red ellipse is drawn (only the outer line)..Lane 12: a blue ellipse is drawn (a filled one).

To draw the ellipses, position of the center of the ellipse, and its width and height are considered. Check the picture bellow to understand the parameters used with those commands.

Page 49: PHP Tutorial for Beginners

imageellipse($im, X, Y, width, height, $color);imagefilledellipse($im, X, Y, width, height,$color);

For example, the center of the red ellipse is located at X=50 Y=50and the dimensions are width = 40 height= 60

To draw a circle you may draw an ellipse with width=height.

Code 5: draw arcssimilar to code 2, but lines 12 to 20 has been added

1234567891011121314151617181920212223

<?phpcreate_image();print "<img src=image.png?".date("U").">";

function create_image(){ $im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red $blue = imagecolorallocate($im, 0, 0, 255); // blue imagearc($im, 20, 50, 40, 60, 0, 90, $red); imagearc($im, 70, 50, 40,

Page 50: PHP Tutorial for Beginners

2425

60, 0, 180, $red); imagearc($im, 120, 50, 40, 60, 0, 270, $red); imagearc($im, 170, 50, 40, 60, 0, 360, $red);

imagefilledarc($im, 20, 150, 40, 60, 0, 90, $blue, IMG_ARC_PIE); imagefilledarc($im, 70, 150, 40, 60, 0, 180, $blue, IMG_ARC_PIE); imagefilledarc($im, 120, 150, 40, 60, 0, 270, $blue, IMG_ARC_PIE); imagefilledarc($im, 170, 150, 40, 60, 0, 360, $blue, IMG_ARC_PIE); imagepng($im,"image.png"); imagedestroy($im);}?>

Lanes 12-15: a red arc is drawn (only the outer line)..Lanes 17-20: a blue arc is drawn (a filled one).

The basic codes used is imagearc ( $im, X, Y, width, height, arc start, arc end, $color) imagefilledarc ( $im, X, Y, width, height, arc start, arc end, $color, flag )

X and Y define thy position of the center of the arc within the imageWidth and height are the dimensions of the complete circle formed by the arc.arc start and arc end are the start and the end of the arc in degrees. If start is zero, as in the example, the figure will start in the right.Flags are specific options available for those commands. Visit the commands information to get additional information about all possible flags. Check the figure bellow for better understanding of the commands above.

Page 51: PHP Tutorial for Beginners

The commands imagearc () and imagefilledarc () may also be used to draw circles (width=height, arc start=0 and arc end=360).

Other figures you may draw: imagepolygon () -- Draw a polygon imagefilledpolygon () -- Draw a filled polygon

Code 6: add text to the imagelines 8 to 16 has been added to code 1

123456789101112131415

<?phpcreate_image();print "<img src=image.png?".date("U").">";

function create_image(){ $im = @imagecreate(200, 200)or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 255, 255, 0); // yellow $red = imagecolorallocate($im, 255, 0, 0); // red

imagestring($im, 1,file:///C:/apache2triad/htdocs/0image/tutorial1.html 5, 10, "Hello !", $red);

Page 52: PHP Tutorial for Beginners

161718192021

imagestring($im, 2, 5, 50, "Hello !", $red); imagestring($im, 3, 5, 90, "Hello !", $red); imagestring($im, 4, 5, 130, "Hello !", $red); imagestring($im, 5, 5, 170, "Hello !", $red);

imagestringup($im, 5, 140, 150, "Hello !", $red);

imagepng($im,"image.png"); imagedestroy($im);}?>

Lane 8: defines red colorLanes 10 to 14: adds text to image. In this simple example, built-in fonts will be used. imagestring ($im, size, X, Y, text, $red); The size will be 1 to 5. X and Y are the positions where the text will start.

Lane 16: similar to previous lines, but text is written in vertical.

Code 7: rotate imageThis is new code

1234567891011

<?php

$im = imagecreatefrompng("image.png");$yellow = imagecolorallocate($im, 255, 255, 0);$rotate = imagerotate($im, 90,$yellow);imagepng($rotate,"image_rotated.png");imagedestroy($im);

print "<img src=image.png> - <img src=image_rotated.png>";

?>

-

Page 53: PHP Tutorial for Beginners

Lane 3: the information about the image is stored in variable $im. In this case, the information has been obtained from an existing png image with the command imagecreatefrompng (). If the reference image has a different extension, other commands may be used:

imagecreatefromgif -- Create a new image from file or URLimagecreatefromjpeg -- Create a new image from file or URLimagecreatefrompng -- Create a new image from file or URLimagecreatefromwbmp -- Create a new image from file or URLimagecreatefromxbm -- Create a new image from file or URLimagecreatefromxpm -- Create a new image from file or URL

More options here.Lanes 4: a new color is used to be use in next line Lanes 5: the information about the image in $im is modified with imagerotate () and stored in a new variable: $rotate imagerotate ($im, degrees, $color); degrees are used to define the rotation angle. Values may be positive (90, 180...) or negative (-90,-180...). $color indicates the color to be used as background when necessary (when rotation angle is different to 90, 180 and 270). For example when rotation is 45 degrees, the size of the figure will be altered, as shown bellow. As a consequence a background color is required to fill the new surface. In this example, we have define the background color as red.

Page 54: PHP Tutorial for Beginners

Lane 6 and 7: the image is saved to a file and frees memory (as described in code 1).Lane 9: Both images are shown (original and new).

Code 8: resize imageThis is new code

12345678910111213141516171819202122

<?php

$original_image = imagecreatefrompng("image.png");

// obtain data from selected image$image_info = getimagesize("image.png");// data contained in array $image_info may be displayed in next line// print_r($image_info)

$width = $image_info[0]; // width of the image$height = $image_info[1]; // height of the image

// we will reduce image size to 70%, so new dimensions must be calculate$new_width = round ($width*0.7);$new_height = round ($height*0.7);

$new_image = imagecreate($new_width,

Resized image

Page 55: PHP Tutorial for Beginners

232425

$new_height);imagecopyresized($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

imagepng($new_image,"resized_image.png");imagedestroy($new_image);

print "<img src=image.png> <br>Resized image<BR> <img src=resized_image.png>";

?>

Lane 3: the information about the original image is stored in variable $original_image. Lines 6: size of original image is obtained. The info is contained in an array as explained in the code.Lanes 10 and 11: width and height of the image are extracted from the array and stored in variables $width and $height.Lanes 13 to 15: In this example, the image will be reduce to 70%, so new width and height are computed as shown. To avoid decimals round command is used. Lane 17: In this line starts the creation process of the new image. Command imagecreate() will define the dimension of the new image, and variable $new_image will store all information related to the image.Lane 18: This is the core command of this script. Lets try to explain the command by using a picture which contains all the elements in the command.

Page 56: PHP Tutorial for Beginners

Where: Xo1, Yo1, Xo2 and Yo2 are the dimensions of the original image Xn1, Yn1, Xn2 and Yn2 are the dimensions of the new image

Lane 20 and 21: the image is saved to a file and frees memory (as described in code 1).Lane 23: Both images are shown (original and new).

Code 9: get a portion of the imageQuite similar to code 8, but with a different result

123456789101112

<?php

// get the original image$original_image = imagecreatefrompng("image.png");

// create new image $new_image = imagecreate(200, 200);

// define red color (it will be the background of the new image) New image

Page 57: PHP Tutorial for Beginners

13141516171819

$red = imagecolorallocate($new_image, 255, 0, 0); imagecopyresized($new_image, $original_image, 75, 75, 0, 0, 100, 100, 100, 100);

imagepng($new_image,"new_image.png");imagedestroy($new_image);

print "<img src=image.png> <br>New image<BR> <img src=new_image.png>";

?>

Lane 4: the information about the original image is stored in variable $original_image. Lane 7: a new 200x200 pixels image is created.Lane 10: a color is defined for the new image.It will be also the background color (for better understanding, check code 7) Lanes 12: The core command of this script. A square area from original image is selected. In this example, the selected area is defined by position (0,0) and position (100,100). The selected area is copied to position (75,75) of the new image and dimension of the area are maintained (100x100). Lane 14 and 15: the new image is saved to a file and frees memory (as described in code 1).Lane 17: Both images are shown (original and new).

Code 10: modify an imageA rectangle and a text will be added to an already existing image

12345678910111213

<?php

// get the original image$im = imagecreatefrompng("image.png");

// new color$blue = imagecolorallocate($im, 0, 0, 255); // blue$red = imagecolorallocate($im, 255, 0, 0); // red

imagefilledrectangle ($im, 80, Modified image

Page 58: PHP Tutorial for Beginners

1415161718

5, 195, 60, $blue);imagestring($im, 5, 80, 5, "Modified!", $red);

imagepng($im,"modified_image.png");imagedestroy($im);

print "<img src=image.png> <br>Modified image<BR> <img src=modified_image.png>";

?>

Lane 4: a new image is created using an already existing image as a reference. Lanes 7 and 8: new colors are definedLane 10: a rectangle is added to the image (check code 3)Lane 11: a text is added to the image (check code 6)Lane 13 and 14: the new image is saved to a file and frees memory (as described in code 1).Lane 16: Both images are shown (original and new).

Code 11: create and show images in the flyThe image is not save to the disk

123456789101112131415

<?php

header("Content-type: image/png");

$im = @imagecreate(200, 200) or die("Cannot Initialize new GD image stream");

$background_color = imagecolorallocate($im, 255, 255, 0); // yellow$blue = imagecolorallocate($im, 0, 0, 255); // blue

imagestring($im, 3, 5, 5, "My Text String", $blue);

imagepng($im);imagedestroy($im);

?>

Page 59: PHP Tutorial for Beginners

Lane 3: In this example, the first information send by the server to the browser is shown in line 3. This line indicates that information being send is a png image.

Lanes 5 to 13: the image is create and send Lane 5: a 200x200 image is created Lanes 7 and 8: colors used in the image are defined Lane 9: a text is added to the image(as described in code 6). Lane 12: the image is output. As no file is indicate, the image is output ("on the fly").