PHP Hypertext Preprocessor PHP is a server side

  • Slides: 70
Download presentation
PHP — Hypertext Preprocessor PHP is a server side scripting language. – Capable of

PHP — Hypertext Preprocessor PHP is a server side scripting language. – Capable of generating the HTML pages • HTML generates the web page with the static text and images. • However the need evolved for dynamic web based application, mostly involving database usage. PHP involves simplicity in scripting (. . generally using the database) platform independence. • PHP is primarily designed for web applications well optimized for the response times needed for web applications

PHP programs are written using a text editor, such as Notepad or Word. Pad,

PHP programs are written using a text editor, such as Notepad or Word. Pad, just like HTML pages. �PHP pages, for the most part, end in a. php extension. This extension signifies to the server that it needs to parse the PHP code before sending the resulting HTML code to the viewer’s Web browser. PHP is denoted in the page with opening and closing tags as follows:

Data Type • PHP is an untyped language – variables type can change on

Data Type • PHP is an untyped language – variables type can change on the fly. • Four basic data types: • More data types 1. Integer 2. Double 3. String 4. Boolean 1. Array 2. Object Variables • The variables in PHP are declared by appending the $ sign to the variable name. – For e. g $company = “NCST”; $sum = 10. 0; • Variable’s data type is changed by the value that is assigned to the variable. • Type casting allows to change the data type explicitly.

Super Globals $_SERVER: The $_SERVER super global contains information created by the Web server

Super Globals $_SERVER: The $_SERVER super global contains information created by the Web server and offers a bevy of information regarding the server and client configuration and the current request environment. $_GET & $_POST: The $_GET and $_POST super globals are used to retrieve information from forms, like user input. $_COOKIE: The $_COOKIE super global stores information passed into the script through HTTP cookies $_ENV: The $_ENV super global offers information regarding the PHP parser’s underlying server environment. $_SESSION: The $_SESSION super global contains information regarding all session variables $_FILES: The $_FILES super global contains information regarding data uploaded to the server via the POST method. This super global is a tad different from the others

PHP Form Handling HTML Code (Form. html) PHP Code (form. php)

PHP Form Handling HTML Code (Form. html) PHP Code (form. php)

PHP Form Handling

PHP Form Handling

Exception Handling PHP 1. The application attempts something. 2. If the attempt fails, the

Exception Handling PHP 1. The application attempts something. 2. If the attempt fails, the exception-handling feature throws an exception. 3. The assigned handler catches the exception and performs any necessary tasks. 4. The exception-handling feature cleans up any resources consumed during the attempt. In PHP, Exception handling can be done by try …throw… catch. Exception handling syntax:

Files �Organizing related data into entities commonly referred to as files. �To create a

Files �Organizing related data into entities commonly referred to as files. �To create a file we use fopen Function. The fopen function needs two important pieces of information to operate correctly. �First parameter requires file name to open. �Second parameter indicates the mode in which the file has to be opened.

Files Some modes are

Files Some modes are

Some File Functions 1) fopen(filename, mode) - used for opening a file with specific

Some File Functions 1) fopen(filename, mode) - used for opening a file with specific mode. 2) fclose(fp) - used to close the file. (fp -> filepointer) 3) feof(fp) - used to find the End of File 4) fgetc(fp) - Gets character from file pointer 5) fgets(fp) - Gets a line from file pointer 6) fread(fp, size) - Binary-safe file read 7) fscanf(fp, format) - Parses input from a file according to a format 8) fwrite(fp, string) - Binary-safe file write 9) file_put_contents(fp, string) - Write a string to a file 10) file_get_contents(fp) - Reads entire file into a string 11) file(fp) - Reads entire file into an array 12) file_exists(fp) - Checks whether a file or directory exists

13)is_readable(fp) - Tells whether the filename is readable 14) is_writable(fp) - Tells whether the

13)is_readable(fp) - Tells whether the filename is readable 14) is_writable(fp) - Tells whether the filename is writable 15) is_file(path) - Tells whether the filename is a regular file 16) is_dir(path) - Tells whether the filename is a directory 17) is_link(path) - Tells whether the filename is a symbolic link 18) readlink(path) - Returns the target of a symbolic link 19) readdir - Read entry from directory handle 20) glob - Find pathnames matching a pattern 21) filesize(fp) - Gets file size 22) filetype(fp) - Gets file type 23) fprintf(fp, format) - Write a formatted string to a stream 24) fstat(fp) - Gets information about a file using an open file pointer

Verifying a Username and Password Private website Only accessible to certain individuals Encrypt username

Verifying a Username and Password Private website Only accessible to certain individuals Encrypt username and password data when sending, storing and retrieving for increased security Implementing password checking Login information stored in file fopen function Read, write, append modes Store data using fputs n newline character Close files when done fclose function

Implementing password checking, cont. Trim newline character chop function Split string into substrings given

Implementing password checking, cont. Trim newline character chop function Split string into substrings given a certain delimiter split function If username/password match list, allow access

Form data is posted to password. php.

Form data is posted to password. php.

Variable names, when preceded by the logical negation operator (!), return true if they

Variable names, when preceded by the logical negation operator (!), return true if they are empty or set to 0. This checks if a user has submitted a form without specifying a username or password. Function fields. Blank is called if the user has submittedisset an incomplete formthe to user notify the Function tests whether has user thatthe all. New form. User fields mustindicating be completed. pressed button, that a new user must be added. To add a new user, we open the file password. txt in append mode and assign the file handle that is returned to variable $file.

Print an error message and terminate script execution if the file cannot be opened.

Print an error message and terminate script execution if the file cannot be opened. Function user. Added is called to print a message Function fputs writes the name and password to to the user to indicate that the username and the text file. . password were added to the file.

Before entering the while loop, variable Function fgets reads a is line $user. Verified

Before entering the while loop, variable Function fgets reads a is line $user. Verified setfrom to 0. the text file. The result is assigned to variable $line. The while loop executes asremoves long as the are character Function chop there newline more lines infrom the file andline. variable the to endread of the Function split is called to separate the string at $user. Verified is still 0 or empty. the specified delimiter (in this case, a comma). The username entered by the$field user is. tested The resulting array is stored in array against the one returned in the text file (stored in the first element of the array). If they match, variable $user. Verified is set to 1. If function check. Password returns true, function access. Granted is called to notify the client that permission has been granted. Otherwise, function wrong. Password is called. Function check. Password is called to verify the user’s password. Variable $PASSWORD and array $field are passed to the function.

If variable $user. Verified has not been set loop has executed, function to a

If variable $user. Verified has not been set loop has executed, function to a value After other the thanwhile 0, function fclose is called to close the file. access. Denied is called to notify the client that access has been denied. Function check. Password compares the user’s password to the password in the file. If they match, true is returned, whereas false is returned if they do not.

Function user. Added prints a message to the client indicating that the user has

Function user. Added prints a message to the client indicating that the user has been added. Function access. Granted prints a message to the client indicating that permission has been granted.

Function wrong. Password prints a message to the client indicating that the password is

Function wrong. Password prints a message to the client indicating that the password is invalid. Function access. Denied prints a message to the client indicating that access has been denied.

Function fields. Blank prints a message to the client indicating that all form fields

Function fields. Blank prints a message to the client indicating that all form fields have not been completed.

password. txt

password. txt

PHP My. SQL Introduction The My. SQL functions allows you to access My. SQL

PHP My. SQL Introduction The My. SQL functions allows you to access My. SQL database servers.

Connecting to a Databases Store and maintain data My. SQL is a free database

Connecting to a Databases Store and maintain data My. SQL is a free database product PHP supports many database operations Access databases from Web pages

Select box containing options for a SELECT query

Select box containing options for a SELECT query

Form to query a My. SQL database

Form to query a My. SQL database

Interacting with databases SQL Structured Query Language Used to manipulate databases Several useful functions

Interacting with databases SQL Structured Query Language Used to manipulate databases Several useful functions mysql_connect mysql_select_db mysql_query mysql_error mysql_fetch_row mysql_close

Basic My. SQL PHP functions mysql_connect() – creates a connection mysql_close() – closes the

Basic My. SQL PHP functions mysql_connect() – creates a connection mysql_close() – closes the connection mysql_select_db() – selects the database mysql_query() – Executes My. SQL queries mysql_error() – returns the error mysql_errorno() – returns the error number of the last mysql process mysql_num_rows() – Retrieves the number of rows from a result set. mysql_num_fields () - Retrieves the number of fields from a query. mysql_affected_rows() – returns the no. of affected rows

mysql_fetch_row () - returns a numerical array that corresponds to the fetched row. Returns

mysql_fetch_row () - returns a numerical array that corresponds to the fetched row. Returns FALSE if there are no more rows. mysql_fetch_array() - returns a row from a recordset as an associative array / numeric array. mysql_fetch_assoc() - returns a row from a recordset as an associative array. mysql_fetch_field() - returns an object containing information of a field from a recordset. get_resource_type () - gets the type of the given resource(not mysql function) mysql_get_client_info() returns a string that represents the client library version. mysql_get_server_info() - Retrieves the My. SQL server version. mysql_pconnect() — Open a persistent connection to a My. SQL server mysql_free_result() — Free result memory mysql_list_dbs() — Lists all databases

Build the select query and assign the string to variable $query. Function mysql_connect returns

Build the select query and assign the string to variable $query. Function mysql_connect returns a database handle which represents PHP’s connection to a database. If this connection is not made, function die is called to terminate script execution.

Function mysql_query returns an object containing the result set of the query, which we

Function mysql_query returns an object containing the result set of the query, which we assign to variable $result. Function mysql_select_db is called to specify the database to be queried. The for loop iterates through each record in the result set while constructing an XHTML table from the results. Variable $counter is incremented by one Function mysql_fetch_row returns for each rowanretrieved. array containing the elements of each row in the result set of our query ($result).

The foreach loop iterates through the array containing the elements of each row of

The foreach loop iterates through the array containing the elements of each row of and printsare outprinted each element in an The total number results to the client. individual table cell.

Querying a database and displaying the results

Querying a database and displaying the results

My. SQL - Connect Create Connection: Before can access data in a database, must

My. SQL - Connect Create Connection: Before can access data in a database, must create a connection to the database. In PHP, this is done with the mysql_connect() function. mysql_connect(servername, username, password);

My SQL - Close Connection: The connection will be closed automatically when the script

My SQL - Close Connection: The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: mysql_close($con);

My SQL – Select DB Database selection can be done by this function. mysql_select_db($dbname,

My SQL – Select DB Database selection can be done by this function. mysql_select_db($dbname, $con);

My SQL – Query E. g: Create DB <? php mysql_connect("localhost", "root", “admin") or

My SQL – Query E. g: Create DB <? php mysql_connect("localhost", "root", “admin") or die(mysql_error()); if (mysql_query(" CREATE DATABASE sample if not exists", $con)) echo "Database created"; else echo "Error creating database: ". mysql_error(); mysql_close($con); ? > All DDL & DML queries can be executed by this function. mysql_query($query, $con);

My SQL – get_client_info mysql_get_client_info() returns a string that represents the client library version.

My SQL – get_client_info mysql_get_client_info() returns a string that represents the client library version. mysql_get_client_info();

mysql_get_server_info() returns a string that represents the server version. mysql_get_server_info();

mysql_get_server_info() returns a string that represents the server version. mysql_get_server_info();

My SQL – Pconnect Establishes a persistent connection to a My. SQL server like

My SQL – Pconnect Establishes a persistent connection to a My. SQL server like mysql_connect with two major differences. mysql_pconnect($recordset); �First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. �Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

My SQL – Pconnect

My SQL – Pconnect

get_resource_type This function used to get the type of resource. get_resource_type($resource);

get_resource_type This function used to get the type of resource. get_resource_type($resource);

PHP Cookies What is a Cookie? A cookie is often used to identify a

PHP 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 too. With PHP, you can both create and retrieve cookie values. A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website. When the user browses the same website in the future, the data stored in the cookie can be retrieved by the website to notify the website of the user's previous activity - Wiki

How to Create a Cookie? The setcookie() function is used to set a cookie.

How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie(name, value, expire, path, domain); E. g. <? php setcookie("user", "Alex Porter", time()+3600); ? > <html>

Note: The value of the cookie is automatically URLencoded when sending the cookie, and

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead). Example 2 You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <? php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ? > <html>. . . In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve

How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve 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); ? >

In the following example we use the isset() function to find out if a

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

How to Delete a Cookie? When deleting a cookie you should assure that the

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

Form data is posted to cookies. php.

Form data is posted to cookies. php.

Gathering data to be written as a cookie

Gathering data to be written as a cookie

Function setcookie takes the name of the cookie to be set as the first

Function setcookie takes the name of the cookie to be set as the first argument, followed by the value to be stored in the cookie. The optional third argument specifies the expiration date of the cookie.

Each form field’s value is printed to confirm the data that has been set

Each form field’s value is printed to confirm the data that has been set as a cookie with the user. Hyperlink to read. Cookies. php.

read. Cookies. php

read. Cookies. php

The foreach loop iterates through the $_COOKIE PHP creates array $_COOKIE which array and

The foreach loop iterates through the $_COOKIE PHP creates array $_COOKIE which array and prints theall name and values value of each by their contains cookie indexed cookie in an XHTML table. names.

PHP Sessions A PHP session variable is used to store information about, or change

PHP Sessions A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. PHP Session Variables When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain 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). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session Before you can store user information in your PHP session,

Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <? php session_start(); ? > <html> <body> </html> The code above 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.

Storing a Session Variable The correct way to store and retrieve session variables is

Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <? php session_start(); // store session data $_SESSION['views']=1; ? > <html> <body> <? php //retrieve session data echo "Pageviews=". $_SESSION['views']; ? > </body> </html> Output: Pageviews=1

In the example below, we create a simple page-views counter. The isset() function checks

In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: <? php session_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

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: <? php session_start(); if(isset($_SESSION['views'])) unset($_SESSION['views']); ? > You can also completely destroy the session by calling the session_destroy() function: <? php session_destroy(); ? > Note: session_destroy() will reset your session and you will lose all your stored session data.