Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

Web Engineering

Lecture PHP
Instructor
Dr. Mariam Rehman
Professor

Department of Information Technology, Government College University


Contents
• PHP Functions
• PHP GET and POST
• PHP File Inclusion
• PHP Files and I/O
• PHP Session Management
• PHP Email Handling
PHP Functions

• A function will be executed by a call to the function.


• Give the function a name that reflects what the
function does
• The function name can start with a letter or
underscore (not a number)
• Syntax
function functionName()
{ code to be executed;
}
PHP Functions - Example
• <html>
• <body>
• <?php
• function writeName()
• {
• echo “Web Engineering";
• }
• echo "My Course Name is "; writeName();
• ?>
• </body>
• </html>
PHP Functions - Adding parameters

• To add more functionality to a function, add


parameters. A parameter is just like a variable.
• Parameters are specified after the function name,
inside the parentheses.

function writeName($fname)
{
echo $fname;
}
1. <html>
2. <body> PHP Functions - Parameters Example 1
3. <?php
4. function writeName($fname)
5. {
6. echo $fname;
7. }
8. echo "My name is ";
9. writeName(“Samander Khan");
10.echo "My sister's name is ";
11.writeName(“Gul Lala");
12.echo "My brother's name is ";
13.writeName(“Derya Khan");
14.?>
15.</body>
16.</html>
1. <html>
2. <body> PHP Functions - Parameters Example 1
3. <?php
4. function writeName($fname, $punctuation)
5. {
6. echo $fname . " Faraz" . $punctuation . "<br />";
7. }
8. echo "My name is ";
9. writeName(“Ali",".");
10.echo "My sister's name is ";
11.writeName(“Ammara","!");
12.echo "My brother's name is ";
13.writeName(“Usama","?");
14.?>
15.</body>
16.</html>
1. <html>
PHP Functions – Return Value Exp 3
2. <body>
3. <?php
4. function add($x,$y)
5. {
6. $total=$x+$y;
7. return $total;
8. }
9. echo "1 + 16 = " . add(1,16);
10.?>
11.</body>
12.</html>
PHP GET & POST
PHP GET Cont.
• The built-in $_GET function is used to collect values
from a form sent with method="get".
• Information sent from a form with the GET method is
visible to everyone (it will be displayed in the
browser's address bar)
• The GET method is restricted to send upto 1024
characters only.
• Never use GET method if you have password or other
sensitive information to be sent to the server.
PHP GET Cont.
• GET can't be used to send binary data, like images or word
documents, to the server.
• The data sent by GET method can be accessed using
QUERY_STRING environment variable.
• The PHP provides $_GET associative array to access all the
sent information using GET method.
• The GET method sends the encoded user information
appended to the page request. The page and the encoded
information are separated by the ? character.
• http://www.test.com/index.php?
name1=value1&name2=value2
PHP GET --- Example
1. <?php
2. if( $_GET["name"] || $_GET["age"] ) {
3. echo "Welcome ". $_GET['name']. "<br />";
4. echo "You are ". $_GET['age']. " years old.";
5.
6. exit();
7. }
8. ?>
9. <html>
10. <body>
11.
12. <form action = "<?php $_PHP_SELF ?>" method = "GET">
13. Name: <input type = "text" name = "name" />
14. Age: <input type = "text" name = "age" />
15. <input type = "submit" />
Output:
16. </form>
17.
18. </body> Welcome Ali
19.</html> Your are 22 years old.
PHP POST Cont.
• The built-in $_POST function is used to collect values
from a form sent with method="post".
• Information sent from a form with the POST method
is invisible to others.
• There is no limits on the amount of information to
send.
• http://www.test.com/index.php
PHP POST Cont.
• The POST method can be used to send ASCII as well
as binary data.
• The data sent by POST method goes through HTTP
header so security depends on HTTP protocol.
• By using Secure HTTP you can make sure that your
information is secure.
• The PHP provides $_POST associative array to access
all the sent information using POST method.
PHP GET --- Example
1. <?php
2. if( $_POST["name"] || $_POST["age"] ) {
3. if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
4. die ("invalid name and name should be alpha");
5. }
6. echo "Welcome ". $_POST['name']. "<br />";
7. echo "You are ". $_POST['age']. " years old.";
8.
9. exit();
10. }
11.?>
12.<html>
13. <body>
14.
15. <form action = "<?php $_PHP_SELF ?>" method = "POST">
16. Name: <input type = "text" name = "name" />
17. Age: <input type = "text" name = "age" />
18. <input type = "submit" />
19. </form>
20.
21. </body>
22.</html>
PHP File Inclusion
PHP File Inclusion Cont.

• Include the content of a PHP file into another PHP


file before the server executes it.
• There are two PHP functions which can be used to
included one PHP file into another PHP file.

1. The include() Function


2. The require() Function
PHP File Inclusion Cont.

• This is a strong point of PHP which helps in creating


functions, headers, footers, or elements that can be
reused on multiple pages.
• This will help developers to make it easy to change
the layout of complete website with minimal effort.
• If there is any change required then instead of
changing thousand of files just change included file.
PHP File Inclusion --- Include() Function

• The include() function takes all the content in a


specified file and includes it in the current file.
• If an error occurs, the include() function generates a
warning, but the script will continue execution.
PHP File Inclusion --- Include() Function
Example Cont.
• Assume you want to create a common menu for your
website. Then create a file menu.php with the
following content.
1. <a href="http://www.tutorial.com/index.htm">Home</a>
2. <a href="http://www.tutorialt.com/ebxml">ebXML</a>
3. <a href="http://www.tutorial.com/ajax">AJAX</a>
4. <a href="http://www.tutorial.com/perl">PERL</a> <br />
PHP File Inclusion --- Include() Function
Example
1. <html>
2. <body>
3. <?php
4. include("menu.php");
5. ?>
6. <p>This is an example to show how to include PHP file!</p>
7. </body>
8. </html>
Home
ebXML
AJAX
PERL
PHP File Inclusion --- Require() Function

• The require() function is identical to include(), except


that it handles errors differently.
• If an error occurs, the include() function generates a
warning, but the script will continue execution. The
require() generates a fatal error, and the script will
stop.
• It is recommended to use the require() function
instead of include(), because scripts should not
continue after an error.
Error Example include() Function Cont.

1. <html> ERROR MESSAGE


2. <body>
Warning: include(wrongFile.php)
3. <?php
[function.include]: failed to open stream:
4. include("wrongFile.php");No such file or directory in C:\home\
5. echo "Hello World!"; website\test.php on line 5
6. ?> Warning: include() [function.include]:
7. </body> Failed opening 'wrongFile.php' for
inclusion (include_path='.;C:\php5\pear')
8. </html>
in C:\home\website\test.php on line 5

Hello World!
Error Example include() Function

1. <html>
2. <body>
3. <?php
4. require("wrongFile.php")echo "Hello World!";
5. ?>
6. </body> ERROR MESSAGE
7. </html>
Warning: require(wrongFile.php) [function.require]:
failed to open stream: No such file or directory in C:\
home\website\test.php on line 5

Fatal error: require() [function.require]: Failed opening


required 'wrongFile.php' (include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Tell the Difference?

The echo statement is not executed, because


the script execution stopped after the fatal error.
PHP Files and I/O
PHP Files and I/O

• Opening a file
• Reading a file
• Writing a file
• Closing a file
PHP Files and I/O --- Open Files Cont.
• PHP fopen() function is used to open a file.
• The first parameter of this function contains the name of the file to be
opened and
• the second parameter specifies in which mode the file should be
opened:
1. <html>
2. <body>
3. <?php
4. $file=fopen("welcome.txt","r");
5. ?>
6. </body>
7. </html>
PHP Files and I/O --- Open Files Cont.
• 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
PHP Files and I/O --- Open Files

• If an attempt to open a file fails then fopen returns a


value of false otherwise it returns a file
pointer which is used for further reading or writing
to that file.
PHP Files and I/O --- Close Files

• fclose() function is used to close an open file


1. <?php
2. $file = fopen("test.txt","r");
3. //some code to be executed
4. fclose($file);
5. ?>
• The fclose() function requires a file pointer as its
argument and then returns true when the closure
succeeds or false if it fails.
PHP Files and I/O --- Check End-of-file

• feof() function checks if the "end-of-file" (EOF) has


been reached.
• The feof() function is useful for looping through data
of unknown length.
• Note: You cannot read from files opened in w, a, and
x mode!
• if (feof($file)) echo "End of file";
PHP Files and I/O --- Reading a File Line by
Line
• The fgets() function is used to read a single line from a file.
• Note: After a call to this function the file pointer has moved to the
next line.
• <?php
• $file = fopen("welcome.txt", "r") or exit("Unable to open file!");
• //Output a line of the file until the end is reached while(!feof($file))
{
• echo fgets($file). "<br />";
• }
• fclose($file);
• ?>
PHP Files and I/O ---
Reading a File Character by Character
• 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.
1. <?php
2. $file=fopen("welcome.txt","r") or exit("Unable to open file!");
3. while (!feof($file))
4. {
5. echo fgetc($file);
6. }
7. fclose($file);
8. ?>
PHP Files and I/O --- Read File

• fread() function requires two arguments. These must be the


file pointer and the length of the file expressed in bytes.
• The files length can be found using the filesize() function
which takes the file name as its argument and returns the
size of the file expressed in bytes.
• Steps required to read a file with PHP are:
1. Open a file using fopen() function.
2. Get the file's length using filesize() function.
3. Read the file's content using fread() function.
4. Close the file with fclose() function.
1. <html>

Example
2. <head>
3. <title>Reading a file using PHP</title>
4. </head>
5. <body>
6. <?php
7. $filename = "tmp.txt";
8. $file = fopen( $filename, "r" );
9. if( $file == false ) {
10. echo ( "Error in opening file" );
11. exit();
12. }
13. $filesize = filesize( $filename );
14. $filetext = fread( $file, $filesize );
15. fclose( $file );
16.
17. echo ( "File size : $filesize bytes" );
18. echo ( "<pre>$filetext</pre>" );
19. ?>
20. </body>
21. </html>
PHP Files and I/O --- Write File

• fwrite() functionrequires two arguments specifying


a file pointer and the string of data that is to be
written.
• Optionally a third integer argument can be included
to specify the length of the data to write.
• If the third argument is included, writing would will
stop after the specified length has been reached.
1. <?php

Example
2. $filename = "/home/user/guest/newfile.txt";
3. $file = fopen( $filename, "w" );
4. if( $file == false ) {
5. echo ( "Error in opening new file" );
6. exit(); 19. if( $file == false ) {
7. } 20. echo ( "Error in opening file" );
8. fwrite( $file, "This is a simple test\n" ); 21. exit();
9. fclose( $file ); 22. }
10. ?> 23.
11. <html> 24. $filesize = filesize( $filename );
12. <head> 25. $filetext = fread( $file, $filesize );
13. <title>Writing a file using PHP</title> 26.
14. </head> 27. fclose( $file );
15. <body> 28.
16. <?php 29. echo ( "File size : $filesize bytes" );
17. $filename = "newfile.txt"; 30. echo ( "$filetext" );
18. $file = fopen( $filename, "r" ); 31. echo("file name: $filename");
32. ?>
33.
34. </body>
35. </html>
PHP Session Management
Session Management

• PHP session allows 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.
• 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.
Session Management --- Starting Session

• Before user information is stored, PHP session


must be started first.
• The session_start() function must appear BEFORE
the <html> tag.
1. <?php session_start(); ?>
2. <html>
3. <body>
4. </body>
5. </html>
Session Management --- Starting Session

1. The code will register the user's session with


the server,
2. Allow you to start saving user information,
3. And assign a UID for that user's session.
Session Management --- Storing Session
Variable
• To store and retrieve session variables is to use the PHP
$_SESSION variable
1. <?php
2. session_start();
3. if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
4. else
5. $_SESSION['views']=1;
6. echo "Views=". $_SESSION['views'];
7. ?>
Session Management --- Storing Session
Variable
• 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.
Session Management --- Destroying Session
Cont.
• completely destroy the session by calling the
session_destroy() function
• session_destroy() will reset your session and you will
lose all your stored session data.

• <?php
• session_destroy();
• ?>
Session Management --- Destroying Session

• Use the unset() or the session_destroy() function to


delete session data.
• unset() function is used to free the specified session
variable

– <?php
– unset($_SESSION['views']);
– ?>

PHP EMAIL HANDLING
PHP EMAIL HANDLING Cont.
• PHP mail() function is used to send emails from inside a script.
• This function requires three mandatory arguments that
specify
– recipient's email address,
– subject of the message and
– actual message
• additionally there are other two optional parameters.

• mail(to,subject,message,headers,parameters)
PHP EMAIL HANDLING Cont.
PHP EMAIL HANDLING Cont.
• Simplest way to send an email with PHP is to send a text
email.
• First declare the variables ($to, $subject, $message, $from,
$headers)
1. <?php
2. $to = "someone@example.com";
3. $subject = "Test mail";
4. $message = "Hello! This is a simple email message.";
5. $from = "someonelse@example.com";
6. $headers = "From: $from";
7. mail($to,$subject,$message,$headers);
8. echo "Mail Sent.";
9. ?>
• HOW can you send email with attachment?
• What is the role of php.ini file?
Practice
• Practice all Content discussed in this Slide
• Embed code in html forms so you can get real look of
professional website.
• Go through all topics on you tube.
Reading and Practice
• https://www.tutorialspoint.com/php/php_files.htm
• https://codeforgeek.com/2014/08/session-handling-php/
• https://www.w3schools.com/php/func_mail_mail.asp
• https://www.youtube.com/watch?v=h6KID8n0zCU

You might also like