Download presentation
Presentation is loading. Please wait.
Published byDale Wilkinson Modified over 9 years ago
1
PHP: Beyond the Basics
2
Beyond the Basics Error Reporting Exception Handling Variable Interpolation Cookies Headers Image Manipulation Including/Organizing Code Autoloading Classes
3
Covered in Future Lectures... Databases (MySQL) Authentication and Authorization (signing in) Session Handling ("faking" state) Security
4
Error Reporting Set in php.ini Also set using the error_reporting() function Uses a series of predefined constants E_ALL, E_STRICT, E_WARNING, E_NOTICE… http://www.php.net/manual/en/errorfunc.constants.php Combine with bitwise-OR to add multiple reporting levels Recommended: E_ALL | E_STRICT
5
Error Reporting Not all errors are written to output, depending on other modules/configurations enabled on the server Check your Apache ErrorLog if you don't see any output
6
Error Reporting set_error_handler(function_name) Calls function_name any time an error is thrown Useful for generating custom error messages
7
Exception Handling Recall that Exceptions are special classes that are thrown in the event of an unexpected state in OOP Unhandled exceptions are often fatal Exceptions are handled in try...catch blocks try { } traps any potential exceptions catch (Exception $e) { } provides the opportunity to handle any exceptions in the preceeding try block
8
Exception Handling Exceptions may be thrown manually by using the throw keyword on a new Exception instance The Exception class may be subclassed to define a more specific type of exception See Lab 7 for an example of exception handling
9
Variable Interpolation: Revisited Recall that in double-quoted strings, variables will be interpolated/parsed (printed in that place in the string) Interpolation is greedy – looks for all valid variable characters A-Z a-z 0-9
10
Variable Interpolation: Revisited What if the variable has other characters? $arr['foo’] $obj->name Solution: Enclose complex variables in { } echo “My name is {$obj->name}”
11
Cookies Explained Special text files stored client-side, containing... name-value pair containing the data and expiration date the domain and path to which the cookie should be sent (must be a domain or subdomain of the originating site) When enabled, stored cookies are sent with request headers Cookies can be set via response headers or JavaScript
12
Cookie Uses Session Management (more on this later...) Personalization Tracking
13
Cookies in PHP setcookie(key, value, expiry) sets the key-value pair and the expiration date (in epoch seconds) Cookies can be unset by setting an expiration date in the past (the browser deletes out-of- date cookies) $_COOKIE contains all cookies sent by the user agent
14
Create a form that prompts the user for their name, and stores it in a cookie Add another button that allows you to destroy the cookie after creating it
15
Headers header(raw_header_text[, replace]) header('Location: http://example.com'); replace is a boolean (default: true) that dictates whether the header replaces any that may be sent by default if false, the header will simply be added Any HTTP response header may be manipulated, but only before output is sent
16
Image Manipulation Image Manipulation in PHP via the GD Library Allows for creation and modification of images in PHP Remember, as long as we can change headers, we don't have to output markup! http://us2.php.net/manual/en/ref.image.php Availability of this and other libraries can be tested by checking output of phpinfo();
17
Images with GD Create the canvas Allocate colors Draw on the canvas Set the Content-type header Output the finished image Deallocate memory
18
Image Creation imagecreate($x, $y) – create a new canvas, returns a resource specific to that canvas This resource is passed in to other function calls imagecolorallocate($img, $r, $g, $b) – creates colors to be used for future operations
19
Image Drawing imagerectangle($img, $x1, $y1, $x2, $y2, $color) draw an unfilled rectangle imagerectangle($img, $x1, $y1, $x2, $y2, $color) draw an filled rectangle imagefilledelipse($img, $x_center, $y_center, $w, $h, $color) draw a filled elipse and more...
20
Set Headers Necessary when outputting anything that's not text/html Ex: header("Content-type: image/jpeg"); Browser will now interpret this as an image
21
Output the Image imagejpeg($img[, $filename[, $quality]]) output the image as JPEG imagegif($img[, $filename]) output image as GIF imagepng($img[, $filename[, $quality]]) output image as PNG
22
Deallocate Memory imagedestroy($img) Destroys and frees all memory associated with the $img resource
23
Use PHP to output a black rectangle, containing: a red square in the upper-left a blue circle in the middle a green oval in the lower-right
24
Organizing Code Many independent PHP scripts Pros: Can develop and debug each separately Cons: Lots of duplication, consistency One PHP script Pros: All common functionality is in one place Cons: "God Script" syndrome – everything is jammed into one place
25
Organizing Code Classes can be moved into their own files Other code can be included conditionally Promotes code reuse Ideally, we use one script, and call other scripts as needed
26
include() and require() include("path/to/foo.php"); Include the contents of the file at this point in the script, if possible require("path/to/foo.php"); Include the contents here, and generate an error if not found Each file will be included and parsed as PHP dirname(__FILE__) can be used to get the full current directory if necessary
27
Inclusion Performance include_once() and require_once() are identical to include() and require(), but only load the code if not loaded already The "once" variations of these functions are orders of magnitude slower; use with care!
28
Simple Include Example <?php include('head.html'); include('body.php'); include('foot.html');
29
Other Examples Creation of modules to handle specific pieces of functionality Database functionality Function libraries Individual classes etc. Use of one script to route requests to other scripts Check $_GET for page/functionality needed Conditionally include other pages based on results Commonly used in content management systems
30
Optional PHP Tag Delimiter The closing PHP delimiter (?>) is optional, and typically not used in PHP files that are meant to be included Avoids accidental whitespace at the end of the file, which may interfere with using headers and the like
31
Autoloading __autoload($class) Global function that's called whenever trying to create an object of an undefined class Common pattern: try loading a file of the same name as the class function _autoload($class) { include($class. '.inc'); }
32
Next Up: Lab 7 Next Up: MySQL
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.