1 / 33

Unit 3 E-MAILING WITH PHP

Unit 3 E-MAILING WITH PHP. Topics to be Covered: Sending an email, Multipart Message, Storing Images, Getting Confirmation, Session Tracking using PHP, Graphics Input Validators, Cookies. Sending an email. PHP makes use of mail() function to send an email.

corbitt
Download Presentation

Unit 3 E-MAILING WITH PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 email 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 email 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…)

  5. Sending an email (Contd…) Example: Sending plain text email <?php $to = "xyz@xyz.com"; $subject = "This is subject"; $message = "This is simple text message."; $header = "From:abc@abc.com \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 email <html> <head> <title>Sending HTML email using PHP</title> </head> <body> <?php $to = "xyz@xyz.com"; $subject = "This is subject"; $message = "<b>This is HTML message.</b>"; $message.= "<h1>This is headline.</h1>"; $header = "From:abc@abc.com \r\n"; $header.= "Cc:pqr@pqr.com \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>

  7. Sending an email (Contd…) Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email 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 email 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 email.

  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 email'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 = "karnam.sreenu@gmail.com"; $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 = "From:bvrtes@bvrtes.com\r\n"; $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"; $header.= "--$num\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 email 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 constantPHPSESSID.

  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[“email”] = “sreenu@gmail.com"; //retrieve session data echo $_SESSION["username"].”<br>”; echo $_SESSION[“email”]; ?>

  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. Example: <?php session_start(); 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>

  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. 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. 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. 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. 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> <?php echo "Set Cookies“ ?> </body> </html>

  30. 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. 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() - 3600); ?> <html> <body> <?php echo "Cookie 'user' is deleted."; ?> </body> </html>

  32. 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() + 3600, '/'); ?> <html> <body> <?php if(count($_COOKIE) > 0) { echo "Cookies are enabled."; } else { echo "Cookies are disabled."; } ?> </body> </html>

  33. Cookies (Contd…) Cookies Path: C:\User\%username\AppData\Roaming\Microsoft\Windows\Cookies\Low Session Path: C:\xampp\tmp

More Related