PHP Handout PF
PHP Handout PF
PHP Handout PF
!! !!
"" ""
! !
" "
Back Back
Close Close
Advantages of Perl/PHP (Cont.) Disadvantages of Perl/PHP
PHP also has some advantages: Perl:
• It is included inside HTML pages. • Management of simple scripts is more difficult than PHP:
This means that: – Scripts need to be loaded separately from the HTML pages.
– All your work can be done in the same directory, and 688 – Typically scripts also be kept in a special directory — E.g. 689
!! !!
"" ""
! !
" "
Back Back
Close Close
• Store file the same directory as HTML pages (not cgi-bin) • Run files by accessing through Web browser
• Link from web pages via standard URL – Must be run via web server URL
– Cannot run PHP through local file:// URL.
• Possible to run (test/debug) scripts from UNIX/Mac OS X
command line via Telnet/Terminal.
!! !!
"" ""
! !
" "
Back Back
Close Close
Including PHP in a Web Page What happens when the page is loaded?
There are 4 ways of including PHP in a web page
When the script is run:
1. <?php echo("Hello world"); ?>
2. <script language = "php"> • The code is executed and
echo("Hello world"); 694 • The tag is replaced the by the output (‘‘Hello world’’) in 695
</script> examples above.
3. <? echo("Hello world"); ?> • Replacement is exactly where the PHP is relation to HTML.
4. <% echo("Hello world"); %> – When you view source of a PHP/HTML page you do not see
the PHP.
You can also use print instead of echo
• Can have more than one PHP tag in a single Web page.
• Method (1) is clear and unambiguous — My preferred method
• Method (2) is useful in environments supporting mixed scripting
languages in the same HTML file (most do not) !! !!
"" ""
• Methods (3) and (4) depend on the server configuration
! !
" "
Back Back
Close Close
A Simple PHP Script Example Basic PHP
Here is first complete PHP script which is embedded in HTML: Comments
• We create a level one header with the PHP output text. PHP supports three types of comments:
• This file is called hello.php:
696 1. Shell style comments - denoted #THIS IS A COMMENT 697
<html>
<head> 2. C++ style comments - denoted THIS IS A COMMENT—
<title>Hello world</title>
3. C style comments - denoted /* ALL THIS COMMENTED! */
</head>
<body>
<h1><?php echo("Hello world"); ?></h1>
<h1><?php print("This prints the same thing!"); ?></h1>
</body>
<html> !! !!
"" ""
! !
" "
Back Back
Close Close
The foreach command can be used to loop through an array: The foreach command can be used to loop through an associative array:
foreach ($food as $day => $item){
foreach ($person as $name){ echo "Today is $day, Eat $item\n";
echo "Hello, $name\n"; }
} A few things to note in the above:
$a = 3; function what() {
++$a;
function what() { 706 echo "a = $a\n"; 707
++$a; }
echo "a = $a\n";
} what();
echo "a = $a\n";
what();
In PHP:
echo "a = $a\n";
• The variable $a in the function what() is different to outside
Is variable $a global/local? variable $a
!! • Not recommended programming practice to have two variables !!
What is the output of both echo(..)s —- Is it 4? "" of the same name. ""
Answer: NO it is 1 and then 3! ! • So the local function prints the value 1 whilst !
" "
We actually have two variables called $a!! • The outer prints 3.
Back Back
Close Close
Global Variables Flow-Control Statements
So how do we share global values with a function? PHP provides the standard Flow-controls statements
• You must declare a variable inside a function as global if, if/else
switch
So our previous example could be phrased as:
708 709
while
$a = 3;
for
function what() {
global $a;
Basic syntax is same as Perl, Java, C, C++.
++$a;
echo "a = $a\n"; We therefore jump over examples here for now
}
!! !!
what();
"" ""
echo "a = $a\n";
! !
" "
Now the output is 4 at both prints. Back Back
Close Close
!! !!
"" ""
! !
" "
Back Back
Close Close
PHP Regular Expression Example Explained
The function preg match():
• Can take just two parameters as well: E.g. Some Practical PHP Examples
if (preg_match($pattern,$test) { A 1 line PHP Script
echo("Match Found\n"); 712 713
} Here a simple 1 line PHP script, phpinfo.php:
• However in this more complex example we use the parenthesis <?php phpinfo() ?>
as memory feature of regular expressions. It prints out information on the PHP system currently running:
• The $matches parameter is used to store the results of matches
in the brackets
• The (\ws) matches any word character followed by a letter s.
• The two matches are separated by a single space \s
• This first element of $matches stores to complete pattern match: !! !!
is is "" ""
! !
• The next two elements are the sub matches (delimited by
" "
parenthesis): two times is
Back Back
Close Close
• Finding Version of PHP that is installed on the Web server • As in Perl ,a forms action references a script, .php in this case.
• Getting other PHP/Server stats • The .php script then extracts the information, making it global.
!! !!
"" ""
! !
" "
Back Back
Close Close
A Simple PHP/HTML Form Processing Example A Simple PHP/HTML Form Processing Example (Cont.)
Lets Consider the Following HTML Form Source, form1.html: The form clearly looks like this:
<html> <head>
<title>Form 1</title>
</head>
<body>
<form name="whoAreYou" method="GET" 716 717
action="form1.php">
<h2>Who are you?</h2>
<h4>Name:<input type="text" name="username"></h4>
<h4>Address:<input type="text" name="address"></h4>
<input type="submit" value="Send">
</form>
</body> </html>
A Simple PHP/HTML Form Processing Example (Cont.) Alternatively, you could have
The PHP which processes this is very simple, form1.php:
<html>
<html>
<head> <head><title>form_do.php</title> </head>
<title>form1.php</title> <body>
</head> <?php
<?php extract($_GET); ?> 718 719
<body> extract( $_GET );
<h2>Your name is: <?php echo($username); ?></h2> print("<h2>HELLO</h2>");
<h2>Your address is: <?php echo($address); ?></h2>
</body>
print $username;
<html> print("<h1>address</h1>");
print $address;
The output of the PHP script looks something like this: ?>
</body>
</html>
!! !!
"" • Note that HTML tags may be enclosed in the print statements ""
! • extract($_GET); is used to access form variables. !
" "
• If using POST then use extract($_POST); instead of GET
Back Back
Close Close
Creating and Processing Forms in One PHP file Forms and Processing Forms in one PHP/HTML File Example
Consider the following example, a very basic/limited calculator,
You can have the action of form self-reference the page that <html>
created the form, This: <head>
<title>Very Simple Calculator Indeed...</title>
</head>
720 721
• Keeps all form processing in one file <body>
<h1>CALCULATOR!</h1>
• Is excellent for Web page develop and upkeep if:
<form action = "<?php echo $_SERVER[’PHP_SELF’]; ?>"
– Small PHP Scripts method = "GET">
– Not too many fragments of PHP in single document. Enter a number:
<input type = "text" name = "thenumber" /> <br/>
• Example: Highlights many good features of PHP <input type = "submit" name = "Mul Num"/>
</form>
<?php
!! extract($_GET);
$theanswer = $thenumber* 321;
!!
"" print("The number x 321 is:". $theanswer); ""
! ?> !
</body>
" </html>
"
Back Back
Close Close
Forms and Processing Forms in one PHP/HTML File Example Sending Email from PHP
Explained Again this is a relatively simple task in PHP:
One new PHP point to note: • The mail() function allows your scripts to send email.
• PHP has a variety of special variables — a bit like Perl. For example:
<html>
• $ SERVER[’PHP SELF’] is an associative array that holds 722
<head>
723
information about the server that runs the script. <title>Email</title>
</head>
• PHP SELF refers to the current PHP page that is running and set <body>
the ACTION attribute: <?php
$to = "[email protected]";
– Makes for portable code to use this $subject = "PHP is Great";
$body = "Hello how are you goodbye";
– Can change file name and it still self-references the page $headers = "From: [email protected]\r\n";
• Much better than and explicit URL to the page $sent = mail($to, $subject, $body, $headers);
• Need to print the elements to form. Can do this in php script + !! if($sent)
!!
echo "Mail sent to $to";
format with HTML "" else ""
! echo "Error sending mail"; !
?>
" </body> "
Back </html> Back
Close Close
Sending Email from PHP Example Explained Dates in PHP
PHP has many functions for manipulating dates and times.
• Hopefully everything is pretty much self explanatory • The date(date string) function can be used
• Note that mail() – To extract date information out in a variety of formats
724 depending on parameters set in the date string). 725
– Has obvious parameters:
• The date string, date string), may have the following formats
$to, $subject, $body, $headers.
– Returns a boolean value (stored in $sent) which checked by
if statement
!! !!
"" ""
! !
" "
Back Back
Close Close
MySQL Example: PHP Database Querying MySQL Example: PHP Database Query Example Output
Now to the PHP side to query the database and display results on The output of this query is as follows:
screen, toys1.php:
<h2>Toys for sale</h2>
<pre>
<?php
// open database connection 738 739
$connection
= mysql_connect("localhost", "scmxx", "password");
// select the database called "toyshop"
mysql_select_db("toyshop", $connection)
or die("Failed!");
// run the query on the database
$result
= mysql_query("SELECT * FROM toys", $connection);
or die("Failed!"); or
Here we assume that toyshop is the name of database created. !! $query = "SELECT * FROM toys"; !!
$result = mysql_query($query, $connection);
"" ""
! !
" "
Back Back
Close Close
4. Retrieve a row of results 5. Extract attribute values
• Retrieve a row of results using mysql fetch row() • Extract attribute values using mysql num fields()
• Parameters • Parameters:
– The result set handle (obtained in step 3) – The result set handle (obtained in step 3)
• Return value 744 • Return value 745
– The next row of the result set, or false when no more data is – The number of fields of the current row
available. • Use a for loop to retrieve the fields
• Use a while loop to retrieve the rows
for($i=0; $i<mysql_num_fields($result); $i++) {
// process data here
while($row = mysql_fetch_row($result)) { echo $row[$i]." ";
// extract attribute values }
// (step 5) and process
}
!! !!
"" ""
! !
" "
Back Back
Close Close