650 likes | 824 Views
PHP Advanced. Code, code and more code . Kyle MacLachlan. Date Function. Used To Format a Date/Time Syntax: date( format , timestamp ) format: Required, specifies format timestamp: Optional, specifies timestamp default is current date/time. Formatting the Date. ARRG! Its a string!
E N D
PHP Advanced Code, code and more code Kyle MacLachlan
Date Function • Used To Format a Date/Time • Syntax: • date(format,timestamp) • format: Required, specifies format • timestamp: Optional, specifies timestamp • default is current date/time
Formatting the Date • ARRG! Its a string! • “y/m/d” • Y -> Year 4 Digits • m -> month Month (01 to 12) • d -> day Day (01 to 31) • / character can be replaced with , . or – • Example: • date(“Y/m/d”);
Examples of Date format • Code • <?phpecho date("Y/m/d") . "<br />";echo date("Y.m.d") . "<br />";echo date("Y-m-d")?> • Output • 2009/05/112009.05.112009-05-11
The date and timestamp • mktime() • returns the Unix timestamp for a date • the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. • mktime(hour,minute,second,month,day,year,is_dst)
Timestamp Example • Code • <?php$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));echo "Tomorrow is ".date("Y/m/d", $tomorrow);?> • Output • Tomorrow is 2009/05/12
Some More on yummy Dates: • 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 • http://www.w3schools.com/php/php_ref_date.asp
Server Side Includes (SSI) • 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
include() and require() • 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
include() • <html><body><?php include("wrongFile.php"); ?><h1>Welcome to my home page!</h1><p>Some text.</p></body></html> • the home page will now include the header.php file
include error Warning: include(wrongFile.php) [function.include]:failed to open stream:No such file or directory in C:\home\website\test.php on line 5Warning: include() [function.include]:Failed opening 'wrongFile.php' for inclusion(include_path='.;C:\php5\pear')in C:\home\website\test.php on line 5Hello World!
require() • <html><body><?phprequire("wrongFile.php");echo "Hello World!";?></body></html> • the home page will now require the header.php file
require error Warning: require(wrongFile.php) [function.require]:failed to open stream:No such file or directory in C:\home\website\test.php on line 5Fatal error: require() [function.require]:Failed opening required 'wrongFile.php'(include_path='.;C:\php5\pear')in C:\home\website\test.php on line 5
The difference • include() • “Throws” error and continues • require() • curls up and dies
File Handling • The fopen() function is used to open files in PHP. • <html><body><?php$file=fopen("welcome.txt","r");?></body></html>
fopen() generate error message • <html><body><?php$file=fopen("welcome.txt","r") or exit("Unable to open file!");?></body></html> • This generates the message :P
Closing a File • fclose(); • <?php$file = fopen("test.txt","r");//some code to be executedfclose($file);?>
End of File • feof() • file end of file • ^_^ • if (feof($file)) echo "End of file";
Reading a File Line by Line • fgets() • <?php$file = fopen("welcome.txt", "r") or exit("Unable to open file!");//Output a line of the file until the end is reachedwhile(!feof($file)) { echo fgets($file). "<br />"; }fclose($file);?> • Note: After a call to this function the file pointer moves to the next character.
Reading a File Character by Character • <?php$file=fopen("welcome.txt","r") or exit("Unable to open file!");while (!feof($file)) { echo fgetc($file); }fclose($file);?> • Note: After a call to this function the file pointer moves to the next character.
Upload Files • 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
HTML Section • <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> • Note the upload method is POST
PHP Upload Script • <?phpif ($_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 • 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
Saving The File • 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
Putting it all together • <?phpif ((($_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 "Return Code: " . $_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 "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; 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"; }?>
Cookies • A cookie is often used toidentify 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.
Creating Cookies • setcookie() • Note: The setcookie() function must appear BEFORE the <html> 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).
Cookie Syntax • Syntax • setcookie(name, value, expire, path, domain); • Example: • <?phpsetcookie("user", "Alex Porter", time()+3600);?><html>.....
Retrieve Cookies • The PHP $_COOKIE variable is used to retrieve a cookie value. • <?php// Print a cookieecho $_COOKIE["user"];// A way to view all cookiesprint_r($_COOKIE);?>
Cookie Retrieval Example • <html><body><?phpif (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />";else echo "Welcome guest!<br />";?></body></html>
Delete Cookies • When deleting a cookie you should assure that the expiration date is in the past. • <?php// set the expiration date to one hour agosetcookie("user", "", time()-3600);?>
What if a Browser Does NOT Support Cookies? • 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
PHP Sessions • 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
PHP sessions • Note: The session_start() function must appear BEFORE the <html> tag: • <?phpsession_start(); ?><html><body></body></html>
Storing a Session Variable • The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: • <?phpsession_start();// store session data$_SESSION['views']=1;?><html><body><?php//retrieve session dataecho "Pageviews=". $_SESSION['views'];?></body></html> • Output: • Pageviews=1
Session Variable Example • <?phpsession_start();if(isset($_SESSION['views']))$_SESSION['views']=$_SESSION['views']+1;else$_SESSION['views']=1;echo "Views=". $_SESSION['views'];?>
Destroying a Session • 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: • <?phpunset($_SESSION['views']); • ?>You can also completely destroy the session by calling the session_destroy() function: • <?phpsession_destroy();?> • Note:session_destroy() will reset your session and you will lose all your stored session data.
Email • The PHP mail() function is used to send emails from inside a script. • Syntax • mail(to,subject,message,headers,parameters)
A Simple Email Example • <?php$to = "someone@example.com";$subject = "Test mail";$message = "Hello! This is a simple email message.";$from = "someonelse@example.com";$headers = "From:" . $from; mail($to,$subject,$message,$headers);echo "Mail Sent.";?>
PHP Mail Form • <html><body><?phpif (isset($_REQUEST['email']))//if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("someone@example.com", "$subject", $message, "From:" . $email); echo "Thank you for using our mail form"; }else//if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br /> Subject: <input name='subject' type='text' /><br /> Message:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>"; }?></body></html>
Secure Emails • Previous Example prone to php injection • Add The following Code: • <html><body><?phpfunction spamcheck($field) { //filter_var() sanitizes the e-mail //address using FILTER_SANITIZE_EMAIL $field=filter_var($field, FILTER_SANITIZE_EMAIL); //filter_var() validates the e-mail //address using FILTER_VALIDATE_EMAIL if(filter_var($field, FILTER_VALIDATE_EMAIL)) { return TRUE; } else { return FALSE; } }
PHP Error handling: DIE • <?phpif(!file_exists("welcome.txt")) { die("File not found"); }else { $file=fopen("welcome.txt","r"); }?> • Error Becomes: • File not found
Custom Error Handler • error_function(error_level,error_message,error_file,error_line,error_context)
Function to Handle Errors function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); }
Set Error Handler • Need to tell php to use your function during errors • set_error_handler("customError");
Trigger an Error • Control your users • <?php$test=2;if ($test>1){trigger_error("Value must be 1 or below");}?>
Trigger an Error Example • <?php//error handler functionfunction customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); }//set error handlerset_error_handler("customError",E_USER_WARNING);//trigger error$test=2;if ($test>1) {trigger_error("Value must be 1 or below",E_USER_WARNING); }?>