php ii php form and file handling. php forms the php $_get and $_post variables/arrays are used to...

43
PHP II PHP Form and File Handling

Upload: luis-peterson

Post on 26-Mar-2015

262 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP II

PHP Form and File Handling

Page 2: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms

• The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms.

• The $_GET variable is used to collect values from a form with method="get". E.g. Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!

• The $_POST variable is used to collect values from a form with method="post". E.g. Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old!

• Why use $_POST?– Variables sent with HTTP POST are not shown in the URL. – The POST requests are not idempotent. This means that they

cannot be cached, and the server is recontacted every time the page is displayed. Because of this, it is not possible to bookmark the page.

– Variables have no length limit

Page 3: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms

<!--“welcome.html” file -->

<html> <body> <form

action="welcome.php" method="post">

<p>Name: <input type="text" name="name" /> </p>

<p>Age: <input type="text" name="age" /> </p>

<input type="submit" name="formSubmit" value="Submit" /></form>

</body> </html>

<!--"welcome.php” file -->

<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>

Page 4: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: • <!-- enter.html file -->

<html> <body> Please enter you

name and age below : <br /><form action="result.php"

method=get> My name is: <input

type="text" name="myname"><br />

My age is: <input type="text" name="myage"><br />

<input type = "submit" name = "submit" value ="go ahead!">

</form> </body></html>

<!-- result.php file -->

<html> <body><?php $myname = $_POST["myname"]; $myage = $_POST["myage"];echo "<h1>WOW! $myname you are $myage years old!!!</h1>"; ?></body></html>

Page 5: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

The $_REQUEST Variable

• The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods as well as $_COOKIE.

ExampleWelcome <?php echo

$_REQUEST["name"]; ?>.<br />You are <?php echo $_REQUEST["age"]; ?>

years old!

Page 6: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Self-Processing Pages Using the $_SERVER['PHP_SELF‘] variable This will return the filename of the currently

executing script, relative to the document root.

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. For instance, $_SERVER['PHP_SELF'] in a script

at the address http://example.com/test.php/foo.bar would be

/test.php/foo.bar.

Page 7: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Self-Processing Pages Using the PHP_SELF variable in the

action field of the form. Consider, you have a file called form-action.php

and want to load the same page after the form is submitted. The usual form code will be:

<FORM name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >

Page 8: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Self-Processing Pages The complete code of "form-action.php“.// checking if the form is submitted or not.

<?php

if(isset($_POST['submit'])) {

$name = $_POST['name'];

echo "User Has submitted the form and entered this name : <b> $name</b>";

echo "<br>You can use the following form again to enter a new name."; }

?>

<HTML> <HEAD><title>Using PHP_SELF</title></HEAD> <BODY>

<FORM method="post" action=“<?php echo $_SERVER['PHP_SELF']; ?>">

<input type="text" name="name"><br>

<input type="submit" name="submit" value="Submit Form"><br>

</FORM> </BODY> </HTML>

Page 9: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Self-Processing Pages

<! -- myform2.php -- ><! -- One PHP page can be used to both generate a form and

process it. -- >

<head><title>names</title></head>

<body>

<?php

echo("First name: " . $_POST['firstname'] . "<br />\n");

echo("Last name: " . $_POST['lastname'] . "<br />\n");

?>

<form action="myform2.php" method="post">

<p>First name:

<input type="text" name="firstname" /></p>

<p>Last name:

<input type="text" name="lastname" /></p>

<input type="submit" name="submit" value="Submit" />

</form></body></html>

Page 10: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Multivalued Parameters

To ensure that PHP recognizes the multiple values that the browser passes to a form processing script, you need to make the name of the field in the HTML form end with [ ].

For example:<select name="languages[ ]"><input name="c">C</input><input name="c++">C++</input><input name="php">PHP</input><input name="perl">Perl</input></select>

when the user submits the form, $_GET['languages'] contains an array instead of a simple string. This array contains the values that were selected by the user.

Page 11: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Multivalued Parameters<html>

<head><title>Personality</title></head>

<body>

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="GET">

Select your personality attributes:<br />

Perky <input type="checkbox" name="attributes[ ]" value="perky" /><br />

Morose <input type="checkbox" name="attributes[ ]" value="morose" /><br />

Thinking <input type="checkbox" name="attributes[ ]" value="thinking" /><br />

Feeling <input type="checkbox" name="attributes[ ]" value="feeling" /><br />

Spend-thrift <input type="checkbox" name="attributes[]" value="thrifty" /><br />

Shopper <input type="checkbox" name="attributes[ ]" value="shopping" /><br />

<input type="submit" name="s" value="Record my personality!" />

</form>

<?php

if (array_key_exists('s', $_GET)) {

$description = join (", ", $_GET['attributes']);

echo "You have a $description personality."; } ?> </body></html>

Page 12: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Form Validation

• User input should be validated whenever possible.

You can validate the form input on two places, client side (done with javascript) server side (done with PHP)

• Client side validation is faster, and will reduce server load.

• For security reason, use server side validation if the form accesses a database.

• Server side form validation with PHP can act as a backup just in case the user switch off javascript support on her browser.

Page 13: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Form Validation

Form validation must be carried out on every form element to guarantee that the input is correct and processing incorrect input values can make your application give unpredictable result.

A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.

Page 14: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Form Validation

Something you need to check : empty values numbers only input length email address strip html tags

Link to Table of Validation Descriptors

Page 15: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Form Validation with PHP

The easiest way to check to see if a user has typed in a value in the text boxes is to use the empty() function.

Example:if (!empty($_POST['fname'])){

$msg = "fname; $_POST[fname] ";}

else{$fname = NULL;echo "Please fill out your first name.";}

Page 16: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Form Validation with PHP

Using the preg_match function() preg_match() is a case sensitiv function, which

means it treats “a” and “A” differently.

Examplefunction check_field1($field_name_1)

{  if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\  ]+$/s”,$field_name_1))  return TRUE;  else  return FALSE;}

Other examples:

The slashes “/” and “/” are delimiters, “^” marks the start of string or line and the Dollar sign “$” the end of the string, or line. The plus-symbol “+” means required.

Page 17: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Forms: Self-Processing Pages

PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the current file (from the root folder).

Syntax: echo $_SERVER [‘PHP_SELF’]; It can be used in the action field of a form. Examplea) Suppose your php file is located at the address:

http://www.yourserver.com/form-action.php

PHP_SELF will contain: "/form-action.php"

b) Suppose your php file is located at the address:

http://www.yourserver.com/dir1/form-action.php

PHP_SELF will be : "/dir1/form-action.php"

Page 18: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

What are PHP_SELF exploits? If PHP_SELF is used in your page then a user can

enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute. example:

Consider that the user has called this script by entering the following URL in the browser's address bar:

http://www.yourdomain.com/form-action.php/%22%3E%3Cscript%3Ealert('xss')%3C /script%3E%3Cfoo%22

After PHP processing, the code becomes:<form name="test" method="post" action="form-action.php"/> <script>alert('xss')</script><foo"">

Page 19: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

How to avoid PHP_SELF exploits

by using the htmlentities() <form name="test" action="<?php echo

htmlentities($_SERVER['PHP_SELF']); ?>" method="post">

The result of entering malicious code in URL will result in the following output:

<form name="test" method="post" action="form-action.php/&quot;&gt;&lt;script&gt;alert('xss')& lt;/script&gt;&lt;foo">

the script part is now 'sanitized'. don't forget to convert every occurrence of

"$_SERVER['PHP_SELF']" into htmlentities($_SERVER['PHP_SELF'])" throughout your script.

Page 20: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP File Handling

File modifiers or indicators: Modes Description

r Read only. Starts at the beginning of the filer+ Read/Write. Starts at the beginning of the filew Write only. Opens and clears the contents of file; or

creates a new file if it doesn't existw+ Read/Write. Opens and clears the contents of file; or

creates a new file if it doesn't exista Append. Opens and writes to the end of the file or

creates a new file if it doesn't exist

a+Read/Append. Preserves file content by writing to the end of the file

x Write only. Creates a new file. Returns FALSE and an error if file already exists

x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

PHP Filesystem Functions

Page 21: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Opening a file

The first step to using a file is to open it using fopen() function. . fopen() prepares the file for use. It returns the reference to the file

for file variable. If it is unable to open the specified file, it returns 0 (false).

Syntax: Using file Handles $filename = "full path/name_of_file.txt"; $handle = fopen($filename, "r") or die("Can't open file");. . .fclose($handle);

Example$filename = “products.txt”;$handle = fopen($filename, "r") or die("Can't open file");. . . do something . . .fclose($handle);

Page 22: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP file_exists()

Checks whether a file or directory exists.

Syntax:file_exists ( string $filename )

Example #1<?php

$filename = '/path/to/foo.txt';

if (file_exists($filename)) {    echo "The file $filename exists";} else {    echo "The file $filename does not exist";}?>

Page 23: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Writing data to a text file

Writing data to a text file requires the use of the fputs() function. This function takes two

parameters - a file handle and a string of text.

Example:

<?php

$theFile = fopen("fileOne.txt", "w");

fputs($theFile, "line of text");

?>

Using the fwrite() function.

Example: <?php$myFile = "testFile.txt"; $fh

= fopen($myFile, 'w') or die("can't open file");

$stringData = "Floppy Jalopy\n";

fwrite($fh, $stringData);

$stringData = "Pointy Pinto\n";

fwrite($fh, $stringData);

fclose($fh); ?>

Page 24: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Check End-of-file

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.

You cannot read from files opened in w, a, and x mode!

Example:if (feof($file)) echo "End of file";

Page 25: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Reading data from a text file

Three different functions – fread() or file(), fgets(), and fgetc()

fread() function. It reads parts or whole of a file and retunes a string

of what was read.

Syntax fread(file,length)

Example: <?php $file = fopen("test.txt","r");fread($file,filesize("test.txt"));Print $file; fclose($file); ?>

Page 26: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Reading data from a text file

Three different functions – fread() or file(), fgets(), fgetc()

fgets() function. Returns a line from an open file When working with the fgets() function, files should be set

with the 'r' (read-only) access modifier.

Example: <?php$theFile = fopen("fileOne.txt", "r");$theText = fgets($theFile);print $theText;?>

Note: You cannot read from files opened in w, a, and x mode!

Page 27: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Reading a File Character by Character The fgetc() function is used to read a

single character from a file.

Example:<?php $file=fopen("welcome.txt","r") or

exit("Unable to open file!");while (!feof($file))

{ echo fgetc($file); }

fclose($file);?>

Page 28: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP File Upload

Example: upload_file.html

<html><body><form action="upload_file.php" method="post“

enctype="multipart/form-data"><label for="file">Filename:</label><input type="file" name="file" id="file" />

<br /><input type="submit" name="submit"

value="Submit" />

</form></body></html>

Page 29: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP File Upload

Example: upload_file.php<?phpif ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; }else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . "

Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; }?>

Page 30: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Restrictions on Upload<?phpif ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg"))&& ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br

/>"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } }else { echo "Invalid file"; }?>

Page 31: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Locking a File

Syntax:flock ( resource $handle , int $operation);

Parameters handle

An open file pointer.

operation operation is one of the following:

LOCK_SH to acquire a shared lock (reader). (set to 1 prior to PHP 4.0.1)

LOCK_EX to acquire an exclusive lock (writer). (set to 2 prior to PHP 4.0.1)

LOCK_UN to release a lock (shared or exclusive). (set to 3 prior to PHP 4.0.1)

LOCK_NB if you don't want flock() to block while locking. (not supported on Windows) (set to 4 prior to PHP 4.0.1)

Page 32: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Locking a File – Continued

flock() example1:

<?php

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock    fwrite($fp, "Write something here\n");    flock($fp, LOCK_UN); // release the lock} else {    echo "Couldn't lock the file !";}

fclose($fp);

?>

Page 33: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Locking a File – Continued

flock() example2:$fh = fopen("myfile", "r+"); if(flock($fh, 2)) echo ("An exclusive lock

has been acquired"); else die ("Lock couldn't be acquired"); /* perform safe read/write operations here

*/ fclose($fh);

Page 34: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP cookies

A 'cookie' is a small text file stored on a users hard drive by a website for various purposes such as remembering a user who frequents that website.

Setting a cookie The function used to set a cookie is

setcookie(). The setcookie() function must be declared

first thing on the page

Syntax of the setcookie() function: setcookie(name, value, expirationDate,

path, domain, isSecure, httpAccess);

Page 35: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP cookies – Continued

Example1: <?php setcookie("user", "Alex Porter", time()

+3600);?>

Page 36: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Reading data from a cookie

This is achieved through the isset() function, which is used to check for the existence of a variable.

Syntax: isset($_COOKIE['nameOfCookie']);

Example: <?php if (isset($_COOKIE['cookie1'])) {$cookie1 = $_COOKIE['cookie1'];}?>

Page 37: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

Example:<?php

// Print a cookieecho $_COOKIE["user"];// A way to view all cookiesprint_r($_COOKIE);

?>

Page 38: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

example: <?php

// set the expiration date to one hour agosetcookie("user", "", time()-3600);

?>

Page 39: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

PHP Sessions A session is the time a user spends at a

website encompassing everything they do in that time at the website.

Use the session_start() function. NOTE: The session_start() function must be

the first thing in your code, even before the <!DOCTYPE> declaration!

Starting a sessionExample: <?php

session_start();?>

Page 40: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Storing and using session variables

You can store and use session variables through the $_SESSION associative array.

Example: <?php$_SESSION['views'] = $_SESSION['views']

+ 1;?>

Page 41: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Destroying a session

Sessions are destroyed through the use of the session_destroy() function. Using session_destroy() will result in the

loss of all data stored in the session. Alternatively, you can use the unset()

function which will destroy only some of the data in the session, as opposed to the entire session.

Examples <?php unset($_SESSION['views']);?><?php session_destroy();?>

Page 42: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Difference between session and cookie? 1) session should work regardless of the

settings on the client browser. 2) session and cookies differ in type and

amount of information they are capable of storing.

• A cookie is a bit of information which is sent to your browser and stored there. The browser will send this information back to the server every time you send a request (to the server that set the cookie)

Page 43: PHP II PHP Form and File Handling. PHP Forms The PHP $_GET and $_POST variables/arrays are used to retrieve information from forms. The $_GET variable

Difference between session and cookie? 3). A session is a store of data on the server

containing state information on a user. A particular sessions is identified by its session id, ideally a large (i.e. unguessable) random number. For example, the session could hold a user's shopping cart.

A cookie is also a store. To create a cookie, the server sends a HTTP header to the client (i.e. the web browser). If the client supports and accepts the cookie, the cookie will be sent back to the server along with every request made to the server.