Topics to be Covered: Sending an , Multipart Message,

Slides:



Advertisements
Similar presentations
LIS651 lecture 3 taming PHP Thomas Krichel
Advertisements

LIS651 lecture 3 functions & sessions Thomas Krichel
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Chapter 10 Managing State Information Using Sessions.
Chapter 10 Managing State Information PHP Programming with MySQL.
Using Session Control in PHP tMyn1 Using Session Control in PHP HTTP is a stateless protocol, which means that the protocol has no built-in way of maintaining.
Chapter 10 Maintaining State Information Using Cookies.
Objectives Learn about state information
Uploading Files. Why? By giving a user the option to upload a file you are creating an interactive page You can enable users have a greater web experience.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Cookies Set a cookie – setcookie() Extract data from a cookie - $_COOKIE Augment user authentication script with a cookie.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Electronic Mail Originally –Memo sent from one user to another Now –Memo sent to one or more mailboxes Mailbox –Destination point for messages.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Cookies & Session Web Technology
PHP Programming with MySQL Slide 10-1 CHAPTER 10 Managing State Information.
Topics Sending an Multipart message Storing images Getting confirmation Session tracking using PHP Graphics Input Validators Cookies.
COOKIES and SESSIONS. COOKIES 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.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
CHAPTER 8 PHP Advanced อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
How to maintain state in a stateless web Shirley Cohen
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
 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.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Cookies and Sessions in PHP. Arguments for the setcookie() Function There are several arguments you can use i.e. setcookie(‘name’, ‘value’, expiration,
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Sessions and cookies (part 2) MIS 3501, Fall 2015 Brad N Greenwood, PhD Department of MIS Fox School of Business Temple University 11/19/2015.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
Programming for the Web Cookies & Sessions Dónal Mulligan BSc MA
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
Week 7 Server side programming PHP Scripting Language MySQL Database Apache Server IT4103 Web Programming
The need for persistence Consider these examples  Counting the number of “hits” on a website  i.e. how many times does a client load your web page source.
Web Engineering Lecture-08.
LIS651 lecture 3 functions & sessions
CHAPTER 5 SERVER SIDE SCRIPTING
PHP Cookies What is a Cookie?
CGS 3066: Web Programming and Design Spring 2016
CONTENT MANAGEMENT SYSTEM CSIR-NISCAIR, New Delhi
Server-Side Application and Data Management IT IS 3105 (Spring 2010)
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
1 CHAPTER 10 ADVANCED PHP.
ITM 352 Cookies.
Web Programming Language
Cookies and Sessions in PHP
Implementing Cookies in PHP
Introduction to Web programming
<?php require("header.htm"); ?>
Cookies Cookie :- A cookie is often used to identify a user. A cookie is often used to identify a user. A cookie is a small file that the server embeds.
Software Engineering for Internet Applications
Configuring Internet-related services
William Stallings Data and Computer Communications
PHP State.
Cookies and Sessions.
Web Programming Language
PHP PROF. S. LAKSHMANAN, DEPT. OF B. VOC. (SD & SA),
Advanced Concepts and AJAX
PHP-II.
[Based in part on SWE 432 and SWE 632 materials by Jeff Offutt, GMU]
Presentation transcript:

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

Sending an email (Contd…) Parameter Description to Required. Specifies the receiver / receivers of the email subject Required. Specifies the subject of the email. 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

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

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> Sending an email (Contd…)

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.

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.

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

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

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

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>

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

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>"; ?>

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>

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

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.

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.

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.

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”]; ?>

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

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

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>

Session Tracking using PHP (Contd…) Example (Contd…) Filename: otherpage.php <?php session_start(); echo "Welcome "."<b>".$_SESSION['username']."</b>". " your count is: ".$_SESSION['counter']; ?>

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.

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.

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.

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.

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>

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>

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

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

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