Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Slide 1 of 40 PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. EX: Name: CENG 449 Lecture 11.
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.
JavaScript Forms Form Validation Cookies CGI Programs.
Simple PHP application. A simple application We are going to develop a simple PHP application with a Web interface. The user enters two numbers and the.
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.
PHP Forms. I. Using PHP with HTML Forms A very common application of PHP is to have an HTML form gather information from a website's visitor and then.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
IS1500: Introduction to Web Development
PHP Overview CS PHP PHP = PHP: Hypertext Preprocessor Server-side scripting language that may be embedded into HTML One goal is to get PHP files.
MS3304: Week 4 PHP & HTML Forms. Overview HTML Forms elements refresher Sending data to a script via an HTML form –The post vs. get methods –Name value.
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 .
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Web forms in PHP Forms Recap  Way of allowing user interaction  Allows users to input data that can then be processed by a program / stored in a back-end.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
Chapter 4 Handling User Input PHP Programming with MySQL 2nd Edition
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.
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:
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.
Hazırlayan:Emin BORANDAĞ 9/8/ Php Define 9/8/20152.
INTERNET APPLICATION DEVELOPMENT For More visit:
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.
Slide 1 of 40 PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. EX: Name: CENG 449 Lecture 11.
Python CGI programming
CSC 2720 Building Web Applications HTML Forms. Introduction  HTML forms are used to collect user input.  The collected input is typically sent to a.
Website Development with PHP and MySQL Saving Data.
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:
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
HTML FORMS GET/POST METHODS. HTML FORMS HTML Forms HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes,
XHTML & Forms. PHP and the WWW PHP and HTML forms – Forms are the main way users can interact with your PHP scrip Typical usage of the form tag in HTML.
Topics Sending an Multipart message Storing images Getting confirmation Session tracking using PHP Graphics Input Validators Cookies.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Forms Collecting Data CSS Class 5. Forms Create a form Add text box Add labels Add check boxes and radio buttons Build a drop-down list Group drop-down.
Part 2 Lecture 9 PHP Superglobals and Form Handling.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
CHAPTER 7 Introduction to PHP5 Part II อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
HTML Forms. A form is simply an area that can contain form fields. Form fields are objects that allow the visitor to enter information - for example text.
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.
NMD202 Web Scripting Week2. Web site
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.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
INTERNET APPLICATIONS CPIT405 Forms, Internal links, meta tags, search engine friendly websites.
CGS 3066: Web Programming and Design Spring 2016 PHP.
PHP and Form Processing CS3520. Idea We have an HTML form that when user clicks on it in their browser a CGI HTTP request is created by the browser and.
HTML III (Forms) Robin Burke ECT 270. Outline Where we are in this class Web applications HTML Forms Break Forms lab.
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,
FORMS Explained By: Jasdeep Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
PHP – Hypertext Preprocessor.
Web Systems & Technologies
Pemrograman WEB I Pertemuan 6.
CS 330 Class 7 Comments on Exam Programming plan for today:
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
PHP Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in.
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
PHP FORM HANDLING Post Method
Introduction to Web programming
Dr. John P. Abraham Professor UTRGV eCommerce CSCI 6314
PHP Forms and Databases.
PHP Lecture 11 Kanida Sinmai
PHP-II.
Presentation transcript:

Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are: – $GLOBALS – $_SERVER – $_REQUEST – $_POST – $_GET – $_FILES – $_ENV – $_COOKIE – $_SESSION

$GLOBALS $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 – Output: 100

$_SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. Example – "; echo $_SERVER['SERVER_NAME']; echo " "; echo $_SERVER['HTTP_HOST']; echo " "; echo $_SERVER['HTTP_REFERER']; echo " "; echo $_SERVER['HTTP_USER_AGENT']; echo " "; echo $_SERVER['SCRIPT_NAME']; ?> Output: /php/demo_global_server.php hp.asp?filename=demo_global_server Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/ (KHTML, like Gecko) Chrome/ Safari/ /php/demo_global_server.php

Element/CodeDescription $_SERVER['PHP_SELF']Returns the filename of the currently executing script $_SERVER['GATEWAY_INTERFA CE'] Returns the version of the Common Gateway Interface (CGI) the server is using $_SERVER['SERVER_ADDR']Returns the IP address of the host server $_SERVER['SERVER_NAME']Returns the name of the host server (such as $_SERVER['SERVER_SOFTWAR E'] Returns the server identification string (such as Apache/2.2.24) $_SERVER['SERVER_PROTOCOL '] Returns the name and revision of the information protocol (such as HTTP/1.1) $_SERVER['REQUEST_METHOD' ] Returns the request method used to access the page (such as POST) $_SERVER['REQUEST_TIME']Returns the timestamp of the start of the request (such as ) $_SERVER['QUERY_STRING']Returns the query string if the page is accessed via a query string $_SERVER['HTTP_ACCEPT']Returns the Accept header from the current request $_SERVER['HTTP_ACCEPT_CHA RSET'] Returns the Accept_Charset header from the current request (such as utf-8,ISO )

$_SERVER['HTTP_HOST']Returns the Host header from the current request $_SERVER['HTTP_REFERER']Returns the complete URL of the current page (not reliable because not all user- agents support it) $_SERVER['HTTPS']Is the script queried through a secure HTTP protocol $_SERVER['REMOTE_ADDR']Returns the IP address from where the user is viewing the current page $_SERVER['REMOTE_HOST']Returns the Host name from where the user is viewing the current page $_SERVER['REMOTE_PORT']Returns the port being used on the user's machine to communicate with the web server $_SERVER['SCRIPT_FILENAME' ] Returns the absolute pathname of the currently executing script $_SERVER['SERVER_ADMIN']Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as

$_SERVER['SERVER_PORT']Returns the port on the server machine being used by the web server for communication (such as 80) $_SERVER['SERVER_SIGNATU RE'] Returns the server version and virtual host name which are added to server-generated pages $_SERVER['PATH_TRANSLATED '] Returns the file system based path to the current script $_SERVER['SCRIPT_NAME']Returns the path of the current script $_SERVER['SCRIPT_URI']Returns the URI of the current page

$_REQUEST The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods. Example <?php if( $_REQUEST["name"] || $_REQUEST["age"] ) { echo "Welcome ". $_REQUEST['name']. " "; echo "You are ". $_REQUEST['age']. " years old."; exit(); } ?> " method="POST"> Name: Age:

GET and POST methods There are two ways the browser client can send information to the web server. – The GET Method – The POST Method Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. name1=value1&name2=value2&name3=value3 Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

GET vs. POST Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3,...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user. Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. $_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET? Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. GET may be used for sending non-sensitive data. Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST? Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

$_POST The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. The POST method does not have any restriction on data size to be sent. The POST method can be used to send ASCII as well as binary data. The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure. The PHP provides $_POST associative array to access all the sent information using POST method. Example <?php if( $_POST["name"] || $_POST["age"] ) { echo "Welcome ". $_POST['name']. " "; echo "You are ". $_POST['age']. " years old."; exit(); } ?> " method="POST"> Name: Age:

$_GET The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. The GET method produces a long string that appears in your server logs, in the browser's Location: box. The GET method is restricted to send upto 1024 characters only. Never use GET method if you have password or other sensitive information to be sent to the server. GET can't be used to send binary data, like images or word documents, to the server. The data sent by GET method can be accessed using QUERY_STRING environment variable. The PHP provides $_GET associative array to access all the sent information using GET method.

<?php if( $_GET["name"] || $_GET["age"] ) { echo "Welcome ". $_GET['name']. " "; echo "You are ". $_GET['age']. " years old."; exit(); } ?> " method="GET"> Name: Age:

Output: Test $GET

Forms

Form Handling- A Simple HTML Form The PHP superglobals $_GET and $_POST are used to collect form-data. An example displays a simple HTML form with two input fields and a submit button: – Name:

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this: – Welcome Your address is: The output could be something like this: – Welcome John Your address is

The same above result could also be achieved using the HTTP GET method: Example – Name:

Validate Form Data With PHP The first thing we will do is to pass all variables through PHP's htmlspecialchars() function. When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field: location.href(' - this would not be executed, because it would be saved as HTML escaped code, like this: <script>location.href(' The code is now safe to be displayed on a page or inside an . We will also do two more things when the user submits the form: Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function) Remove backslashes (\) from the user input data (with the PHP stripslashes() function) The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again). We will name the function test_input().

PHP Form Validation Example "> Name: Website: Comment: Gender: Female Male Your Input: "; echo $name; echo " "; echo $ ; echo " "; echo $website; echo " "; echo $comment; echo " "; echo $gender; ?>

Forms - Required Fields From the validation rules table on the previous slide, we see that the "Name", " ", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form. FieldValidation Rules NameRequired. + Must only contain letters and whitespace Required. + Must contain a valid address and.) WebsiteOptional. If present, it must contain a valid URL CommentOptional. Multi-line input field (textarea) GenderRequired. Must select one In the following example, added some new variables: $nameErr, $ Err, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:

Example with error fields:.error {color: #FF0000;} <?php // define variables and set to empty values $nameErr = $ Err = $genderErr = $websiteErr = ""; $name = $ = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); }

if (empty($_POST[" "])) { $ Err = " is required"; } else { $ = test_input($_POST[" "]); } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); }

if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> PHP Form Validation Example * required field. "> Name: *

* Website: Comment: Gender: Female Male * Your Input: "; echo $name;echo " ";echo $ ;echo " "; echo $website;echo " ";echo $comment; echo " ";echo $gender;?>

Validate and URL Validate Name – The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message: – $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

Validate The easiest and safest way to check whether an address is well-formed is to use PHP's filter_var() function. In the code below, if the address is not well-formed, then store an error message: $ = test_input($_POST[" "]); if (!filter_var($ , FILTER_VALIDATE_ )) { $ Err = "Invalid format"; }

Validate URL The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message: $website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[- { $websiteErr = "Invalid URL"; }

Complete Form Example To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, , and website. In the comment textarea field, we put the script between the and tags. The little script outputs the value of the $name, $ , $website, and $comment variables. Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):

Name: "> "> Website: "> Comment: Gender: value="female">Female value="male">Male