.
You are years old! The $_POST variable is used to collect values from a form with method="post". E.g. Welcome .
You are 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"> .
You are years old! The $_POST variable is used to collect values from a form with method="post". E.g. Welcome .
You are 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">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Form and File Handling

Similar presentations


Presentation on theme: "PHP Form and File Handling"— Presentation transcript:

1 PHP Form and File Handling
PHP II PHP Form and File Handling

2 PHP Forms Why use $_POST?
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

3 PHP Forms <html> <body>
<!--“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>

4 PHP Forms: <!-- result.php file -->
<!-- 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>

5 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. Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!

6 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 would be /test.php/foo.bar.

7 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']; ?>" >

8 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>

9 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>

10 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.

11 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>

12 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.

13 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.

14 Form Validation Something you need to check : empty values
numbers only input length address strip html tags Link to Table of Validation Descriptors

15 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. "; }

16 Form Validation with PHP
Using the preg_match function() preg_match() is a case sensitiv function, which means it treats “a” and “A” differently. Example function 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.

17 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. Example a) Suppose your php file is located at the address: PHP_SELF will contain: "/form-action.php" b) Suppose your php file is located at the address: PHP_SELF will be : "/dir1/form-action.php"

18 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: 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"">

19 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/"><script>alert('xss')& lt;/script><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.

20 PHP File Handling File modifiers or indicators:
Modes Description r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a 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

21 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);

22 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"; } ?>

23 Writing data to a text file
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"; fclose($fh); ?> 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"); ?>

24 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";

25 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); ?>

26 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!

27 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); ?>

28 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>

29 PHP File Upload Example: upload_file.php <?php 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"]; } ?>

30 Restrictions on Upload
<?php if ((($_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"; } ?>

31 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)

32 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); ?>

33 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);

34 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);

35 PHP cookies – Continued
Example1: <?php setcookie("user", "Alex Porter", time()+3600); ?>

36 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'];} ?>

37 How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value. Example: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>

38 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 ago setcookie("user", "", time()-3600); ?>

39 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 session Example: <?php session_start(); ?>

40 Storing and using session variables
You can store and use session variables through the $_SESSION associative array. Example: <?php $_SESSION['views'] = $_SESSION['views'] + 1; ?>

41 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();?>

42 Difference between session and cookie?
session should work regardless of the settings on the client browser. 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)

43 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.


Download ppt "PHP Form and File Handling"

Similar presentations


Ads by Google