1 / 65

PHP Advanced

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!

lindsey
Download Presentation

PHP Advanced

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Advanced Code, code and more code Kyle MacLachlan

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

  3. 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”);

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

  5. 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)

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

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

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

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

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

  11. 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!

  12. require() • <html><body><?phprequire("wrongFile.php");echo "Hello World!";?></body></html> • the home page will now require the header.php file

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

  14. The difference • include() • “Throws” error and continues • require() • curls up and dies

  15. File Handling • The fopen() function is used to open files in PHP. • <html><body><?php$file=fopen("welcome.txt","r");?></body></html>

  16. fopen() modes

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

  18. Closing a File • fclose(); • <?php$file = fopen("test.txt","r");//some code to be executedfclose($file);?>

  19. End of File • feof() • file end of file • ^_^ • if (feof($file)) echo "End of file";

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

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

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

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

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

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

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

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

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

  29. 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).

  30. Cookie Syntax • Syntax • setcookie(name, value, expire, path, domain); • Example: • <?phpsetcookie("user", "Alex Porter", time()+3600);?><html>.....

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

  32. Cookie Retrieval Example • <html><body><?phpif (isset($_COOKIE["user"]))  echo "Welcome " . $_COOKIE["user"] . "!<br />";else  echo "Welcome guest!<br />";?></body></html>

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

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

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

  36. PHP sessions • Note: The session_start() function must appear BEFORE the <html> tag: • <?phpsession_start(); ?><html><body></body></html>

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

  38. Session Variable Example • <?phpsession_start();if(isset($_SESSION['views']))$_SESSION['views']=$_SESSION['views']+1;else$_SESSION['views']=1;echo "Views=". $_SESSION['views'];?>

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

  40. Email • The PHP mail() function is used to send emails from inside a script. • Syntax • mail(to,subject,message,headers,parameters)

  41. 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.";?>

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

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

  44. PHP Error handling: DIE • <?phpif(!file_exists("welcome.txt"))  {  die("File not found");  }else  {  $file=fopen("welcome.txt","r");  }?> • Error Becomes: • File not found

  45. Custom Error Handler • error_function(error_level,error_message,error_file,error_line,error_context)

  46. Error Report levels

  47. Function to Handle Errors function customError($errno, $errstr) {  echo "<b>Error:</b> [$errno] $errstr<br />";  echo "Ending Script";  die();  }

  48. Set Error Handler • Need to tell php to use your function during errors • set_error_handler("customError");

  49. Trigger an Error • Control your users • <?php$test=2;if ($test>1){trigger_error("Value must be 1 or below");}?>

  50. 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);  }?>

More Related