Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL E-mail sending.

Similar presentations


Presentation on theme: "PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL E-mail sending."— Presentation transcript:

1 PHP Advance

2 Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL E-mail sending

3 Server side Includes include() –Takes all the text in a specified file and copies it into the file that uses the include function –The include() function generates a warning (but the script will continue execution) You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages.

4 Server side Includes require() –The require() function is identical to include(), except that it handles errors differently. –The require() function generates a fatal error (and the script execution will stop after the error).

5 File Handling Three Steps, 1.Open a File 2.Read/write the File 3.Close the File Open a File –fopen(filename,mode,include_path,c ontext ) - is used to open files in PHP. <?php $file=fopen("welcome.txt","r"); ?>

6 File Handling Read/write the File –The feof() function checks if the "end-of-file" (EOF) has been reached (You cannot read from files opened in w, a, and x mode). –The fgets() function is used to read a single line from a file (After a call to this function the file pointer has moved to the next line). –The fgetc() function is used to read a single character from a file (After a call to this function the file pointer moves to the next character).

7 File Handling Close the File –fclose(file) - is used to close an open file. <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>

8 File Handling File opening modes, ModesDescription r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist a+ Read/Append. Preserves file content by writing to the end of the file x Write only. Creates a new file. Returns FALSE and an error if file already exists x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

9 File Handling If the fopen() function is unable to open the specified file, it returns 0 (false). <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>

10 File Handling File handling functions, –fwrite(file,string,length ) - writes to an open file. –rename(oldname,newname,context ) - renames a file or directory. –readfile(filename,include_path,context) - reads a file and writes it to the output buffer. –fputs(file,string,length ) - writes to an open file. –filesize(filename) - returns the size of the specified file. –file_exists(path) - checks whether or not a file or directory exists. –copy(file,to_file) - copies a file. –move_uploaded_file(file,newloc) - moves an uploaded file to a new location

11 File Handling Upload-File Form <form action="upload_file.php" method="post" enctype="multipart/form-data"> Filename:

12 File Handling Server side upload script –By using the global PHP $_FILES array you can upload files from a client computer to the remote server. $_FILES[ ]["name"] - the name of the uploaded file $_FILES[ ]["type"] - the type of the uploaded file $_FILES[ ]["size"] - the size in bytes of the uploaded file $_FILES[ ]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES[ ]["error"] - the error code resulting from the file upload

13 File Handling <?php if (($_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"]. " "; } 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"; } ?>

14 Cookies What is a Cookie? –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.

15 Cookies How to Create a Cookie? –setcookie(name,value,expire,path,domain) is used to set a cookie. –Note: The setcookie() function must appear BEFORE the tag. –Create a cookie named "user" and assign the value "Alex Porter" to it and also specify that the cookie should expire after one hour: <?php setcookie("user", "Alex Porter", time()+3600); ?>

16 Cookies How to Retrieve a Cookie Value? –The PHP $_COOKIE variable is used to retrieve a cookie value. –In the example below, retrieves the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>

17 Cookies In the following example uses the isset() function to find out if a cookie has been set: <?php if (isset($_COOKIE["user"])) echo "Welcome ". $_COOKIE["user"]. "! "; else echo "Welcome guest! "; ?>

18 Cookies How to Delete a Cookie? –When deleting a cookie you should assure that the expiration date is in the past. <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>

19 Cookies Disadvantages of Cookies –Size and number of cookies stored are limited. –It stored as plain-text in a specific directory, everyone can view and modify them. Personal information is exposed. –It won't work if the security level set too high in browser.

20 Sessions The HTTP address doesn't maintain user state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). Session information is temporary and will be deleted after the user has left the website. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.

21 Sessions

22 Steps, –Starting a PHP Session –Storing a Session Variable –Destroying a Session Starting a PHP Session –Before you can store user information in your PHP session, you must first start up the session. –The session_start() function must appear BEFORE the tag: –session_start() function will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

23 Sessions Storing a Session Variable –To store and retrieve session variables is to use the PHP $_SESSION variable. <?php session_start(); ?>

24 Sessions Destroying a Session –unset(session_key) - is used to free the specified session variable –You can also completely destroy the session by calling the session_destroy() function <?php unset($_SESSION['views']); ?> <?php session_destroy(); ?>

25 Error/Exception handling Error Handling –The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. –The most common error checking methods in PHP, Simple "die()" statements Custom errors and error triggers Error reporting

26 Error/Exception handling Simple "die()" statements <?php $fileName = "hello.txt"; if(!file_exists($fileName)){ die("No Such a file named $fileName"); } else{ $file = fopen($fileName); } echo " End of the script "; ?> If the file does not exist you get an error like this: No Such a file named hello.txt Doesn’t execute rest of the script, when we call die().

27 Error/Exception handling Custom errors and error triggers –We can create a special function that can be called when an error occurs in PHP. –error_function(error_level,error_message, error_file,error_line,error_contex t )

28 Error/Exception handling ParameterDescription error_levelSpecifies the error report level for the user-defined error error_messageSpecifies the error message for the user-defined error error_fileSpecifies the filename in which the error occurred error_lineSpecifies the line number in which the error occurred error_contextSpecifies an array containing every variable, and their values, in use when the error occurred Parameter Description

29 Error/Exception handling ValueConstantDescription 2E_WARNING Non-fatal run-time errors 8E_NOTICERun-time notices 256E_USER_ERRORFatal user-generated error 512E_USER_WARNINGNon-fatal user-generated warning. 1024E_USER_NOTICEUser-generated notice. 4096E_RECOVERABLE_ERRORCatchable fatal error. 8191E_ALLAll errors and warnings, Error Report levels

30 Error/Exception handling A simple error handling function <?php function customErrorHandler($ERROR_NO,$ERROR_MEG){ echo "Error no is : $ERROR_NO "; echo "Error message is : $ERROR_MEG "; } ?> Set Error Handler –We are going to make the function above the default error handler for the duration of the script. –set_error_handler(" customErrorHandler ");

31 Error/Exception handling Example <?php function customErrorHandler($ERROR_NO,$ERROR_MEG){ echo "Error no is : $ERROR_NO "; echo "Error message is : $ERROR_MEG s"; } set_error_handler("customErrorHandler"); echo $name; // Error statement echo " End of the script "; ?> Output is, Error no is : 8 Error message is : Undefined variable: name End of the script

32 Error/Exception handling Trigger an Error –In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function. –By adding a second parameter, you can specify what error level is triggered. –Possible error types are, E_USER_ERROR E_USER_WARNING E_USER_NOTICE

33 Error/Exception handling Example <?php function customErrorHandler($ERROR_NO,$ERROR_MEG,){ echo "Error no is : $ERROR_NO "; echo "Error message is : $ERROR_MEG "; } set_error_handler("customErrorHandler"); $x = "HPH"; if($x!="PHP"){ trigger_error("Invalid language name",E_USER_WARNING); } echo " End of the script "; ?> Output is, Error no is : 512 Error message is : Invalid language name End of the script

34 Error/Exception handling Error reporting –By using the error_log() function you can send error logs to a specified file or a remote destination.

35 Error/Exception handling Exception Handling –With PHP 5 came a new object oriented way of dealing with errors. –Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

36 Error/Exception handling Try, throw and catch <?php //create function with an exception function checkNum($number){ if($number>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(); } ?>

37 Error/Exception handling Multiple Exceptions with custom exception class <?php class customException extends Exception{ public function errorMessage(){ //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': '.$this->getMessage().' is not a valid E-Mail address'; return $errorMsg; } $email = "someone@example.com"; try { //check if if(!isset($email)){ //throw exception if email is not valid throw new customException($email); }

38 Error/Exception handling //check for "example" in mail address if(strpos($email, "example") !== FALSE){ throw new Exception("$email is an example e-mail"); } catch (customException $e){ echo $e->errorMessage(); } catch(Exception $e){ echo $e->getMessage(); } ?>

39 Error/Exception handling Re-throwing Exceptions –When an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block. Rules for exceptions –Code may be surrounded in a try block, to help catch potential exceptions –Each try block or "throw" must have at least one corresponding catch block –Multiple catch blocks can be used to catch different classes of exceptions –Exceptions can be thrown (or re-thrown) in a catch block within a try block

40 Database handling with MySQL The MySQL Database is very often used with PHP. MySQL is the most popular open source database server. Basic steps to working with any database, –Create a database connection –Open the connection –Execute SQL (DDL/DML) statements –Close the connection

41 Database handling with MySQL Connecting to a MySQL Database –Before you can access and work with data in a database, you must create a connection to the database. –mysql_connect ( servername, username, password) ParameterDescription servernameSpecifies the server to connect to. Default value is "localhost:3306" usernameSpecifies the username to log in with. Default value is the name of the user that owns the server process passwordSpecifies the password to log in with. Default is ""

42 Database handling with MySQL Closing a Connection <?php // Create an connection $con = mysql_connect("localhost","peter","abc123"); // Check the connection is null if (!$con) { die('Could not connect: '. mysql_error()); } // some code ?> <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: '. mysql_error()); } // some code mysql_close($con); ?>

43 Database handling with MySQL Create Database and Tables - DDLs <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: '. mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: ". mysql_error(); } // Create table in my_db database mysql_select_db("my_db", $con); $sql = "CREATE TABLE person(FirstName varchar(15),LastName varchar(15), Age int)"; mysql_query($sql,$con); mysql_close($con); ?>

44 Database handling with MySQL Select query - DMLs <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: '. mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']. " ". $row['LastName']; echo " "; } mysql_close($con); ?>

45 Database handling with MySQL Insert, Update and Delete query – DMLs // Select a database mysql_select_db("my_db", $con); –Insert query // Insert a record mysql_query ("INSERT INTO person (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); –Update query // Update a record mysql_query ("UPDATE Person SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); –Delete query // Delete a record mysql_query ("DELETE FROM Person WHERE LastName='Griffin'");

46 Database handling with MySQL Function summary –mysql_connect(server,user,pwd,newlink,clientflag) - opens a non-persistent MySQL connection. –mysql_close(connection) - closes a non-persistent MySQL connection. –mysql_error(connection) - returns the error description of the last MySQL operation. –mysql_fetch_array(data,array_type ) - returns a row from a recordset as an associative array and/or a numeric array. –mysql_fetch_row(data) - returns a row from a recordset as a numeric array. –mysql_query(query,connection ) - executes a query on a MySQL database. –mysql_select_db(database,connection ) - sets the active MySQL database.

47 E-mail sending mail() –The PHP mail() function is used to send emails from inside a script. –mail(to,subject,message,headers,par ameters ) <?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."; ?>


Download ppt "PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL E-mail sending."

Similar presentations


Ads by Google