Download presentation
Presentation is loading. Please wait.
Published byChristiana Haynes Modified over 6 years ago
1
Unit 3 E-MAILING WITH PHP
2
Topics to be Covered: Sending an email, Multipart Message,
Storing Images, Getting Confirmation, Session Tracking using PHP, Graphics Input Validators, Cookies.
3
Sending an email PHP makes use of mail() function to send an email.
This function requires three mandatory arguments that specify the recipient's address, the subject of the message and the actual message additionally there are other two optional parameters. Syntax: mail(to, subject, message, headers, parameters); As soon as the mail function is called PHP will attempt to send the then it will return true if successful or false if it is failed. Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.
4
Sending an email (Contd…)
Parameter Description to Required. Specifies the receiver / receivers of the subject Required. Specifies the subject of the . This parameter cannot contain any newline characters message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n) parameters Optional. Specifies an additional parameter to the send mail program
5
Sending an email (Contd…)
Example: Sending plain text <?php $to = $subject = "This is subject"; $message = "This is simple text message."; $header = \r\n"; $retval = mail ($to, $subject, $message, $header); if( $retval == true ) { echo "Message sent successfully..."; } else { echo "Message could not be sent..."; ?>
6
Sending an email (Contd…)
Example: Sending HTML <html> <head> <title>Sending HTML using PHP</title> </head> <body> <?php $to = $subject = "This is subject"; $message = "<b>This is HTML message.</b>"; $message.= "<h1>This is headline.</h1>"; $header = \r\n"; $header.= \r\n"; $header.= "MIME-Version: 1.0\r\n"; $header.= "Content-type: text/html\r\n"; $retval = mail ($to,$subject,$message,$header); if( $retval == true ) { echo "Message sent successfully..."; } else { echo "Message could not be sent..."; ?> </body> </html> Sending an (Contd…)
7
Sending an email (Contd…)
Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of to support: Text in character sets other than ASCII, Non-text attachments, Message bodies with multiple parts, Header information in non-ASCII character sets. To send an with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the .
8
Sending an email (Contd…)
A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the 's final section must also end with two hyphens. Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.
9
Sending an email (Contd…)
<html> <head> <title>Sending attachment using PHP</title> </head> <body> <?php $to = $subject = "This is subject"; $message = "This is test message."; # Open a file $file = fopen( "mail6.php", "r" ); if( $file == false ) { echo "Error in opening file"; exit(); }
10
Sending an email (Contd…)
# Read the file into a variable $size = filesize("mail6.php"); $content = fread( $file, $size); # encode the data for safe transit # and insert \r\n after every 76 chars. $encoded_content = chunk_split( base64_encode($content)); # Get a random 32 bit number using time() as seed. $num = md5( time() );
11
Sending an email (Contd…)
# Define the main headers. $header = $header.= "MIME-Version: 1.0\r\n"; $header.= "Content-Type: multipart/mixed; "; $header.= "boundary=$num\r\n"; $header.= "--$num\r\n"; # Define the message section $header.= "Content-Type: text/plain\r\n"; $header.= "Content-Transfer-Encoding:8bit\r\n\n"; $header.= "$message\r\n";
12
Sending an email (Contd…)
# Define the attachment section $header.= "Content-Type: multipart/mixed; "; $header.= "name=\"mail6.php\"\r\n"; $header.= "Content-Transfer-Encoding:base64\r\n"; $header.= "Content-Disposition:attachment; "; $header.= "filename=\"mail6.php\"\r\n\n"; $header.= "$encoded_content\r\n"; $header.= "--$num--"; # Send now $retval = mail ( $to, $subject, "", $header ); if( $retval == true ){ echo "Message sent successfully..."; } else { echo "Message could not be sent..."; ?> </body> </html>
13
Storing an Image <?php if(isset($_POST["submit"])) {
mysql_connect('localhost','root',''); mysql_select_db('mydb1'); $imgData =addslashes(file_get_contents($_FILES["fileToUpload"]["tmp_name"])); $sql="INSERT into profile(image) values ('$imgData')"; mysql_query($sql) or die(mysql_error()); } ?>
14
Displaying an Image <?php mysql_connect('localhost','root','');
mysql_select_db('mydb1'); $sql="SELECT * from profile"; $query=mysql_query($sql); while($row=mysql_fetch_array($query)){ echo "<center>"; echo " ".'<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" ">'; } echo "</center>"; ?>
15
Uploading an Image <html> <body>
<form action="upload1.php" method="post“ enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload1"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html>
16
Uploading an Image (Contd…)
<?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; if(isset($_POST["submit"])) { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; ?>
17
Session Tracking using PHP
A PHP Session is used to store information on the server, this information can be used across multiple pages. A session creates a file in a temporary directory on the server where registered session variables and their values are stored. A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration. Starting a PHP Session: Before use session variables, you must first start the session using the session_start() function. The function session_start() should be in starting and you can’t send anything to the browser before it.
18
Session Tracking using PHP (Contd…)
When a session is started following things happen: PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443. A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string. A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
19
Session Tracking using PHP (Contd…)
Example: <?php session_start(); ?> <html> <body> </body> </html> When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the session id using the PHP session_id() function or predefined constant PHPSESSID.
20
Session Tracking using PHP (Contd…)
Storing a Session Variable: Associative array called $_SESSION[] is used to store information in a session. These variables can be accessed during lifetime of a session. Example: <?php session_start(); // store session data $_SESSION[“username”] = “Sreenu"; $_SESSION[“ ”] = //retrieve session data echo $_SESSION["username"].”<br>”; echo $_SESSION[“ ”]; ?>
21
Session Tracking using PHP (Contd…)
Destroying a Session A complete PHP session can be destroyed by using session_destroy() function, which does not require any arguments. Example: <?php session_start(); session_destroy(); ?> If you wish to delete a single session variable then you can use unset() function. if(isset($_SESSION[username])) unset($_SESSION[username]);
22
Session Tracking using PHP (Contd…)
Example: <?php session_start(); $_SESSION['username'] = 'Sreenu'; if( isset( $_SESSION['counter'] ) ) { $_SESSION['counter'] += 1; } else { $_SESSION['counter'] = 1; $msg = $_SESSION['username']." , you have visited this page ". $_SESSION['counter']; $msg .= " times in this session."; echo ( $msg )."<br><br><br>"; echo "Session ID is: ".session_id(); ?> <html> <p> <a href="nextpage.php">Click here to get the username and count in next page.....<br /> </a> </p> </html> Session Tracking using PHP (Contd…)
23
Session Tracking using PHP (Contd…)
Example (Contd…) Filename: nextpage.php <?php session_start(); echo "Welcome ".$_SESSION['username']." your count is: ".$_SESSION['counter']; ?> <html> <p> <a href="otherpage.php">Click here to get the username and count in next page.....<br/> </a> </p> </html>
24
Session Tracking using PHP (Contd…)
Example (Contd…) Filename: otherpage.php <?php session_start(); echo "Welcome "."<b>".$_SESSION['username']."</b>". " your count is: ".$_SESSION['counter']; ?>
25
Cookies Cookies are text files stored on the client computer and they are kept for tracking purpose. PHP transparently supports HTTP cookies. There are three steps involved in identifying returning users: Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
26
Setting Cookies with PHP
Cookies (Contd…) Setting Cookies with PHP PHP provided setcookie() function to set a cookie. This function takes six arguments and should be called before <html> tag. For each cookie this function has to be called separately. Syntax: setcookie(name, value, expire, path, domain, security); Only the name parameter is required. All other parameters are optional.
27
Here is the detail of all the arguments:
Cookies (Contd…) Here is the detail of all the arguments: Name - This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies. Value - This sets the value of the named variable and is the content that you actually want to store. Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
28
Domain - This can be used to specify the domain name.
Cookies (Contd…) Path -This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories. Domain - This can be used to specify the domain name. Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
29
Example for setting Cookies: <?php
Cookies (Contd…) Example for setting Cookies: <?php setcookie("name", "Sreenu", time()+3600, "/","", 0); setcookie("age", "36", time()+3600, "/", "", 0); ?> <html> <head> <title>Setting Cookies with PHP</title> </head> <body> echo "Set Cookies“ </body> </html>
30
PHP provides many ways to access cookies.
Cookies (Contd…) PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Example for accessing Cookies: <html> <head> <title>Accessing Cookies with PHP</title> </head> <body> <?php if( isset($_COOKIE["name"])) echo "Welcome " . $_COOKIE["name"] . "<br />"; else echo "Sorry... Not recognized" . "<br />"; ?> </body> </html>
31
// set the expiration date to one hour ago
Cookies (Contd…) Delete a Cookie: To delete a cookie, use the setcookie() function with an expiration date in the past. <?php // set the expiration date to one hour ago setcookie("user", "", time() ); ?> <html> <body> echo "Cookie 'user' is deleted."; </body> </html>
32
Check if Cookies are Enabled:
Cookies (Contd…) Check if Cookies are Enabled: The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable. <?php setcookie("test_cookie", "test", time() , '/'); ?> <html> <body> <?php if(count($_COOKIE) > 0) { echo "Cookies are enabled."; } else { echo "Cookies are disabled."; </body> </html>
33
Session Path: C:\xampp\tmp
Cookies (Contd…) Cookies Path: C:\User\%username\AppData\Roaming\Microsoft\Windows\Cookies\Low Session Path: C:\xampp\tmp
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.