Wednesday, June 6, 2012

Learn abour your server: php variables


Learn about your server: PHP variables

The server which is hosting your site (we will suppose in this tutorial you have an account with an ISP, so you are not controlling 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.
 

serverex.php
<form method=post action=serverex.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>

<?php
print phpinfo();
?>

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 additional information about the computer and how it has been set up to support .

Additionally, 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 slightly different data in that table. We do believe printing this response page is very useful, so we recomment 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/serverex.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 "serverex.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.
 

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

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











Example


Check Get and Post
             here



Languaje specific response

Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example comming soon
Example 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: random numbers and random selection of text


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 I
A randon selection within a range

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

1
2
3
4
5
6
7
8
9
10
<?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 II
A 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).
 

1
2
3
4
5
6
7
8
9
<?php

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

shuffle ($the_numbers);


?>

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?

$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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?

$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>";

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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;

?>

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.




PHP: Session


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 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 session
Password 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");
?>
1
2
3
4
5
6

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 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>  
        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 } ?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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: Open, Read and Create files


PHP: Open, Read and Create files

Open and Read content from a text file
Create and Write to a text file
Read 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.
 

1
2
3
4
5
6
7
8
<?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:

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

1
2
3
4
5
6
7
<?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:
 

1
2
3
4
5
6
7
8
9
10
11
<?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.

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:
1
2
3
4
5
6
7
8
9
10
11
<?
$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"). 

1
2
3
4
5
6
7
8
9
10
11
<?
$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).
 

1
2
3
4
5
6
7
8
9
<?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.
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. 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).
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?
// 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 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=myquery
http://www.myreferrer.com/main.html
http://search.yahoo.com/search?p=myquery2
http://www.google.com/search?q=a+diferent+query
http://www.myreferrer2.com/dir/file33.html



PHP tutorial: Using arrays


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.
Let´s check an example:
 

array.php

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



An array may be created from a two dimensional 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[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(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(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 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 my
Word number 1 is dog
Word number 2 is is
Word number 3 is very
Word number 4 is nice
Word number 5 is and
Word number 6 is my
Word number 7 is cat
Word number 8 is is
Word 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;
  
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>
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 sensitive)
3
Find 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 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
}

?>

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

}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 : GET and POST methods and how to get info from them


PHP : 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. Let´s check both methods

Post method
Get method
An 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


Does not work

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

When 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

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


Does not work

When submitting the form we will visit the URL bellow:

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

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

<?php if ($QUERY_STRING=="showall") { ?>
Anna
 From London. Student
Paolo
 From Roma. Student
Andoni
 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.

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