PHP Tutorial for Beginners
-
Author
sergeiivan -
Category
Documents
-
view
21 -
download
1
Embed Size (px)
Transcript of 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.
-
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 . 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
This is my page
-
This is the content of my page.
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 closing tag.
mypage.php
This is my page
This is the content of my page.
When visiting the page, the server will process the page to execute all PHP commands in the page, which will be located within 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.
-
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
This is my page
This is the content of my page.
Additionaly we may add several opening and closing tags within our page with executable commands.
mypage.php
This is my page
This is the content of my page.
-
print "";print "If not, please visit a different page.";print "";print "Goodbay";?>
As sown in the example above we may add PHP scripts within HTML tags.
Concatenation of stringsCheck the codes bellow:
Code 1
Code 2
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 charactersCheck the codes bellow:
The code The outputUse "\n" to add a line break
Use "\n" to add a line break AABBCCDDEE
Use "\"" to add brakets Use "\"" to add brakets
-
He said "Hello" to John
Using variables: first stepWith 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
This is spage
This page was written in .
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.
-
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
This page was written in 2002
This page was written in 2002
This page was written in 2002
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
-
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 pm "am" or "pm" PM "AM" or "PM" 15 Day of the month: 01 to 31
Tue Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat October Month: January, February, March... 03 Hour: 01 to 12 15 Hour: 00 to 23 3 Hour: 1 to 12 15 Hour: 0 to 23 26 Minutes: 00 to 59 15 Day of the month: 1 to 31 Tuesday Day of the week: Sunday, Monday, Tuesday... 0 Is it a leap year? 1 (yes) or 0 (no) 10 Month: 01 to 12 10 Month: 1 to 12 Oct Month: Jan, Feb, Mar, Apr, May... 03 Seconds: 00 to 59
th Ordinal: 1st, 2st, 3st, 4st... Need to be used with a numeric time/date value. See latter. 31 Number of days in the month: 28 to 31 1034691963 Seconds since 1970/01/01 00:00:00 2 Day of the week: 0 (Sunday) to 6 (Saturday) 2002 Year (four digits) 02 Year (two digits) 287 Day of the year: 0 to 365
-21600 Difference 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
-
want to display different values simultaneously, we have at least three option:
The code Output::
2002:10:15
2002:10:15 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 2002:10:15 15:26
Tuesday 15th of October 2002 15:26:03 PM
The time is .
That means it's 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):
-
The code Output Character with meaning
WETo15pm02 2603 Tuesday
The following characters have a meaning: T, d, a, y, i, s, 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
1st of January2002/01/02 2nd of January2002/01/03 3rd of January2002/01/04 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 timeIn 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).
-
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:
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:
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
-
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. Lets 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
Your name
Your age
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 John 30
Hi John, I know you are 30 years old
GET method
-
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.
Your name
Your age
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 thename=John&theage=30 John 30
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.
-
Getandpostexample.php
Information about my friends
Anna From London. StudentPaolo From Roma. StudentAndoni From Donosti. Student
Hide data
Anna From London. Student
Anna
Paolo From Roma. Student
Paolo
Andoni From Euskadi. Student
Andoni
Show all data
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.
-
Getandpostexample2.php
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
-
// 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 "\n\n";print "\nInformation about my friends\n"; if ($QUERY_STRING=="showall") { print $Anna.$Paolo.$Andoni; print "\nHide data";}else{
if ($_GET["name"]=="Anna") { print $Anna; }else{ print "\nAnna"; }
if ($_GET["name"]=="Paolo") { print $Paolo; }else{ print "\nPaolo"; }
if ($_GET["name"]=="Andoni") { print $Andoni; }else{ print "\nAndoni"; }
print "\nShow all data";
}?>
PHP tutorial: Using arrays
Introduction
-
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. Lets check an example:
array.asp My Array
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.
-
21
An array may be created from a two dimentional table. Lets check an example:
array2.php My Array
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
Thearray[0]: Thearray[1]: Thearray[2]: 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
-
Thearray[4]: Thearray[5]: Thearray[6]: Thearray[7]: Thearray[8]: Thearray[9]:
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
The element number 5 is :
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
-
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
How many words do I have in $TheArray?
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
Method 1:Number of strings containing "o" (case sensitive)
-
foreach ($MyArray as $key =>$val){ if (substr_count ($val,"o")>0){$counter++;} } print $counter; ?> Number of strings containing "o" (case insensitive)
Method 2:Number of strings containing "o" (case sensitive)
Find strings containing "o" (case insensitive)
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
-
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 123John teacher London 234Sue 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
-
?>
This script may be used for several porpouses: we may generate $Mydata by filtering values from an array as shown bellow:
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
-
}else{ // if no info has been posted, print the form print ""; print ""; print ""; print "";}
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
-
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
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:
-
$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
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
Your first name is Your last name is Your are years old
Line 2: A variable named $filename is defined. It contains the name of the file we will read.
-
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
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").
-
1234567891011
Example 6: This code is shorter than example 4, but the same results will be obtained (only for PHP version 5 or above).
123456789
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.
-
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
-
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
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
-
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.txthttp://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: SessionThe 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
-
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
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).
-
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 sessionsLet'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
Our private pages In order to access this pages fill the form below: Username: Password:
Our private pages
1234567891011121314151617181920212223242526272829303132
-
Hi, you are allow to see these pages: Page 1 Page 2
Error in username or password
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
-
session_start();if ($permission=="yes") { ?>
Page 1 Hi, welcome to Page 1 This page is empty at the moment, but it will be very interesting in the next future
You are not allowed to access this page
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
-
We will obtain a random number between a minimum and a maximum value.
12345678910
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
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.
-
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
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
-
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
-
?>
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 Name: Age:
-
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:
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), I know you are years old.
-
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 variablesWe 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
The value of variable "a" (get method): Value of variable "b" (get method): Value of variable "c" (get method): Value of variable "age" (post method):
Example
Check Get and Post here
Languaje specific response
Example comming soonExample comming
-
Language(s) selected in the browser:
Host: Referer: Browser of the visitor: Query string: Remote address: Remote host: Name of script: Name of server: Local address: Path:
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: 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
-
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
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.
-
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
-
12345678910111213141516
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.
-
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 changed12345678910111213141516
-
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
-
12345678910111213141516
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.
-
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 added1234567891011121314151617181920212223
-
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.
-
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 1123456789101112131415
-
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
-
-
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.
-
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 code12345678910111213141516171819202122
-
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 " Resized image ";
?>
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.
-
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 result123456789101112
-
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 " New image ";
?>
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
-
1415161718
5, 195, 60, $blue);imagestring($im, 5, 80, 5, "Modified!", $red);
imagepng($im,"modified_image.png");imagedestroy($im);
print " Modified image ";
?>
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
-
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").
PHP tutorial for beginnersIntroduction 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 SyntaxWhat is PHP?What Can You Do with PHP?What Do PHP pages Look Like?What Do PHP pages Look Like?Do You Have to Be a Programmer to Understand Server-Side Scripting?Displaying Date and TimeExample: Link of the DayUsing "S" with date comand.
DefaultOcxName1: DefaultOcxName: DefaultOcxName4: DefaultOcxName3: