IP - Chapter Two P2
IP - Chapter Two P2
Mary’s University
Faculty of Informatics
Part 2
PHP 5 Functions
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach
loop, like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
13
?>
The following example sorts the elements of the $numbers array in
ascending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
14
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Example
Search an array for the value "red" and return its key:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
Definition and Usage
The array_search() function search an array for a value and returns the key .
Syntax
arrary_search(value, array, strict)
Parameter Description
value Required. Specifies the value to search for
array Required. Specifies the array to search in
strict •Optional. If this parameter is set to TRUE, then
this function will search for identical elements in
the array. Possible values:true
•false - Default
When set to true, the number 5 is not the same 19
PHP array_search() Function
More Examples
Example 1
Search an array for the value 5 and return its key (notice the ""):
<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>
20
PHP 5 Global Variables - Superglobals
Several predefined variables in PHP are "superglobals", which means that they are
always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
PHP $GLOBALS
is used to access global variables from anywhere in the PHP script (also from within
functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.
21
PHP $GLOBALS
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
22
PHP $_REQUEST
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
23
PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
Example
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
24
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" is
sent to "test_get.php", and you can then acces their values in "test_get.php" with
$_GET.
The example below shows the code in "test_get.php":
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html> 25
PHP 5 Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a
submit button:
Example
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php".
The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>
</body>
</html>
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
</body>
</html>
PHP 5 Form Validation
• PHP Form Validation Example
• * required field.
• Name: * Name is required
Website:
Comment:
submit
The validation rules for the form above are as follows:
Field Validation Rules
Text Fields
The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
The Form Element
The HTML code of the form looks like this:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When the form is submitted, the form data is sent with method="post".
What is the $_SERVER["PHP_SELF"] variable?
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
PHP 5 Date and Time
Parameter Description
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
</body>
</html>
PHP 5 Date and Time…
PHP Tip - Automatic Copyright Year
• Use the date() function to automatically update the copyright year on your
website:
Example
<!DOCTYPE html>
<html>
<body>
If the time you got back from the code is not the right time, it's probably because
your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set a
timezone to use.
The example below sets the timezone to "America/New_York", then outputs the
current time in the specified format:
Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
PHP 5 Date and Time…
The PHP strtotime() function is used to convert a human readable string to a Unix time.
Syntax
strtotime(time,now)
The example below creates a date and time from the strtotime() function:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
PHP 5 Include Files
The include (or require) statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or text
on multiple pages of a website.
PHP include and require Statements
• It is possible to insert the content of one PHP file into another PHP file (before the
server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include
file is missing, use the include statement. Otherwise, in case of FrameWork, CMS,
or a complex PHP application coding, always use the require statement to include a
key file to the flow of execution. This will help avoid compromising your application's
security and integrity, just in-case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header needs to
be updated, you can only update the header include file.
PHP 5 Include Files…
Syntax
include 'filename';
or
require 'filename';
PHP include Examples
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:
Example
<html>
<body>
</body>
</html>
PHP 5 Include Files…
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done (we are using a <div> element
so that the menu easily can be styled with CSS later):
Example
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
PHP include vs require
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is included
with the include statement and PHP cannot find it, the script will continue to execute:
Example
<html>
<body>
</body>
</html>
If we do the same example using the require statement, the echo statement will not be
executed because the script execution dies after the require statement returned a fatal
error:
Example
<html>
<body>
</body>
</html>
PHP 5 File Handling
File handling is an important part of any web application. You often need to open
and process a file for different tasks.
PHP has several functions for creating, reading, uploading, and editing files.
PHP readfile() Function
The readfile() function reads a file and writes it to the output
buffer.
Assume we have a text file called "webdictionary.txt", stored on
the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
PHP 5 File Handling…
The PHP code to read the file and write it to the output buffer is as follows (the
readfile() function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read
its contents.
PHP 5 File Open/Read/Close
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end
of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end
of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Read File - fread()
• The fread() function reads from an open file.
• The first parameter of fread() contains the name of the file to read from
and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize(“names.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.
• The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()
• The fgets() function is used to read a single line from a file.
The example below outputs the first line of the “names.txt" file:
Example
<?php
$myfile = fopen(“names.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP File upload
A PHP script can be used with HTML form to upload files to the server. Initially files
are uploaded into the temporary directory and then redirected to the target
destination by the PHP script.
Creating an upload form:
The following HTM code below creates an uploader form. This form is having
method attribute set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" > <br > <br>
<input type="submit" value=“submit" >
</form>
</body>
</html>
Creating an upload script
?>
<?php
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES["file"]['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = "uploads/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo "uploaded";
}
else "please select the file";
}
}
?>
<html>
<body>
<form action ="upload.php" method ="POST" enctype = "multipart/form-data">
The code below only allows users to upload JPG and JPEG files and also it only accept 2mb and less than, if this not true it generate error message “File must be jpg/jpeg and must
be 2mb or less”
<?php
$name = $_FILES[‘file’][‘name’];
$extension = strtolower(substr($name, strpos($name, “ .”) + 1));
$type = $_FILES[‘file’][‘type’];
$size = _FILES[‘file’][‘size’];
$max_size = 2097152;
$tmp_name = $_FILES["file"]['tmp_name'];
if(isset($name)){
if(!empty($name)){
If(($extension == ‘jpg’|| $extension == ‘jpeg’) && $type == ‘image/jpeg’ && $size <= $max_size){
$location = "uploads/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo "uploaded";
}
else “There was an error”;
}
}else { echo “File must be jpg/jppeg and must be 2mb or less”;
}
}
?>
<html>
<body>
<form action ="upload.php" method ="POST" enctype = "multipart/form-data">