Pemrograman Berbasis Web12 – PHP Contd.
Informatics DepartmentParahyangan Catholic University
PHP Super globals
Super globals were introduced in PHP 4.1.0, and are built-in variables that are always available in all scopes
Several predefined variables in PHP are superglobals
The PHP super global variables are: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION
PHP $GLOBALS
$GLOBALS is a PHP super global variable which 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.
Example:<?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?>
PHP $GLOBALS
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
The entries in this array are created by the web server. There is no guarantee that every web server will provide same set of variables
Reference:http://php.net/manual/en/
reserved.variables.server.php
PHP $_SERVER
Example:<?php /*The filename of the currently executing script, relative to the document root*/echo $_SERVER['PHP_SELF']; echo "<br>";
/*The name of the server host*/echo $_SERVER['SERVER_NAME']; echo "<br>";
/*The IP address of the server*/echo $_SERVER['SERVER_ADDR']; echo "<br>";
/*Which request method was used to access the page, i.e. GET or POST*/echo $_SERVER['REQUEST_METHOD'];?>
PHP $_REQUEST
$_REQUEST is used to collect data from a submitted HTML form.
<?phpif (isset($_REQUEST['fname'])){
$name = $_REQUEST['fname'];echo "Hello $name !!";
}else{
?><form method="post" action="hello.php">Name: <input type="text" name="fname"><input type="submit"></form>
<?php}?>
PHP $_REQUEST
PHP $_POST
$_POST is used to collect data from a submitted HTML form with method="post".
$_POST is also widely used to pass variables.
Example:
<?phpif ($_SERVER['REQUEST_METHOD'] ==
'POST'){$name = $_POST['fname'];echo "Hello $name !!";
}else{
?><!– same form as previous slide -->
<?php}?>
PHP $_GET
$_GET can be used to collect data from a submitted HTML form with method="get“
$_GET can also collect data sent in the URL
PHP $_GET
Example:<?php
if (isset($_GET['fname'])){$name = $_GET['fname'];echo "Hello $name !!";
}else{
?><form method="get" action="hello.php">Name: <input type="text" name="fname"><input type="submit"></form>
<?php}?>
$_REQUEST VS $_GET VS $_POST
$_REQUEST is an associative array that by default contains the contents of $_GET, $_POST and $_COOKIE
There is no guarantee that the $_REQUEST data comes from the source we wanted, thus it is more reliable to use $_POST or $_GET or $_COOKIE
$_REQUEST VS $_GET VS $_POST
<?phpif (isset($_REQUEST['fname'])){
$name = $_REQUEST['fname'];echo "REQUEST : Hello $name !!<br>";$name = $_GET['fname'];echo "GET : Hello $name !!<br>";$name = $_POST['fname'];echo "POST : Hello $name !!<br>";
}else{
?><form method="post" action="hello.php?
fname=Bob">Name: <input type="text" name="fname"><input type="submit"></form>
<?php}?>
Sent through GET
Sent through POST
$_REQUEST VS $_GET VS $_POST
There is no guarantee which fname will be recorded in $_REQUEST
PHP Form Validation
Suppose we have form like this:
<form method="post" action="hello.php">Name: <input type="text" name="fname" required><i><font color="red">*required</font></i><br><input type="submit"></form>
PHP Form Validation
Since the validation is done by HTML (client side), it is easy to override. One can rewrite the HTML code without the required attribute.
Thus it is important to validate the form’s input at the server’s side.
Client side form validation is useful for giving the user a quick feedback whether he/she has filled the form correctly
PHP Form Validation
Example:<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){if(isset($POST['fname'])){
$name = $_POST['fname'];echo "Hello $name !!<br>";
}else{
echo "Error: no name was provided!";}
}else{
?><!-- HTML form here -->
<?php}?>
PHP File Handling
File handling is an important part of any web application. You often need to open and process a file for different tasks.
Our discussion includes: Reading a file’s content Writing to a file Uploading a file
PHP File Handling
When we are manipulating files we must be very careful.
We can do a lot of damage if we do something wrong. Common errors are: editing the wrong file filling a hard-drive with garbage data eleting the content of a file by accident
readfile() Function
The readfile() function reads a file and writes everything in it to the output buffer (i.e., echoes everything in it)
The readfile() function returns the number of bytes read on success
readfile() Function
Example: myfile.txt contains:
<?phpreadfile("myfile.txt");?>
<?php$num = readfile("myfile.txt");echo "<br>$num";?>
abcdefghijkl
file_get_contents() Function
The file_get_contents() reads entire file into a string
Example:
More options, see: http://php.net/manual/en/function.file-get-contents.php
<?php$str =
file_get_contents("myfile.txt");for($i=0; $i<strlen($str); $i++)
echo $str[$i]."<br>";
?>
file() function
The file() function reads the entire file into an array. One line per array’s element.
Example: myfile.txt contains:abcdefghijkl
helloworld!12345
<?php$lines = file("myfile.txt");for($i=0; $i<sizeof($lines); $i+=2)
echo $lines[$i]."<br>";
?>
fopen() function
The fopen() function opens a file or URL for reading. It returns a file handle.
Syntax:fopen(filename, mode)
fopen() function
Mode
R/W ? File doesn’t exist
File already exist
Pointer at
r read only failed to open successfully opens it
beginning
r+ read & write
failed to open successfully opens it
beginning
w write only creates new file
replace with a new file
beginning
w+ read & write
creates new file
replace with a new file
beginning
a write only creates new file
appends to existing file
end
a+ read & write
creates new file
appends to existing file
end
x write only creates new file
failed to replace beginning
x+ read & write
creates new file
failed to replace beginning
c write only creates new file
appends to existing file
beginning
c+ read & write
creates new file
appends to existing file
beginning
fopen() function
Example:<?php$handle = fopen("myfile.txt", "r");if($handle){
echo "file successfully opened";}else{
echo "file not found";}?>
fopen() function
<?php$handle = fopen("myfile2.txt", "r");if($handle){
echo "file successfully opened";}else{
echo "file not found";}?>
Example:
error_reporting() function
How to remove warning messages ? fix the error that causes it ! control which PHP errors are reported
using the error_reporting() functionExample:error_reporting(E_ERROR | E_PARSE);tells PHP to only shows fatal run-time errors and parse errors.
Complete reference: http://php.net/manual/en/errorfunc.constants.php
fclose() function
The fclose() function is used to close an opened file.
It is important to close an opened file after we finish using it (reading/writing), so that other program can access it.
Example:fclose($handle);
fprintf() function
The fprintf() function writes a formatted string to a stream (i.e., opened file)
Syntax:fprintf(handle, format, [variables])
Works like printf in Java/C
fprintf() function
Example:
After running the PHP file, myfile2.txt contains:
<?php$PI = 3.141592;$x = 5;$handle = fopen("myfile2.txt", "w");fprintf($handle, "x=%d\nPI=%.3f", $x,
$PI);fclose($handle);
?>
x=5PI=3.142
printf() & sprintf() function
The printf() function writes a formatted string to the output buffer (i.e., like echo)
The sprintf() returns a formatted string
printf() & sprintf() function
Example:<?php
$PI = 3.141592;$x = 5;$str = "";$str = sprintf("x=%d\nPI=%.3f", $x, $PI);printf("String str now contains:<br>%s<br>",
$str);?>
fscanf() function
The fscanf() function parses input from a file according to a format
Syntax:fscanf(handle, format, [variables])
Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab \t in the format string can match a single space character in the input stream.
fscanf() function
Example: file myfile.txt contains:
Monday, 26 October 20153.14 22/7Alice Bob
<?php$handle = fopen("myfile.txt", "r");fscanf($handle, "%[^,], %d %s %d", $day, $date, $month, $year);printf("%s<br>%d<br>%s<br>%d<br>", $day, $date, $month, $year);?>%[^,] is a regular expression that means read a string which doesn’t contain a coma (,)
coma and space at file input is matched to coma and space in scanf’s
formatting string
fscanf() function
Each call to fscanf() reads one line from the file.
Example:
<?php$handle = fopen("myfile.txt", "r");fscanf($handle, "%[^\,], %d %s ", $day, $date, $month);fscanf($handle, "%d", $year);printf("%s<br>%d<br>%s<br>%d<br>", $day, $date, $month, $year);?>
Monday, 26 October 20153.14 22/7Alice Bob
fscanf() function
If fscanf() used with >2 arguments (that is, we specify the variables to store the parsed values), it returns the number of successfully parsed values. It returns ≤ 0 when no values parsed.
Example: myfile.txt contains:123
456
<?php$handle = fopen("myfile.txt", "r");$res1 = fscanf($handle, "%d", $num1);$res2 = fscanf($handle, "%d", $num2);$res3 = fscanf($handle, "%d", $num3);
printf("%d %d<br>", $res1, $num1);printf("%d %d<br>", $res2, $num2);printf("%d %d<br>", $res3, $num3);fclose($handle);?>
sscanf() function
The sscanf() function works similarly to fscanf(), except that it parses input from a string
Example: <?php$handle = fopen("myfile.txt", "r");fscanf($handle, "%[^\n\r]",$str);printf("Variable str contains: %s<br>", $str);
sscanf($str, "%[^\,], %d %s %d", $day, $date, $month, $year);printf("%s<br>%d<br>%s<br>%d<br>", $day, $date, $month, $year);fclose($handle);?>
Monday, 26 October 20153.14 22/7Alice Bob
feof() function
The feof() function checks if the "end-of-file" (EOF) has been reached. It is useful for looping through data of unknown length.
Example:<?php$handle = fopen("myfile.txt", "r");$i = 1;while(!feof($handle)){
fscanf($handle, "%[^\n\r]", $str);printf("Line %d: %s<br>", $i++, $str);
}fclose($handle);?>
Monday, 26 October 20153.14 22/7Alice Bob
feof() function
Example:<?php$handle = fopen("myfile.txt", "r");$i = 1;while(!feof($handle)){
$res = fscanf($handle, "%[^\n\r]", $str);printf("Line %d: %d [%s]<br>", $i++, $res, $str);
}fclose($handle);?>
Monday, 26 October 20153.14 22/7Alice Bob
Charlie
fgets() function
The fgets() function reads one line from a file, including the new line character (\n\r). It can reads an empty line.
Example:<?php$handle = fopen("myfile.txt", "r");$i = 1;while(!feof($handle)){
$str = fgets($handle);printf("Line %d: [%s]<br>", $i++, $str);
}fclose($handle);?>
fgets() function
Monday, 26 October 20153.14 22/7Alice Bob
Charliewhy there is a space on line 4 ?
fgets reads a line, including the \n\r
character.New line on HTML code
means a space in the web page
Top Related