What is PHP?

stickyraffleSoftware and s/w Development

Nov 4, 2013 (3 years and 7 months ago)

325 views

What is PHP?

Hypertext Pre
-
processor


(PHPs) is a


server
-
side

scripting language, and


server
-
side
scripts 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 informat
ion 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 We
b 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 differen
t. In addition to text and HTML tags, you also
see server
-
side scripts. This is what the PHP page looks like to the Web server before it is
processed and sent in response to a request.

What Do PHP pages Look Like?

Server
-
side scripts look a lot like HTML
tags. However, instead of starting and ending with
lesser
-
than ( < ) and greater
-
than ( > ) brackets, they typically start with <?php or <? and will
typically end with ?>. The <?php or <? are called an
opening tags
, and the ?> is called a
closing
tag
. In be
tween 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 withou
t 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 scri
pting languaje we will modify a regular HTML page and we
will add to it PHP commads.


Bellow we will find a regular HTML page:

mypage.html

<html>

<head>

<title>This is my page</title>

</head>


<body>

This is the content of my page.


</body>


</html>


To create a PHP page using the page above as our model, the first important action is to rename
our file. In our case we will name the file "
mypage.php
". When a file with ".php" extension is
placed in the server and the corresponding url is visited, the se
rver 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 UR
L the result will be exactly the same (because there is
nothing to be processed in the page) .




To this renamed page ("mypage.php") we will add a small PHP command within


<?php

opening tag

and
?>

closing tag
.

mypage.php

<html>

<head>

<title>This is my

page</title>

</head>


<body>

This is the content of my page.

<?php

print
"Do you like it?";

?>


</body>


</html>


When visiting the page, the server will process the page to execute all PHP commands in
the
page, which will be located within


<?php

opening tag

and
?>

closing tags.
In our case

"
print
"
command will


write to the resulting page the text contained between brakets ("Do you like it?").
Often,

instead of
print
command,
echo
command is used to output string. At the end of the line
we will add
";"

(otherway we will get an error). We may use "echo" command instead of
"print", and the result will be identical.


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


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


Between
opening

and
closing tags

we may include several lines with executable commands as
shown bellow (we must write
";"

at the end of each line):


mypage.php

<html>

<head>

<title>This is my page</title>

</head>


<body>

This is the content of my page.

<?php

print
"Do you like it?";

print
"<br>";

print
"<b>If not,

please visit a different
page.</b>";

print
"<br>";

print
"<h1>Goodbay</h1>";

?>


</body>


</html>



Additionaly we may add

several
opening

and
closing
tags

within our page with executable
commands.





mypage.php

<html>

<head>

<title>This is my page</title>

</head>


<body
<?php
print
"bgcolor=#FFFFFF"; ?>
>

<?php

print
"Hello!<br>";

?>

This is the content of my page.

<?php

print
"Do you like it?";

print
"<br>";

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

print
"<br>";

print
"<h1>Goodbay</h1>";

?>


</body>


</html>


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


Concatenation of strings


Check the codes bellow:

Code 1

<?php

print "Hello!<br>";

print "I am Joe";

?>

Code 2

<?php

print "Hello!<br>"."I am Joe";

?>


The pages
containing any of the codes above will be exactly the same. We have just put both
lines in one, and to do that we have use a

point

between the two texts we want to show in our
pages. The point used in Code 2 will concatenated both strings.


Writing some s
pecial characters


Check the codes bellow:

The code

The output

Use "
\
n
" to add a line break

<pre>

<?php

print
"AA
\
nBB
\
nCC
\
nDD
\
nEE";

?>

</pre>

Use "
\
n" to add a line break

AA

BB

CC

DD

EE

Use "
\
"
" to
add brakets<br>

<?php

print
"He said
\
"Hello
\
" to John";

?>

Use "
\
"
" to add brakets

He said "Hello" to John




Using variables: first step


With PHP we may also use variables. The variables used in PHP w
ill 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 var
iable names:

$my_favorite_song

$my_counter

$username

etc



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

mypage.php

<?php

$my_name="Joe";

$my_hello_text="Hello everybody!";

$year_create=2002;

?>


<html>

<head>

<title>This is

<?php
print


$my_name;
?>´s
page</title>

</head>


<body>


<?php print

$my_hello_text; ?>


This page was written in
<?php
print


$year_create;
?>.

</body>


</html
>


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


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_hel
lo_text


are strings

$year_create

is a number


We may also use variables in the following ways:

The code

The output

<?php

$year_create
=2002;

print


"This page was written in ".
$year_create
;

?>

This
page was written in 2002

<?php

$year_create
=2002;

print


"This page was written in
$year_create
";


?>

This page was written in 2002

<?php

$the_text
="This page was written in ";

$year_create
=2002;

print


$the_text
.
$year_create
;


?>

This page was written in 2002

<?php

$the_text
="This page was written in ";

$year_create
=2002;

print


"$the_text$year_cr
eate"
;


?>

This page was written in 2002


PHP tutorial: Displaying Date and Time

Displaying local time

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 w
hich is explained in the third column. The

column in the middle is the value of those
data the day we were preparing this page.




Code

Output



<?php
print


date
("a"); ?>

pm

"am" or "pm"

<?php
print


date
("A"); ?>

PM

"AM" or "PM"

<?php
print


date
("d"); ?>

15

Day of the month: 01 to 31

<?php
print


date
("D"); ?>

Tue

Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat

<?php
print


date
("F"); ?>

October

Month: January, February, March...

<
?php

print


date
("h"); ?>

03

Hour: 01 to 12

<?php
print


date
("H"); ?>

15

Hour: 00 to 23

<?php

print


date
("g"); ?>

3

Hour: 1 to 12

<?php
print


date
("G"); ?>

15

Hour: 0 to 23

<?php
print


date
("i"); ?>

26

Minutes: 00 to 59

<?php
print


date
("j"); ?>

15

Day of the month: 1 to 31

<?php

print


date
("l"); ?>

Tuesday

Day of the week: Sunday, Monday, Tuesday...

<?php

print


date
("L"); ?>

0

Is it a lea
p year? 1 (yes) or 0 (no)

<?php

print


date
("m"); ?>

10

Month: 01 to 12

<?php

print


date
("n"); ?>

10

Month: 1 to 12

<?php
print


date
("M"); ?>

Oct

Month: Jan, Feb, Mar, Apr, May...

<?php

print


date
("s"); ?>

03

Seconds: 00 to 59

<?php

print


date
("S"); ?>

th

Ordinal: 1
st
, 2
st
, 3
st
, 4
st
... Need to be used with a
numeric time/date value. See
latter
.

<?php
print


date
("t"); ?>

31

Number of days in the month: 28 to 31

<?php
print


date
("U"); ?>

1034691963


Seconds sinc
e 1970/01/01 00:00:00

<?php

print


date
("w"); ?>

2

Day of the week: 0 (Sunday) to 6 (Saturday)

<?php

p
rint


date
("Y"); ?>

2002

Year (four digits)

<?php
print


date
("y"); ?>

02

Year (two digits)

<?php
print


date
("z"); ?>

287

Day of the year: 0 to 365

<?php
print


date
("Z"); ?>

-
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 d
ifferent values simultaneously, we have at least three option:


The code

Output

<?php
print


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


date
("m"); ?>:

<?php
print


date
("d"); ?>

2002:10:15

<?php
print


date
("Y").":".
date
("m").":".
da
te
("d"); ?>

2002:10:15

<?php
print


date
("Y:m:d"); ?>

2002:10:15


The first option is very easy to understand (we have just copied the code from the table one by
one). The second option
concatenates

the data basically in the same way, an
d 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 withi
n 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 cor
responding value:


Y

:

Year (four digits)

no meaning

m

:

d







Month: 01 to 12

no meaning

Day of the month: 01 to 31


Check this usefull examples:

The code

Output

<?php
print


date
("Y:m:d H:i") ?>

2002:10:15 15:26

<?php
print


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

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

The time is <?php
print


date
("H:i") ?>.

That means it's <?php
print


date
("i") ?>

minutes past <?php
print


date
("H") ?>
o'clock.

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


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

The code

Output

Character

with meaning

<?php
print


date
("Today is
l"); ?>

WETo15pm02 2603
Tuesday

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

l

<?php
print


"Today is
".
date
("l"); ?>

Today is Tuesday

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



Example: Link of the Day

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



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

<a href= <?php
print


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


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


Using "S" with date comand.

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


Day

Code

Output

2002/01/01

<? php
print


date
("nS of F"); ?>

1st of January

2002/01/02

<? php
print


date
("nS of F"); ?>

2nd of January

2002/01/03

<? php
print


date
("nS of F"); ?>

3rd of January

2002/01/04

<? php
print


date
("nS of F"); ?>

4th of January

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


Displaying local time

In this tutorial we will consider our server is located in a different time zo
ne 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: <?
php
print


date
("H:i") ?>

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

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

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

<?php

$differencetolocaltime=4;

$new_U=
date
("U")
-
$differencetolocaltime*3600;

print
date
("H:i", $new_U);

?>

Lets explain this code:



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



In third line of the script we have create a variable named $new_U, and the value for this
variable will be 'date("U")' (Seconds since 1970/01/01 00:00:00) to which we have
substracted the difference of hours between the two

time zones (in our case 4 hours,
which is the value for the variable $differencetolocaltime, has been multiplied by 3600,
which is the number of seconds in one hour)



In the last step we have write to the document the new hour and time by using "
date
"
command to which we have let know the exact date (specified by

$new_U) from which
we want to get the time (if it is not specified, as for example when using 'date("H:i")', the
time and date in the server will b
e 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.

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 na
me=
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


S
end 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.php

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

Hi John, I
know you
$theage=$_POST["
theage
"];


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

?>

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


S
end info

Does not work


When submitting the form we will visit the URL bellow:

http://www.phptutorial. info/learn/GetandPost.php?
thename
=John&
theage
=30

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
depe
nding 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=Ge
tandpostexample.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"]=="Pa
olo") {



print
"
\
nPaolo
\
n From Roma. Student";



}
else
{



print
"
\
n<a href=Getandpos
texample.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 thi
s 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>


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




array.asp



<html>

<title>My Array</title>

<body>

<?php

$MyData [0] = "0"


$MyData [1] = "1"


$MyData [2] = "2"


$MyData [3] = "3"


$MyData [4] = "4"


$MyData [5] = "5"


$MyData [6] = "6"


$MyData [7] = "7"


$MyData [8] = "8"


$MyData [9] = "9"


print $MyData [5]
;

?>

</body>

</html>

1

2

3

4

5

6

7

8

9

10


11


12


13


14


15


16


17


18


19


20


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




array2.php


<html>

<title>My Array</title>

<
body>

<?php

$MyData [0][0] = "1";


$MyData [0][1] = "2";


$MyData [0][2] = "3";


$MyData [1][0] = "4";


$MyData [1][1] = "5";


$MyData [1][2] = "6";


$MyData [2][0] = "7";


$MyData [2][1] = "8";


$MyData [2][1] = "9";


print $MyData [1][2]
;

?>

</body>

</html>

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




MyData

0

1

2

0

1

2

3

1

4

5

6

2

7

8

9

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



Line 16
. In the response page we will
send the value assigned to
$MyData
[1][2]

in the array. The first number will
be the row and the second one the
column, so that in our case the response
page will show the value "6"



It is also possible to define an array
with more dimensions as for example


$MyData

[5][5][5][5][5]
.

Working with Arrays


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


array3a.php

Resulting
page

<pre>


<?


$Thearray=
array

("Zero","one","two","three","four","five","six","seven","eight","nine")


?>


Thearray(0):
Zero


Thearray(1):
pne


Thearray(2):
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>

two


Thearray(3):
three


Thearray(4):
four


Thearray(5):
five


Thearray(6):
six


Thearray(7):
seven


Thearray(8):
eigh
t


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 disc
over 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
$The
Array?

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



pri
nt
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
origi
nal 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 se
cond 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 lik
e the one bellow, and that
this table was the original source of information we used to create our table:




Pete
r

student

Chicag
o

12
3

Joh
n

teacher

Londo
n

23
4

Sue

Manag
er

Sidney

78
9


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 th
e 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($Myda
ta);

?>




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 as
king 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 s
tring 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);


}els
e{
























// 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 contain
ing 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.inf
o/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 scri
pt";




$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
file

Create and Write to a text file

Read and Write compressed files (.gz)

Exampl
e:
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, yo
u 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
($f
ilename));

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.t
xt";

// This is the absolute location within the hard disk

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

// This is the location relative to document root (the
folder con
taining 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 c
ommands 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

<?php

$filename="myfile.txt";


$lines=
file
($filename);

5

6

7

8

9

10

11


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 exampl
e 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 f
ile $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 tha
t 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 per
formed (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 t
he 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 process
ed.

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/sear
ch?p=myquery2

http://www.google.com/search?q=a+diferent+query

http://www.myreferrer2.com/dir/file33.html



PHP: Session


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

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


Passwo
rd 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 restrict
ed 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"){
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

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
authoriz
ed 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
informatio
n 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
inclu
de 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 site
s 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 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

<?php

2

3

4

5

6

7

8

9


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


shuffle

($the_numbers);


print

$the_numbers[0];


?>

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

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

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 r
epeated as many times as the length of the password we want to obtain.

1

2

3

4

5

<?php


$passwordlength=10;


$str =
6

7

8

9

1
0

1
1

1
2

1
3

1
4

1
5

1
6

"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 varia
ble $password.

Line 14:
The password is outputted.


Learn abour your server: php variables

The server which is hosting your site (we will supose in this tutorial you have an account with an
ISP, so you are not controling the server) may provide you


a
lot of useful information. In the
next table we have a very simple code which will allow us to get a huge amount of information
from the server.



askyourserver.php

<form method=post
action=askyourserver.php?a=1&b=2&c=3>

Name: <input type=text name=name>
<br>

Age: <input type=text name=age><br>

<input type=submit value=submit>

</form>

<hr>

<?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 aditional
information about the computer and how it h
as 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 d
ifferent data in that table. We do believe printing this response
page is very useful, so we recoment so.


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




PHP_SELF

/mydir
/askyourserver.php




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



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

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

We know PHP_SELF variable will provi
de 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