12 - PHP(2) - online

advertisement
12 – PHP Contd.
Informatics Department
Parahyangan Catholic University
Super globals were introduced in PHP 4.1.0, and are builtin 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

$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;
?>

$_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

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'];
?>

$_REQUEST is used to collect data from a submitted
HTML form.
<?php
if (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
}
?>
$_POST is used to collect data from a submitted
HTML form with method="post".
 $_POST is also widely used to pass variables.
 Example: <?php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$name = $_POST['fname'];
echo "Hello $name !!";
}
else{
?>
<!– same form as previous slide -->
<?php
}
?>

$_GET can be used to collect data from a submitted
HTML form with method="get“

$_GET can also collect data sent in the URL

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 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
<?php
if (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>";
}
Sent through GET
else{
?>
<form method="post" action="hello.php?fname=Bob">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
}
?>
Sent through POST

There is no guarantee which fname will be recorded
in $_REQUEST

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>

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

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
}
?>

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


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

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

Example:
 myfile.txt contains:
<?php
readfile("myfile.txt");
?>
<?php
$num = readfile("myfile.txt");
echo "<br>$num";
?>
abcdefghijkl

The file_get_contents() reads entire file into a
string

Example:
<?php
$str = file_get_contents("myfile.txt");
for($i=0; $i<strlen($str); $i++)
echo $str[$i]."<br>";
?>

More options, see:
http://php.net/manual/en/function.file-get-contents.php
The file() function reads the entire file into an array.
One line per array’s element.
 Example:

 myfile.txt contains:
abcdefghijkl
hello
world!
12345
<?php
$lines = file("myfile.txt");
for($i=0; $i<sizeof($lines); $i+=2)
echo $lines[$i]."<br>";
?>

The fopen() function opens a file or URL for
reading. It returns a file handle.

Syntax:
fopen(filename, mode)
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

Example:
<?php
$handle = fopen("myfile.txt", "r");
if($handle){
echo "file successfully opened";
}
else{
echo "file not found";
}
?>

Example:
<?php
$handle = fopen("myfile2.txt", "r");
if($handle){
echo "file successfully opened";
}
else{
echo "file not found";
}
?>

How to remove warning messages ?
 fix the error that causes it !
 control which PHP errors are reported using the
error_reporting() function

Example:
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

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);

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

Example:
<?php
$PI = 3.141592;
$x = 5;
$handle = fopen("myfile2.txt", "w");
fprintf($handle, "x=%d\nPI=%.3f", $x, $PI);
fclose($handle);
?>

After running the PHP file, myfile2.txt
contains: x=5
PI=3.142

The printf() function writes a formatted
string to the output buffer (i.e., like echo)

The sprintf() returns a formatted string

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);
?>

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.

Example:
 file myfile.txt contains:
Monday, 26 October 2015
3.14 22/7
coma and space at file input is matched to
Alice Bob
coma and space in scanf’s formatting string
<?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 (,)

Each call to fscanf() reads one line from the file.

Example:
Monday, 26 October 2015
3.14 22/7
Alice Bob
<?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);
?>


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:
 123
myfile.txt contains:
456
<?php
$handle
$res1 =
$res2 =
$res3 =
= fopen("myfile.txt",
fscanf($handle, "%d",
fscanf($handle, "%d",
fscanf($handle, "%d",
"r");
$num1);
$num2);
$num3);
printf("%d %d<br>", $res1, $num1);
printf("%d %d<br>", $res2, $num2);
printf("%d %d<br>", $res3, $num3);
fclose($handle);
?>


The sscanf() function works similarly to fscanf(),
except that it parses input from a string
Example:
Monday, 26 October 2015
3.14 22/7
Alice Bob
<?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);
?>


The feof() function checks if the "end-of-file" (EOF)
has been reached. It is useful for looping through
data of unknown length.
Monday, 26 October 2015
Example:
3.14 22/7
Alice Bob
<?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);
?>

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 2015
3.14 22/7
Alice Bob
Charlie

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);
?>
Monday, 26 October
2015
3.14 22/7
Alice Bob
Charlie
fgets reads a line, including the
\n\r character.
New line on HTML code means
a space in the web page
why there is a space
on line 4 ?
Download