Kyle MacLachlan.  Used To Format a Date/Time  Syntax: › date(format,timestamp)  format: Required, specifies format  timestamp:Optional, specifies.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

PHP: Date() Function The PHP date() function formats a timestamp to a more readable date and time.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
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.
More on PHP Coding Lab no. 6 Advance Database Management System.
SWU, Computer systems and technologies. The Objective of This Lecture To give you a very high-level overview of some of the tools for Web Programming.
XAMPP: Cross – Apache, MySQL, Php, Perl + FileZilla, Tomcat NetBeans: IDE PHP Installation.
Intermediate PHP & MySQL
Using Session Control in PHP tMyn1 Using Session Control in PHP HTTP is a stateless protocol, which means that the protocol has no built-in way of maintaining.
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
Outline Overview about Web Page HTML Form Creation FORM Input INPUT control types GET & POST PHP File Upload PHP Include Files Headers Cookie Sessions.
Lecture 8 : PHP Errors & Exceptions UFCFR Advanced Topics in Web Development II 2014/15 SHAPE Hong Kong.
U NIT 4 F ILE U PLOAD. I. C REATE AN U PLOAD -F ILE F ORM - With PHP, it is possible to upload files to the server.To allow users to upload files from.
04/09/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Advance Database Management Systems Lab no. 5 PHP Web Pages.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
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.
INTRODUCTION TO PHP Basic concept of PHP and Much More Prepared By: Farhan Nisar(7 th Semester) University of Peshawar.
INTERNET APPLICATION DEVELOPMENT For More visit:
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
PHP3. PHP File Upload With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can.
PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures.
PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL sending.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Includes and Dates.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
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.
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.
Topics Sending an Multipart message Storing images Getting confirmation Session tracking using PHP Graphics Input Validators Cookies.
COOKIES and SESSIONS. COOKIES A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Advanced Web 2012 Lecture 6 Sean Costain Files Sean Costain 2012 Php allows for the : Creation Reading Appending Deleting Uploading And Closing.
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.
CST336, Spring 2015 Week 8: PHP File Upload. PHP provides specific functions to handle binary data such as uploading a file into the server, storing it.
PHP Error Handling & Reporting. Error Handling Never allow a default error message or error number returned by the mysql_error() and mysql_errno() functions.
PHP Error Handling Section :I Source: 1.
CHAPTER 8 PHP Advanced อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
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.
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
8 th Semester, Batch 2008 Department of Computer Science SSUET.
 A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
PHP: Beyond the Basics. Beyond the Basics Error Reporting Exception Handling Variable Interpolation Cookies Headers Image Manipulation Including/Organizing.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Martin Kruliš Who is General Failure and why is he reading my disk? by Martin Kruliš (v1.0)1.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
PHP File Handling. Opening a file Fopen(filename,mode) Closing a file Fclose(filename)
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
CHAPTER 5 SERVER SIDE SCRIPTING
Advanced PHP Lecture by Nutthapat Keawrattanapat
<?php require("header.htm"); ?>
Advanced Concepts and AJAX
PHP-II.
Presentation transcript:

Kyle MacLachlan

 Used To Format a Date/Time  Syntax: › date(format,timestamp)  format: Required, specifies format  timestamp:Optional, specifies timestamp  default is current date/time

 ARRG! Its a string! › “y/m/d”  Y -> Year4 Digits  m -> monthMonth (01 to 12)  d -> dayDay (01 to 31) › / character can be replaced with,. or –  Example: › date(“Y/m/d”);

 Code › "; echo date("Y.m.d"). " "; echo date("Y-m-d") ?>  Output › 2009/05/

 mktime() › returns the Unix timestamp for a date  the number of seconds between the Unix Epoch (January :00:00 GMT) and the time specified. › mktime(hour,minute,second,month,day,year, is_dst)

 Code ›  Output › Tomorrow is 2009/05/12

 getdate() › Returns an array that contains date and time information for a Unix timestamp  checkdate() › Validates a Gregorian date  gmdate() › Formats a GMT/UTC date/time  _date.asp

 You can insert the content of one PHP file into another PHP file before the server executes it with two functions: › include() › require()  SSI saves work › if you have multiple headers and footers or a menu file for all pages, you can have one php file to update instead of one per page

 Identical in every way except for error handling: › include()  generates a warning, but the script will continue execution › require()  generates a fatal error, and the script will stop

 Welcome to my home page! Some text.  the home page will now include the header.php file

Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 Hello World!

  the home page will now require the header.php file

Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5

 include() › “Throws” error and continues  require() › curls up and dies

 The fopen() function is used to open files in PHP. 

 This generates the message :P

 fclose(); 

 feof() › file end of file › ^_^  if (feof($file)) echo "End of file";

 fgets()  "; } fclose($file); ?>  Note: After a call to this function the file pointer moves to the next character.

  Note: After a call to this function the file pointer moves to the next character.

 Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads. › They will break your server  Create a HTML file to upload the file › Then link the php script

 Filename:  Note the upload method is POST

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

 if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { }  This Code Forces it to be an image

 if (file_exists("upload/". $_FILES["file"]["name"])) { echo $_FILES["file"]["name"]. " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/". $_FILES["file"]["name"]); echo "Stored in: ". "upload/". $_FILES["file"]["name"]; }  Saved Because once the script ends the temporary file dissapears

 0) { echo "Return Code: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; echo "Temp file: ". $_FILES["file"]["tmp_name"]. " "; if (file_exists("upload/". $_FILES["file"]["name"])) { echo $_FILES["file"]["name"]. " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/". $_FILES["file"]["name"]); echo "Stored in: ". "upload/". $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>

 A cookie is often used to identify a user.  A cookie is a small file that the server embeds on the user's computer › Each time the same computer requests a page with a browser, it will send the cookie too.  With PHP, you can both create and retrieve cookie values.

 setcookie()  Note: The setcookie() function must appear BEFORE the tag.  setcookie(name, value, expire, path, domain);  Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

 Syntax › setcookie(name, value, expire, path, domain);  Example: ›.....

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

 "; else echo "Welcome guest! "; ?>

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

 If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. › One method is to pass the data through forms

 A PHP session allows you to store user information on the server for later use (i.e. username, shopping items, etc). › However, session information is temporary and will be deleted after the user has left the website

 Note: The session_start() function must appear BEFORE the tag: 

 The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:   Output: › Pageviews=1

 If you wish to delete some session data, you can use the unset() or the session_destroy() function. › The unset() function is used to free the specified session variable:  <?php unset($_SESSION['views']); › ?>You can also completely destroy the session by calling the session_destroy() function:   Note: session_destroy() will reset your session and you will lose all your stored session data.

 The PHP mail() function is used to send s from inside a script.  Syntax › mail(to,subject,message,headers,parameters)

 <?php $to = $subject = "Test mail"; $message = "Hello! This is a simple message."; $from = $headers = "From:". $from; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>

 Subject: Message: "; } ?>

 Previous Example prone to php injection  Add The following Code: › <?php function spamcheck($field) { //filter_var() sanitizes the //address using FILTER_SANITIZE_ $field=filter_var($field, FILTER_SANITIZE_ ); //filter_var() validates the //address using FILTER_VALIDATE_ if(filter_var($field, FILTER_VALIDATE_ )) { return TRUE; } else { return FALSE; } }

  Error Becomes: › File not found

 error_function(error_level,error_message, error_file,error_line,error_context) ParameterDescription error_levelRequired. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels error_messageRequired. Specifies the error message for the user- defined error error_fileOptional. Specifies the filename in which the error occurred error_lineOptional. Specifies the line number in which the error occurred error_contextOptional. Specifies an array containing every variable, and their values, in use when the error occurred

ValueConstantDescription 2E_WARNINGNon-fatal run-time errors. Execution of the script is not halted 8E_NOTICERun-time notices. The script found something that might be an error, but could also happen when running a script normally 256E_USER_ERR OR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512E_USER_WA RNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024E_USER_NO TICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096E_RECOVER ABLE_ERRO R Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191E_ALLAll errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

function customError($errno, $errstr) { echo " Error: [$errno] $errstr "; echo "Ending Script"; die(); }

 Need to tell php to use your function during errors  set_error_handler("customError");

 Control your users  1) { trigger_error("Value must be 1 or below"); } ?>

 Error: [$errno] $errstr "; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>

 Error: [$errno] $errstr "; echo "Webmaster has been notified"; error_log("Error: [$errno] $errstr",1, } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>  Output is mail and an Error Message

 Try/Catch:  1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } //catch exception catch(Exception $e) { echo 'Message: '.$e->getMessage(); } ?>

 Custom Exception Handling › class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': '.$this->getMessage().' is not a valid address'; return $errorMsg; } }

 try { //check if if(filter_var($ , FILTER_VALIDATE_ ) === FALSE) { //throw exception if is not valid throw new customException($ ); } //check for "example" in mail address if(strpos($ , "example") !== FALSE) { throw new Exception("$ is an example "); } } catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); }

 Catch statements can re-throw exceptions, for example: › catch(Exception $e) { //re-throw exception throw new customException($ ); } } catch (customException $e) { //display custom message echo $e->errorMessage(); }

 The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions. › Exception: ", $exception- >getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>

 Used to validate and filter data from insecure sources. › filter_var() - Filters a single variable with a specified filter › filter_var_array() - Filter several variables with the same or different filters › filter_input - Get one input variable and filter it › filter_input_array - Get several input variables and filter them with the same or different filters

 Validating filters: › Are used to validate user input › Strict format rules (like URL or validating) › Returns the expected type on success or FALSE on failure  Sanitizing filters: › Are used to allow or disallow specified characters in a string › No data format rules › Always return the string

 A Good Example  array ( "min_range"=>0, "max_range"=>256 ) ); if(!filter_var($var, FILTER_VALIDATE_INT, $int_options)) { echo("Integer is not valid"); } else { echo("Integer is valid"); } ?>

 array ( "filter"=>FILTER_SANITIZE_STRING ), "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array ( "min_range"=>1, "max_range"=>120 ) ), " "=> FILTER_VALIDATE_ , ); $result = filter_input_array(INPUT_GET, $filters); if (!$result["age"]) { echo("Age must be a number between 1 and 120. "); } elseif(!$result[" "]) { echo(" is not valid. "); } else { echo("User input is valid"); } ?>

 "convertSpace")); ?>  Output: › Peter is a great guy!

 I Highly recommend working through the website as it provides the opportunity of working at your own pace  Thanks