years old.">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 PHP II PHP Form and File Handling

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

3 PHP Forms Name: Age: Welcome. You are years old.

4 PHP Forms: Please enter you name and age below : My name is: My age is:

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. You are 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: " >

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

9 PHP Forms: Self-Processing Pages names First name: Last name:

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: C C++ PHP Perl 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 Personality " method="GET"> Select your personality attributes: Perky Morose Thinking Feeling Spend-thrift Shopper

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: alert('xss')

19 How to avoid PHP_SELF exploits by using the htmlentities() " method="post"> The result of entering malicious code in URL will result in the following output: 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: ModesDescription rRead only. Starts at the beginning of the file r+Read/Write. Starts at the beginning of the file wWrite 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 aAppend. 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 xWrite 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

23 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: Using the fwrite() function. Example:

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:

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

28 PHP File Upload Example: upload_file.html Filename:

29 PHP File Upload Example: upload_file.php 0) { echo "Error: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; echo "Stored in: ". $_FILES["file"]["tmp_name"]; } ?>

30 Restrictions on Upload 0) { echo "Error: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; 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:

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:

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:

37 How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. Example:

38 How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past. example:

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 declaration! Starting a session Example:

40 Storing and using session variables You can store and use session variables through the $_SESSION associative array. Example:

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

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

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

Similar presentations


Ads by Google