PHP Form and File Handling

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

WEB DESIGN TABLES, PAGE LAYOUT AND FORMS. Page Layout Page Layout is an important part of web design Why do you think your page layout is important?
FORM VALIDATION Faheem Ahmed Khokhar. FORM VALIDATION Faheem Ahmed Khokhar.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
CHAPTER 3 MORE ON FORM HANDLING INCLUDING MULTIPLE FILES WRITING FUNCTIONS.
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
1 Chapter 5 – Handling HTML Controls in Web Pages spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
DT211/3 Internet Application Development JSP: Processing User input.
Tutorial 6 Working with Web Forms
Website Development Introducing PHP The PHP scripting language Syntax derives from C, Java and Perl Open Source Links to MySql database.
Tutorial 6 Working with Web Forms. XP Objectives Explore how Web forms interact with Web servers Create form elements Create field sets and legends Create.
CGI Programming: Part 1. What is CGI? CGI = Common Gateway Interface Provides a standardized way for web browsers to: –Call programs on a server. –Pass.
15. User Authentication, Form Validation, Paging. M. Udin Harun Al Rasyid, S.Kom, Ph.D
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Client-Side programming with JavaScript 3
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Advance Database Management Systems Lab no. 5 PHP Web Pages.
Advance web Programming Chapter 3: MySQL Date: 28 April 2014 Advance web Programming Chapter 3: MySQL Date: 28 April 2014 Dr. Mogeeb A. A. Mosleh .
Chapter 4 Handling User Input PHP Programming with MySQL 2nd Edition
JavaScript Form Validation
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
(c) Manzur Ashraf, Short course, KFUPM PHP & MySQL 1 Basic PHP Class 2.
PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
INTERNET APPLICATION DEVELOPMENT For More visit:
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.
Tutorial 14 Working with Forms and Regular Expressions.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
Week 7. Lecture 3 PHP Forms. PHP forms In part 2 of this course, we discussed html forms, php form is similar. Lets do a quick recap of the things we.
JavaScript, Fourth Edition
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Python CGI programming
Chapter 8 Cookies And Security JavaScript, Third Edition.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
NMD202 Web Scripting Week3. What we will cover today Includes Exercises PHP Forms Exercises Server side validation Exercises.
Website Development with PHP and MySQL Saving Data.
LOGO FORMs in HTML CHAPTER 5 Eastern Mediterranean University School of Computing and Technology Department of Information Technology ITEC229 Client-Side.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
1 © Netskills Quality Internet Training, University of Newcastle HTML Forms © Netskills, Quality Internet Training, University of Newcastle Netskills is.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Dynamic web content HTTP and HTML: Berners-Lee’s Basics.
Tutorial 6 Working with Web Forms. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Explore how Web forms interact with.
Topics Sending an Multipart message Storing images Getting confirmation Session tracking using PHP Graphics Input Validators Cookies.
Storing and Retrieving Data
Introduction to JavaScript CS101 Introduction to Computing.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
Part 2 Lecture 9 PHP Superglobals and Form Handling.
 Previous lessons have focused on client-side scripts  Programs embedded in the page’s HTML code  Can also execute scripts on the server  Server-side.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Tutorial 6 Working with Web Forms. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Explore how Web forms interact with.
Since you’ll need a place for the user to enter a search query. Every form must have these basic components: – The submission type defined with the method.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
PHP Syntax You cannot view the PHP source code by selecting "View source" in the browser - you will only see the output from the PHP file, which is plain.
COSC 2328 – Web Programming.  PHP is a server scripting language  It’s widely-used and free  It’s an alternative to Microsoft’s ASP and Ruby  PHP.
INTERNET APPLICATIONS CPIT405 Forms, Internal links, meta tags, search engine friendly websites.
CGS 3066: Web Programming and Design Spring 2016 PHP.
Unit 4 Working with data. Form Element HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons,
Radoslav Georgiev Telerik Corporation
Simple PHP Web Applications Server Environment
Web Programming– UFCFB Lecture 17
<?php require("header.htm"); ?>
JavaScript: Introduction to Scripting
Presentation transcript:

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

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

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>

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>

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!

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.

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

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>

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>

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.

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>

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.

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.

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

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

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.

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

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

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.

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

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

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

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

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

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

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!

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

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>

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

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

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)

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

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

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

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

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

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

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

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

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

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

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)

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.