PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling...

47
PHP Advance

Transcript of PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling...

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

PHP

Advance

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

Agenda

• Server side Includes

• File Handling

• Cookies

• Sessions

• Error/Exception handling

• Database handling with MySQL

• E-mail sending

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

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.

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

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

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

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<op>,c

ontext<op>) - is used to open files in PHP.

<?php $file=fopen("welcome.txt","r");

?>

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

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

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

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);

?>

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

File Handling• File opening modes,

Modes Description

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

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

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);

?>

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

File Handling

• File handling functions,– fwrite(file,string,length<op>) - writes to an open file.– rename(oldname,newname,context<op>) -

renames a file or directory.– readfile(filename,include_path,context) - reads a

file and writes it to the output buffer. – fputs(file,string,length<op>) - 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

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

File Handling

• Upload-File Form<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>

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

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[<file_name>]["name"] - the name of the uploaded file

• $_FILES[<file_name>]["type"] - the type of the uploaded file

• $_FILES[<file_name>]["size"] - the size in bytes of the uploaded file

• $_FILES[<file_name>]["tmp_name"] - the name of the temporary copy of the file stored on the server

• $_FILES[<file_name>]["error"] - the error code resulting from the file upload

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

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

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

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.

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

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 <html> 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);

?> <html> <body> </body> </html>

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

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 cookieecho $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE);

?>

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

Cookies

• In the following example uses the isset() function to find out if a cookie has been set:

<html> <body>

<?php if (isset($_COOKIE["user"]))

echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?>

</body> </html>

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

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 agosetcookie("user", "", time()-3600);

?>

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

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.

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

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.

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

Sessions

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

Sessions

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

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

Sessions

• Storing a Session Variable– To store and retrieve session variables is to

use the PHP $_SESSION variable.

<?php session_start();

?> <html> <body> </body> </html>

<?phpsession_start(); if(isset($_SESSION['views']))

$_SESSION['views']=$_SESSION['views']+1;else

$_SESSION['views']=1;echo "Views=". $_SESSION['views'];

?>

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

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']); ?>

<?phpsession_destroy();

?>

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

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

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

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 "<b>End of the script</b>";

?>

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

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

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<op>,error_line<op>,error_context<op>)

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

Error/Exception handling

Parameter Description

error_level Specifies the error report level for the user-defined error

error_message Specifies the error message for the user-defined error

error_file Specifies the filename in which the error occurred

error_line Specifies the line number in which the error occurred

error_context Specifies an array containing every variable, and their values, in use when the error occurred

• Parameter Description

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

Error/Exception handling

Value Constant Description

2 E_WARNING Non-fatal run-time errors

8 E_NOTICE Run-time notices

256 E_USER_ERROR Fatal user-generated error

512 E_USER_WARNING Non-fatal user-generated warning.

1024 E_USER_NOTICE User-generated notice.

4096 E_RECOVERABLE_ERROR Catchable fatal error.

8191 E_ALL All errors and warnings,

• Error Report levels

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

Error/Exception handling

• A simple error handling function <?php function customErrorHandler($ERROR_NO,$ERROR_MEG){ echo "Error no is : $ERROR_NO <br/>"; echo "Error message is : $ERROR_MEG <br/>"; }?>

• 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");

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

Error/Exception handling

• Example<?php function customErrorHandler($ERROR_NO,$ERROR_MEG){ echo "Error no is : $ERROR_NO <br/>"; echo "Error message is : $ERROR_MEG <br/>s"; } set_error_handler("customErrorHandler"); echo $name; // Error statement echo "<b>End of the script</b>";?>

• Output is,Error no is : 8 Error message is : Undefined variable: name End of the script

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

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

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

Error/Exception handling

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

• Output is,Error no is : 512 Error message is : Invalid language name End of the script

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

Error/Exception handling

• Error reporting– By using the error_log() function you can

send error logs to a specified file or a remote destination.

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

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.

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

Error/Exception handling• Try, throw and catch<?php

//create function with an exceptionfunction checkNum($number){

if($number>1){throw new Exception("Value must be 1 or below");

} return true; }

//trigger exception in a "try" blocktry {

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 exceptioncatch(Exception $e){

echo 'Message: ' .$e->getMessage(); }?>

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

Error/Exception handling• Multiple Exceptions with custom exception

class<?phpclass customException extends Exception{

public function errorMessage(){//error message$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';return $errorMsg;

}}

$email = "[email protected]";

try {//check if

if(!isset($email)){ //throw exception if email is not valid throw new customException($email); }

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

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

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

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

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

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

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

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)

Parameter Description

servername Specifies the server to connect to. Default value is "localhost:3306"

username Specifies the username to log in with. Default value is the name of the user that owns the server process

password Specifies the password to log in with. Default is ""

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

Database handling with MySQL

• Closing a Connection

<?php// Create an connection$con = mysql_connect("localhost","peter","abc123");

// Check the connection is nullif (!$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 codemysql_close($con);

?>

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

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 databaseif (mysql_query("CREATE DATABASE my_db",$con)) {

echo "Database created"; }

else { echo "Error creating database: " . mysql_error(); }

// Create table in my_db databasemysql_select_db("my_db", $con);$sql = "CREATE TABLE person(FirstName varchar(15),LastName varchar(15),

Age int)";mysql_query($sql,$con);mysql_close($con);

?>

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

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 "<br />"; }

mysql_close($con);?>

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

Database handling with MySQL• Insert, Update and Delete query – DMLs// Select a databasemysql_select_db("my_db", $con);

– Insert query// Insert a recordmysql_query ("INSERT INTO person (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')");

– Update query// Update a recordmysql_query ("UPDATE Person SET Age = '36'WHERE FirstName = 'Peter' AND LastName = 'Griffin'");

– Delete query// Delete a recordmysql_query ("DELETE FROM Person WHERE LastName='Griffin'");

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

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<op>) - 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<op>) - executes a query on a

MySQL database. – mysql_select_db(database,connection<op>) - sets the active

MySQL database.

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

E-mail sending

• mail()– The PHP mail() function is used to send

emails from inside a script. – mail(to,subject,message,headers<op>,para

meters<op>) <?php

$to = "[email protected]";$subject = "Test mail";$message = "Hello! This is a simple email message.";$from = "[email protected]";$headers = "From: $from";

mail($to,$subject,$message,$headers);

echo "Mail Sent.";?>