1/7/20161 open source programming emailing with php unit – iii sending an email – multipart...

79
03/30/22 1 Open Source Programming emailing with PHP Unit – III Sending an email – multipart message storing images getting confirmation. Session tracking using PHP – Graphics and Input Validators – cookies.

Upload: samuel-simpson

Post on 19-Jan-2016

229 views

Category:

Documents


0 download

TRANSCRIPT

04/21/23 1Open Source Programming

emailing with PHP

Unit – III

Sending an email – multipart message – storing images – getting confirmation. Session tracking using PHP – Graphics and Input Validators – cookies.–

04/21/23 2Open Source Programming

Emailing with PHP

If you are in a *NIX environment, you will most likely have sendmail installed on your server. If you are using a hosting service, check with your service provider to make sure sendmail or some equivalent is being used. Once you have your mail server squared away, you’ll need to modify your php.ini

1.SMTP - Set this to the ip address or DNS name of

your SMTP server. default value : localhost

2.sendmail_from -The From address used by default

by the PHP mail() command

3.smtp_port - Set this to the port PHP uses to connect

to the SMTP server. default value 25

04/21/23 3Open Source Programming

Email – mail()It is a function in PHP used to send an email. It returns true on success of sending an email, otherwise false.

mail(to,sub,message, headers, other_parameters)(In this, the first three parameters are must. )

Where to- the receiver(s) email address(es). “,” used as delimiter to separate the addresses.Sub – subject of the mailMessage – text which has to delivered to the receiver(s).Each line should be separated with a CRLF (\r\n). Lines should not

be larger than 70 characters.Headers – additional parameter used

1. to include BCC & CC email address(es),2. send the mail as multipart, and3. contains the attachment file

Other_parameters – used to display some additional information to the receiver(s).

04/21/23 4Open Source Programming

Simple Mail program<? php$to=“[email protected]”;$sub=“Test mail”;$message1 = “This is a sample test mail";$mailsent = mail($to,$sub,$message1);If ($mailsent) echo “the mail was sent to $to successfully”;Else echo “the mail couldn’t send. Pl verify your mail settings / connection”;?>

Output:

The mail was sent to [email protected] successfully.

04/21/23 5Open Source Programming

Collecting Data & Sending Email

Can collect the data through HTML forms and can send an email. Should create one HTML program to collect information like to-address, subject, message from user; and one PHP program to send mail using these information.

Collecting Data and Sending Mail

• we are going to create two Web pages, mailform.html and email.php The file mailform.html will collect the data you are going to send. The file email.php will actually send the message, using the data you enter.

• Save the first page as mailform.html. Note that mailform.html doesn’t actually have any PHP code in it. It simply collects the required data in an HTML form.

• Save the second page as email.php. This second page will take the values entered into the first page, and send them in an e-mail.

04/21/23 7Open Source Programming

Email – program

<html><form action="email.php" method=“POST">EmailId: <input type="text" name="email" size=40><br>Subject:<input type="text" name="subject" size=40><br>Message:<br><textarea cols=40 rows=10 name="message"></textarea><input type="submit" value="Send"></form></html>

Email.html

04/21/23 8

email.php<?php ini_set("sendmail_from", "[email protected]");ini_set("SMTP","mail.vit.ac.in");echo "<h1>Welcome to emailing with PHP</h1>";echo "<br>";$to= $_REQUEST["to"]; $subject= $_REQUEST["subject"]; $message= $_REQUEST["MESSAGE"]; $from = "[email protected]";$headers = "From:" . $from;$send=mail($to,$subject,$message,$headers);if($send)echo "congrats! The following Mail has been Sent<br><br>";echo "<b>To:</b> $to<br>";echo "<b>From:</b> $from<br>";echo "<b>Subject:</b> $subject<br>";echo "<b>Message:</b><br>";echo $message;elseecho "error in sending mail...."; ?>

Running the script• Load up the first page, Email.html, in

your browser, and enter some data. Make sure you use valid e-mail addresses so that you can verify their receipt.

• Click the Send button. A second page appears, similar to the one shown below.

• Open your e-mail client and check your e-mail

04/21/23 10Open Source Programming

Email Program – Input

[email protected]

[email protected]

Hello World….

…. We will be there soon!

04/21/23 11Open Source Programming

Email Program – Result

04/21/23 12Open Source Programming

Receiver’s Inbox

04/21/23 13Open Source Programming

Email to more addresses<? php$to=“[email protected], [email protected], [email protected]”;$sub=“Test mail”;$message1 = “This is a sample test mail";$mailsent = mail($to,$sub,$message1);If ($mailsent) echo “the mail was sent to $to successfully”;Else echo “the mail couldn’t send. Pl verify your mail settings / connection”;?>

Output:

The mail was sent to [email protected], [email protected], [email protected] successfully.

04/21/23 14Open Source Programming

Email with CC & BCC

The cc & bcc addresses to be included in header parameter as follows:

$header=“cc: [email protected],[email protected]

Or

$header=“bcc: [email protected],[email protected]

If u want to add both together, then

$header =“cc: [email protected],[email protected]\r\n”

$header.=“bcc: [email protected],[email protected]

Here \r\n – is the boundary between cc & bcc. It is must to use \r\n to the header, if you want to add more parameters.

04/21/23 15Open Source Programming

Email – with cc <? php$to=“[email protected]”;$sub=“Test mail”;$message1 = “This is a sample test mail";$header = “cc:[email protected], [email protected]”;$mailsent = mail($to,$sub,$message1,$header);If ($mailsent) echo “the mail was sent to $to and $headersuccessfully”;Else echo “the mail couldn’t send. Pl verify your mail settings / connection”;?>

Output:

The mail was sent to [email protected] cc:[email protected], [email protected] successfully.

04/21/23 16Open Source Programming

Email – with cc & Bcc<? php$to=“[email protected]”;$sub=“Test mail”;$message1 = “This is a sample test mail";$header = “cc:[email protected], [email protected]\r\n”;$header .=“bcc: [email protected]”;$mailsent = mail($to,$sub,$message1,$header);If ($mailsent) echo “the mail was sent to $to and $headersuccessfully”;Else echo “the mail couldn’t send. Pl verify your mail settings / connection”;?>

Output:

The mail was sent to [email protected] cc:[email protected], [email protected] bcc: [email protected] successfully.

04/21/23 17Open Source Programming

Email – HTML messages

In order to send messages as a plain text and an HTML, will use headers with additional information as follows:

$headers = “MIME Version 1.0 \r\n”;$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";$headers .= "Content-Transfer-Encoding: 7bit\r\n";

Tell the e-mail client that data is coming in multiple parts—in this instance, plain text and HTML. This tells the e-mail client to look for additional “Content-type” information in the message, which includes boundary information. The boundary is what separates the multiple parts of the message.

04/21/23 18Open Source Programming

Email as HTML COntent<? php$to=“[email protected]”;$sub=“Test mail”;$message1 = “<h1>MIME mail</h1>This<br> is <br>a <br>sample <br>test <br>mail";$headers = "MIME-Version: 1.0\r\n";$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";$headers .= "Content-Transfer-Encoding: 7bit\r\n";$mailsent = mail($to,$sub,$message1,$header);If ($mailsent) echo “the mail was sent to $to successfully”;Else echo “mail was not sent”;?>

04/21/23 19Open Source Programming

It is on receiver side

Email as HTML

04/21/23 20

Multipart Messages

04/21/23 21

04/21/23 22

How it Works

• This tells the e-mail client to look for additional “Content-type” information in the message, which includes boundary information. The boundary is what separates the multiple parts of the message. It begins with two dashes (--), and goes at the beginning of the message, between each part, and at the end.

• The HTML portion of our e-mail follows. Note the double dashes (--) in front of the boundary. Also note the use of two new lines (\n\n) on the Content-Transfer-Encoding line. Do not neglect those— the code will not work correctly without them.

• $message .= “--$boundary\n”;• $message .= “Content-type: text/html; charset=iso-8859-1\n”;• $message .= “Content-Transfer-Encoding: 7bit\n\n”;• $message .= $messagebody . “\n”;

$headers .= “Content-type: multipart/alternative;boundary=\”$boundary\”\r\n”;

04/21/23 23

How it works

• Next is the text portion of our e-mail. Note the similarity to the HTML portion. You do not need to include the same $messagebody here. In fact, you would usually include an alternate message in text format.

$message .= “--$boundary\n”;$message .= “Content-Type: text/plain;

charset=\”iso-8859-1\”\n”;$message .= “Content-Transfer-Encoding: 7bit\n\n”;$message .= $messagebody . “\n”;

• This is the final boundary. Note the double dashes (--) at the end. This signifies that it’s the end of the e-mail.

$message .= “--$boundary--”;• This is used to set the boundary in our example $boundary = “==MP_Bound_xyccr948x==”;

04/21/23 24Open Source Programming

Email with an attachment

To send a email with an attachment, should do the following steps:

Step 1: Open the attach file and transfer its content to a php variable.

Step 2: Assign that file content to the message parameter of the mail function with some attributes and boundary which are needed for attachment.

Step 3: Now add the message which has to be delivered to the receiver with attributes to specify it is a message.

Note: Here, every information has to be separated with a boundary value.

04/21/23 25

Rb Mode• Windows offers a text-mode translation flag ('t') which

will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b'or 't' as the last character of the mode parameter.

• The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases.

• If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

04/21/23 26Open Source Programming

Email – with an attachmentThe above steps will explain in detail with program codes

1. Open the file which has to be attached with the mail in rb mode and transfer the content into a php variable.

$fileatt = "mysql-php.pdf"; // Path to the file$file = fopen($fileatt,'rb');$data = fread($file,filesize($fileatt));fclose($file);

Set the attributes for attachment2.1 Now add the content-type to the message as the type of

attached file.

$email_message = "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n“;

04/21/23 27Open Source Programming

Email – with an attachment

2.2 Then can rename the attach file as follows:$email_message .= " name=\"{$fileatt_name}\"\n“;(here same name used, you can change the name here, if you want. )

2.3 Add “content-disposition: attachment” – which indicates the mail is coming with an attachment.

$email_message .= "Content-Disposition: attachment;\n“;

2.4 Add the transfer encoding type.$email_message .= "Content-Transfer-Encoding: base64\n\n“;

2.5 Now it is a time to add the content of the attachment file.$email_message .= $data . "\n\n“;

2.6 Add the boundary with the message as a ended one.$email_message .= "--{$mime_boundary}--\n";

04/21/23 28Open Source Programming

Email – with an attachment

3.1 Now can add message which has to send as a plain or HTML:

$email_message .= “your file has been sent as an <h1>attachment </h1>to the <font color = red> user specified by you</font>”.

3.2. Now add attributes for message.

$email_message .= "This is a multi-part message in MIME format.\n\n" ."--{$mime_boundary}\n" .

"Content-Type:text/html; charset=\"iso-8859-1\"\n" ."Content-Transfer-Encoding: 7bit\n\n" .

After all the above is done use mail() as follows:$headers = "\nMIME-Version: 1.0\n" ."Content-Type:

multipart/mixed;\n" ." boundary=\"{$mime_boundary}\"";

$sent=mail($to, $sub, $email_message,$headers);

04/21/23 29Open Source Programming

Email with an attachmentDetail explanation about previous steps:

1. Collect the message and store it in a variable.

2. Add the boundary at the end of that message.

3. Enclose the content type of that message and its transfer encoding method.

4. Now add boundary to mark it as end of message.

5. Open the file which has to be attached with the mail in r+ mode and transfer the content into a php variable.

6. Now add the content-type to the message as the type of attached file.

04/21/23 30

7. Then set the name as the file name which has to be sent an attachment.

8. Add “content-disposition: attachment” – which indicates the mail is coming with an attachment.

9. Can add the rename option of the attached file.

10.Add the transfer encoding type.

11.Now it is a time to add the content of the attachment file.

12.Add the boundary with the message as a ended one.

Open Source Programming

Email with an attachment

04/21/23 31

Chunk_split• The chunk_split() function splits a string into a series of

smaller parts.• Syntax

– chunk_split(string,length,end)

ParameterDescription – string Required. Specifies the string to split– Length Optional. A number that defines the length of the

chunks. Default is 76– endOptional. A string that defines what to place at the end of

each chunk. Default is \r\n

Note: This function does not alter the original string.

04/21/23 32Open Source Programming

Sample program The following slides show the sample email program with an

attachment

<?php/* IMAGE ATTACHMENT$fileatt = "test1.jpg"; // Path to the file$fileatt_type = "image/jpg"; // File Type$fileatt_name = "test1.jpg"; // Filename that will be used for the file as the attachment*/

//TEXT ATTACHMENT$fileatt = "MYSQL-PHP.pdf"; // Path to the file$fileatt_type = "application/pdf"; // File Type$fileatt_name = "PHPebook.pdf"; // Filename that will be used for the file as the attachment

04/21/23 33Open Source Programming

Sample program (cont)// READ THE FILE$file = fopen($fileatt,'r+');$data = fread($file,filesize($fileatt));fclose($file);

// ENCODE THE FILE WHICH HAS TO ATTACH$data = chunk_split(base64_encode($data));

// ASSIGNING ADDRESSES, SUBJECT & MESSAGE $email_from = “[email protected]"; // Who the email is from//$email_subject = "image file attached"; // The Subject of the email$email_subject= "PHP book attached as a pdf file";$email_message = "Thanks for visiting mysite.com! Here is your free file.<br>";$email_message .= "Thanks for visiting.<br>"; // Message that the email has in it$email_to = “[email protected]"; // Who the email is to

04/21/23 34Open Source Programming

//CREATE HEADER FOR MULTIPART MESSAGE

$headers = "From: ".$email_from;$semi_rand = md5(time());$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" ."Content-Type: multipart/mixed;\n" ." boundary=\"{$mime_boundary}\"";

// DEFINING MESSAGE TYPE$email_message .= "This is a multi-part message in MIME format.\n\n" ."--{$mime_boundary}\n" ."Content-Type:text/html; charset=\"iso-8859-1\"\n" ."Content-Transfer-Encoding: 7bit\n\n" .$email_message .= "\n\n";

Sample program (cont)

04/21/23 35Open Source Programming

//ATTACHING THE FILE$email_message .= "--{$mime_boundary}\n" ."Content-Type: {$fileatt_type};\n" ." name=\"{$fileatt_name}\"\n" ."Content-Disposition: attachment;\n" ." filename=\"{$fileatt_name}\"\n" ."Content-Transfer-Encoding: base64\n\n" .$data .= "\n\n" ."--{$mime_boundary}--\n";

//SEND MAIL$ok = @mail($email_to, $email_subject, $email_message, $headers);

Sample program (cont)

04/21/23 36Open Source Programming

// check the mail was sent or notif($ok) {echo "Your file has been sent<br> to the email address you specified.<br>Make sure to check your junk mail!<br>

} Else {die("Sorry but the email could not be sent. Please go back and try again!");}?>

Sample program (cont)

04/21/23 37Open Source Programming

Output at Client Side

04/21/23 38Open Source Programming

Receivers Inbox

04/21/23 39Open Source Programming

Storing Images Create a database named as postcard and create a table, images consisting of three fields, imageid, imageurl, imagedes. That table stores the image details. For this, all the images should be stored in a folder called postcards. The following programs explain it.

DBcreation.php<?php //Connect to the server using the correct username and password.$conn = mysql_connect(“yourserver”, “joeuser”, “yourpass”);

/*Create the database. Call it “postcard.” If it is successful, print “Database created” to the screen and move on. */

$sql = “CREATE DATABASE postcard”;$success = mysql_query($sql, $conn) or die(mysql_error());Echo “Database created. . .”;?>

04/21/23 40Open Source Programming

Storing Images (cont)Create a program to connect with databaseDBconnect.php<?php$conn = mysql_connect(“yourserver”, “joeuser”, “yourpass”);mysql_select_db(“postcard”, $conn);?>

Create the images table in the database, containing three columns.Createtable.php<?phprequire(“dbconnect.php”); //imports the db connection prg.$sql = “CREATE TABLE images (id int NOT NULL primary keyauto_increment, img_url VARCHAR (255) NOT NULL,img_desc text )”;$success = mysql_query($sql, $conn) or die(mysql_error());echo “‘images table created. . .”?>

04/21/23 41

Create two arrays, to store image url and image description. Then insert those values into the images tablestoreimages.php<?phprequire(“dbconnect.php”);//Now create two arrays of values to place in the images table.

$imgURL = array(‘/postcards/punyearth.gif’, ‘/postcards/grebnok.gif’,‘/postcards/sympathy.gif’, ‘/postcards/congrats.gif’);

$imgDESC = array(‘Wish you were here!’, ‘See you soon!’, ‘OurSympathies’, ‘Congratulations!’);

//Loop through the arrays, pulling the location and description text and inserting them into the images table.for ($i=0; $i<4; $i++) {$sql = “INSERT INTO images ( images.img_url , images.img_desc )

VALUES ( ‘$imgURL[$i]’, $imgDESC[$i]’)”;$success = mysql_query($sql, $conn) or die(mysql_error());}Echo “Data entered. . .”;?>

Open Source Programming

Storing Images (cont)

04/21/23 42

It is quite easy for the user to use any e-mail address in the “From” field. This is a bad thing because nasty e-mails can be sent on someone else’s behalf.

In order to prevent such maliciousness, you must first send a confirmation e-mail to the “From” address.

Once you get the confirmation, you know the user entered a good e-mail address, and you can go ahead and send the e-mail.

This will explain with the following screen shots.

Open Source Programming

Getting Confirmation

04/21/23 43Open Source Programming

Getting ConfirmationCreate a PHP program to collect the following information

04/21/23 44Open Source Programming

Getting ConfirmationSend the selected card & message to from address to get confirmation.

04/21/23 45Open Source Programming

Now the user gives confirmation by using the link given below.

Click here to confirm

Can send the mail to address in ‘to’ field, if receives confirmation.

Getting Confirmation

04/21/23 46Open Source Programming

Cookies A cookie is a small piece of information that a Web server can store through your Web browser on to your hard disk when you visit the corresponding site. The Web server can also retrieve this information later when you visit the same site next time.

When you visit a cookie-enabled Web site, you might need to log in to the site or register using a password and other relevant information. This information is stored into a small text file whose maximum size is 4 KB.

This file is referred to as a cookie and contains the relevant user-related information, such as User ID, password, list of pages that the user visited, and the date the user last visited a page.

04/21/23 47Open Source Programming

Why Cookie

Internet is based on Hypertext Transfer Protocol (HTTP), which is a stateless protocol. This implies that once a transaction between the client machine and the Web server is finished, the Web server loses all the memory regarding the transaction. Maintaining the state between your subsequent visits to a Web page prevent loss of sensitive data

04/21/23 48Open Source Programming

Use of Cookies To determine how many users visit the given Web site and how often

For storing details of the users who visit the site or register on the Web site.

Allowing users to customize the interface (such as layout and colors) as per their liking.

To prevent repetitive logins, thus making the login process faster. In addition, since the cookie is stored at the client end, the Web server need not be burdened each time a user needs to log in to the site. The server only needs to authenticate the first-time users.

For tracking a user's path and activities on a given Web site. This feature allows the Web administrators to track miscreants.

For generating individual user profiles. For example, some sites display personalized messages to their users when they log in to the site.

For storing the items selected by the site users in their respective shopping carts.

04/21/23 49Open Source Programming

How does a Cookie work?

Yes ->Updates

cookie value

No -> Creates new cookie

No

04/21/23 50Open Source Programming

How does a Cookie work? When you type the URL of the destination Web site in the

Address bar of your browser, the address is located and if found successfully, a request is sent to the Web server that hosts the site.If the Web server accepts the request, the Web browser at the client end checks for an existing cookie from the given site.

If the cookie is found, the browser sends all the name-value pairs in the cookie to the server as the HTTP header. In addition, the expiration date of the cookie, if any, and a path is also sent to the server along with the name-value pairs.

If the corresponding cookie is not found on the local hard disk, the server is notified about the absence of a cookie. In this case, the server generates a new ID for the client who requested a connection and sends the cookie containing the name-value pair(s) to the requester's Web browser. The browser then stores this cookie on the hard disk of your machine.

04/21/23 51Open Source Programming

Parameters of Cookie

Name – identifies the cookie Value – may be password or some other information related to the connection. Expiration – tells the validity or life span of a cookie in seconds. Path - This parameter is used to limit the scope of a cookie to a certain part of the document tree within the Web server. Domain - This parameter is used to specify the domain for which the cookie is valid. Security parameter – This parameter ensures that the confidential data stored in the cookie is safe from unauthorized access while it travels from the Web server to the client machine

04/21/23 52Open Source Programming

Restrictions of Cookie

1. A cookie can be a maximum size of 4KB only.

2. A domain can stores upto 20 cookies in a

client’s hard disk.

3. At a moment, a client can stores maximum of

300 cookies only.

04/21/23 53Open Source Programming

Cookies in PHPsetcookie(name, value, expiration, path, domain, securemode) –

It is a function in PHP used to create a cookie.

Only the first two parameters are enough to create a cookie.

Can delete a cookie either by using the same function with first parameter or can create with the expiration time as a early time.

Setcookie(“mycookie”,”regno”,time()+60,”/”,”localhost”,0)

Here, the cookie is named as mycookie with value regno, and expiration time of 1 minute, under default path. It is created by the local host for non secure transaction.

04/21/23 54Open Source Programming

Accessing Cookies in PHP

In php, cookies can be accessed in three ways:

1. Use the super global $_COOKIE[‘cookiename’]

2. Can access through the super global cookie array HTTP_VARS_COOKIE[‘cookiename’].

3. Can use a cookie name as a php variable.

04/21/23 55Open Source Programming

Sample cookies program

1. Setcookie.php<?php$username = “jeremys”;setcookie(‘username’, $username, time() + 60 * 60 * 24); // cookie for 1 dayecho $_COOKIE[‘username’] .” created with expiration time of 1 day”;setcookie(‘secondcookie’,$username); //expiration time is Session time.setcookie(‘third’,’sample’,time()+60*60*24*30);//cookie for 30 days//accessing cookie echo $_HTTP_COOKIE_VARS[‘third’]; echo $secondcookie;?>

04/21/23 56

TestCookie.php<html> <head><title>Beginning PHP, Apache, MySQL Web Development</title></head> <body><h1>This is the Test Cookie Page</h1><?phpif ($_COOKIE[‘username’] == “” || $_COOKIE[‘password’] == “”){?>No cookies were set.<br><a href=”setcookie.php”>Click here</a> to set your cookies.<?php }else{ ?>Your cookies were set:<br>Username cookie value: <b><?php echo $_COOKIE[‘username’]; ?></b><br>Password cookie value: <b><?php echo $_COOKIE[‘password’]; ?></b><br><?php} ?> </body> </html>

Open Source Programming

Sample cookies program

04/21/23 57

<?phpif (!isset($_COOKIE['kookie'])) {

$pagecount=0;setcookie("kookie",$pagecount);echo "<font size=8><center>This is the first time u have accessed

this page<br>";echo "<center>A cookie was sent to u & stored in ur

computer<br>";}

else {$pagecount = ++$_COOKIE['kookie'];//setcookie("kookie",$pagecount,time()-10);setcookie("kookie",$pagecount);echo "<center><font size=10 color = red> view count: ".

$_COOKIE['kookie'];}

?> <html><body><b> <center> <font size=8 color=blue> Refresh button will refresh the page and the page count</b></center> </body> </html>

Open Source Programming

Page Count program

04/21/23 58

<?phpecho "<font size=8>";if (isset($_COOKIE["kookie"])) { setcookie("kookie","",time()-10); // deletes cookie echo "Cookie named as <color = red>kookie </color>was deleted"; }else echo "there is no cookie with name 'KOOKIE'";?>

Open Source Programming

Delete Cookie program

04/21/23 59Open Source Programming

Visitor Count program

<?php$visitor_ip = $HTTP_COOKIE_VARS["user_ip"]; $counter = "counter.txt"; $counter_file_line = file($counter); if(!$vistor_ip) { setcookie("user_ip", $REMOTE_ADDR, time()+360000); $counter_file_line[0]++; $cf = fopen($counter, "w+"); fputs($cf, "$counter_file_line[0]"); fclose($cf); } elseif($vistor_ip != $REMOTE_ADDR) { $counter_file_line[0]++; $cf = fopen($counter, "w+"); fputs($cf, "$counter_file_line[0]"); fclose($cf); } ?>

04/21/23 60Open Source Programming

Regular Expression

Regular expression provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. e.g. emailid, webname, username,age,…..

The most important set of regex functions start with preg. These functions are a PHP wrapper around the PCRE library (Perl-Compatible Regular Expressions)

The oldest set of regex functions are those that start with ereg. They implement POSIX Extended Regular Expressions. Portable Operating System Interface [for Unix]

04/21/23 61

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

e.g./foo bar/ #^[^0-9]$# +php+ %[a-zA-Z0-9_-]%

Open Source Programming

PCRE Delimiters

04/21/23 62Open Source Programming

Meta CharactersCharacter

Description Character Description

\ general escape character with several uses

[ Start subpattern

^ start of expression ] end subpattern

$ End of expression ? extends the meaning of

. match any character except newline (by default

* 0 or more quantifier

( Start character class Definition

+ 1 or more quantifier

) End character class Definition

{ start min/max quantifier

| start of alternative branch

} end min/max quantifier

04/21/23 63Open Source Programming

PCRE Functions

ereg_replace — Replace regular expressionereg — Regular expression matcheregi_replace — Replace regular expression case insensitiveeregi — Case insensitive regular expression matchsplit — Split string into array by regular expressionspliti — Split string into array by regular expression case insensitivesql_regcase — Make regular expression for case insensitive match

04/21/23 64

Regular expression for email idereg(‘(^[a-zA-Z0-9_]+@[a-z]+\.+[a-z]{2,5}$)’, $email)

Regular expression for Nameereg(‘(^[a-zA-Z. ]{6,15}$)’, $name)

Regular expression for passwordereg(‘(^[a-z0-9]{4,8}$)’,$password)

Open Source Programming

Samples Expressions

04/21/23 65Open Source Programming

SESSION A normal HTML website will not pass data from one page to another.

(OR)

In other words, all information is forgotten when a new page is loaded. This makes a quite problem for tasks like a shopping cart, which requires data (the user's selected product) to be remembered from the time of selection to billing. (i.e. one page to the next page).

Cookie used for such requirements, however, limitations on cookie size and the number of cookies allowed, and various inconveniences surrounding their implementation, prompted to introduce another solution called as session handling.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.

04/21/23 66

There are two things that the session mechanism must hang onto: the session ID itself and any associated variable bindings.

The session ID is either stored as a cookie on the browser's machine, or it is incorporated into the GET/POST arguments submitted with page requests.

The contents of session variables are stored in special files on the server, one file per session ID: Doing this kind of storage requires the session code to

serialize the data by turning it into a linear sequence of bytes that can be written to a file and read back to recreate the data

It's possible to configure PHP to store the contents of session variables in a server-side database, rather than in files

Open Source Programming

SESSION Mechanism

04/21/23 67Open Source Programming

Storing the Sessions

The session variables are stored on the web server The Path is /var/lib/php/session The file name is the session ID

Eg.sess_076opqrstu56kldr670ndft0op

04/21/23 68

Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.

Session_start() – it is required, for every session’s program.

$_SESSION[‘session_name’] – can access the created sessions through this super global.

isset($_SESSION[‘session_name’]) – used to check the availability of a session.

unset($_SESSION[‘session_name’]) – deletes the session

Session_destroy() – deletes all sessions.

Open Source Programming

Working of a Session

04/21/23 69Open Source Programming

Session Functions

session_start — Initialize session data.session_destroy — Destroys all data registered to a sessionsession_unset — Free all session variablessession_name — Get and/or set the current session namesession_register — Register one or more global variables with the current session. session_destroy — Destroys all data registered to a session. session_id — Get and/or set the current session id.Session_regenerate_id — Update the current session id with a newly generated one session_is_registered — Find out whether a global variable is

registered in a session

Open Source Programming

Start a Session

Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.

bool session_start (void)

Sample program to Start Session: Session_start.php

<?php session_start(); // starts PHP session! echo “The session was started”;?>

This tiny piece of code will register the user's session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user's session.

04/21/23 71Open Source Programming

Create a Session

When you want to store user data in a session use the $_SESSION (super global). This is used for both store and retrieve session data.

$_SESSION[‘session_name’]

Sample program to Create Session: Session_Create.php

<?php session_start(); // starts PHP session! $_SESSION[‘view’] = 1; // creates a new session with name “view”?>

04/21/23 72Open Source Programming

Access Session

Can access the existing sessions through the following super global:

$_SESSION[‘session_name’] – global array

$_HTTP_SESSION_VARS[‘session_name’] – environment variables

Sample program to Access a Session: Session_Access.php

<?php

session_start(); // starts PHP session!

if (isset($_SESSION[‘view’]) // checks the availability

$_SESSION[‘view’] += 1; // access the existing

?>

04/21/23 73Open Source Programming

Delete Session

Imagine that you were running an online business and a user used your website to buy your goods. The user has just completed a transaction on your website and you now want to remove everything from their shopping cart. Can delete the existing session by the function “unset”. The sample program shows it:

Sample program to Delete Session: Session_Delete.php

<?php

session_start(); // starts PHP session! if (isset($_SESSION[‘view’]) // checks the existing {

unset($_SESSION[‘view’]); // deletes the existingecho “The session ‘view’ was deleted”;

}else

echo “no session with name ‘view’”;?>

04/21/23 74Open Source Programming

Delete All Sessions

Session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session. Variables associated with the session, or unset the session cookie.

bool session_destroy (void)

Sample program to Delete all Session: Sessions_Delete.php

<?php session_start(); // starts PHP session

……… //codings session_destroy(); // deletes all sessions?>

Note: destroy will reset your session, so don't call that function unless you are entirely comfortable losing all your stored session data!

04/21/23 75Open Source Programming

Register a Session session_register() accepts a variable number of arguments, any of

which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

bool session_register (mixed $name [,mixed $...])

Sample program to Register a Session: Session_Register.php<?php// Use of session_register() is deprecatedsession_register("barney"); // barney can use later?>

04/21/23 76

The registered session can be used later. It is must to check a session is registered or not, before use it. For that, session_is_registered is used to find whether a global variable is registered in a session

bool session_is_registered (string $name)

Sample program to use Registered Session: Session_Registerd_use.php

<?php // use the registered sesssionsession_start();if (session_is_registered(‘barney’]) echo "barney is ",$_SESSION['barney']++."<br>";else echo “The session ‘barney’ is not yet registered”;?>

Open Source Programming

Use Registered Session

04/21/23 77Open Source Programming

session_name() returns the name of the current session.

bool session_name (string $name)

If name is given, session_name() will update the session name and return the old session name. The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).

Sample program for Session Name: Session_Name.php

<?php// set the session name to WebsiteID $previous_name = session_name("WebsiteID");echo "The previous session name was $previous_name<br />";?>

Session Name

04/21/23 78Open Source Programming

Session id

session_id() is used to get or set the session id for the current session. The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs.

bool session_id (string $id)The session id can be updated by the function

bool session_regenerate_id ([bool $delete_old_session=false])

Sample program for Session Name: Session_Name.php<?phpsession_start();echo "session id is ".session_id()."<br>";echo "barney is ",$_SESSION['barney']++."<br>";?>

04/21/23 79Open Source Programming