Please style sheet are not equal in internet explorer browser Firefox, Chrome, Safari, Apple and Opera browser please visit this website.

Thank for Visit My Site and Please sent me Shayari, Status and Quotes post request.

PHP - Session management and Cookie, PHP Advanced

 
What is a Cookie?
 
Cookies are pieces of text that are sent to a user's web browser. Cookies can help you create shopping carts, user communities, and personalized sites. It's not recommended that you store sensitive data in a cookie, but you can store a unique identification string that will match a user with data held securely in a database.
 
Take the shopping example. Suppose you assign an identification variable to a user so that you can track what he does when he visits your site. First, the user logs in, and you send a cookie with variables designed to say, "This is Ruchita, and Ruchita is allowed to be here."
 
While Ruchita is surfing around your site, you can say, "Hello, Ruchita!" on each and every page. If Ruchita clicks through your catalog and chooses 14 items to buy, you can keep track of these items and display them all in a bunch when Ruchita goes to the checkout area.
 
 
A cookie is a text-only string that gets entered into the memory of your browser. This value of a variable that a website sets. Web cookies, tracking cookies or just cookies, are parcels of text sent by a server to a Web client (usually a browser) and then sent back unchanged by the client each time it accesses that server. HTTP cookies are used for authenticating, session tracking (state maintenance), and maintaining specific information about users, such as site preferences or the contents of their electronic shopping carts. The term "cookie" is derived from "magic cookie," a well-known concept in UNIX computing which inspired both the idea and the name of HTTP cookies.
 
 
 
Cookies are created in PHP using the setcookie() function. setcookie() takes a number of arguments. The first argument is the name of the cookie (the name part of the name/value pair described earlier). The second is the value part of the name/value pair.
 
The third argument is the optional expiration date of the cookie. The fourth argument specifies the active path for the cookie. The fifth argument is the domain setting and the sixth is the security setting (0 specifies HTTP and HTTPS and 1 specifies HTTPS only).
 
Creating Cookie in PHP
 
Based on the above information we can create a cookie using the following PHP:
 
<?php
setcookie('username', 'Ruchita', time() + 4800);
echo 'Cookie has been set<br>';
?>
 
The above example creates a cookie on the computer system of anyone who loads the page (assuming they have cookies enabled in their browser) containing the name value pair userName=Ruchita'. The cookie will expire 4800 seconds from the time it is created.
 
Reading a Cookie in PHP
 
Given that you've gone to the trouble of writing a cookie it stands to reason you'll probably want to read it back at some point. This is achieved by accessing the $_COOKIE array. The $_COOKIE array is an associative array whereby the name of the cookie provides the index into the array to extract the corresponding value of the name/value pair (for details of PHP arrays read the PHP Arrays chapter of this tutorial).
 
For example we can obtain the value of our userName cookie as follows:
 
<?php
echo 'Reading cookie<br>';
echo 'userName = ' . $_COOKIE['userName'];
?>
 
The above script should generate the following output:
 
Cookie has been set Reading cookie userName = Ruchita
 
Deleting a Cookie
 
Cookies are deleted by calling the setcookie() function with the cookie name, a null for the value and an expiration date in the past. Once again the time() function can be used to calculate an expired date:
 
<?php
setcookie ('userName', '', time() - 4800);
?>
 
Note that if you specified domain and/or path arguments when you created the cookie you must also specify them when you delete the cookie.
 
 
 
What is a PHP Session?
 
What is a PHP Session?
 
PHP Sessions allow web pages to be treated as a group, allowing variables to be shared between different pages. One of the weaknesses of cookies is that the cookie is stored on the user's computer (and by user we mean the person with the browser visiting your web site). This provides the user the ability to access, view and modify that cookie for potentially nefarious purposes.
 
PHP sessions, on the other hand, store only an ID cookie on the user's system which is used to reference the session file on the server. As such, the user has no access to the content of the session file, thereby providing a secure alternative to cookies.
 
PHP sessions also work when the user has disabled the browser's cookie support. In this situation it includes the session ID information in the web page URLs.
 
PHP Session Variables
 
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
 
A PHP session solves this problem by allowing you 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. If you need a permanent storage you may want to store the data in a database.
 
 
 
Using Session management in PHP
 
Creating a PHP Session
 
PHP sessions are created using the session_start() function which should the first function call of the PHP script on your web page (i.e before any output is written to the output stream).
 
The following example demonstrates the creation of a PHP session:
 
<?php
session_start();
$msg="Session Created";
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> PHP Tutorial: Working With Session </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>

<BODY onload="alert('<?php echo $msg;?>');">
<B><?php echo $msg;?></B>
</BODY>
</HTML>
 
img
 
Creating and Reading PHP Session Variables
 
Variables can be assigned to a session using the $_SESSION array. This is a global array that is accessible to all the pages on your web site. This is also an associative array and as such it is possible to access array elements using the variable name as an index.
 
Session variables can be any type of data such as strings, numbers, arrays and objects.
 
Session variables can be defined using a number of mechanisms. Variables can be assigned directly to the $_SESSION array using the assignment operating and variable name:
 
<?php
$_SESSION['userName'] = 'XYZ';
?>
 
Another option is to use the PHP session_register() function. session_register() takes two arguments, the string representing the variable name, and the value to be assigned to the variable:
 
<?php
session_register('username', 'Neeraj');
?>
 
Session variables are accessed by using the variable name as an index key into the $_SESSION array. The session_is_registered() function can also be used to make sure the variable exists before attempting to read the value (which is generally considered to be good practice).
 
For example:
 
<?php
session_start();
?>
<html>
<head>
<title>Simple HTML Form</title>
</head>
<body>
<?php
        if (session_is_registered('userName')
        {
                $_SESSION['userName'] = 'Neeraj';
                echo 'userName = ' . $_SESSION['userName'];
        }
?>

</body>
</html>
 
The resulting output from the above page will read:
 
userName = Neeraj
 
The same PHP code to read the value can be used on any page on your web server to access the current value of the variable.
 
Storing a Session Variable
 
When you want to store user data in a session, use the $_SESSION associative array. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.
 
<?php
session_start();
$_SESSION['num_page_view'] = 1; // store session data

?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP Tutorial :Working with Session</title>
</head>
<body>
<?php
echo "Page Views  = ". $_SESSION['num_page_view']; //retrieve data
?>
</body>
</html>
 
Display:
 
img
 
In this example we learned how to store a variable to the session associative array $_SESSION and also how to retrieve data from that same array.
 
PHP Sessions: Using PHP's isset Function
 
Now that you know can easily store and retrieve data from the $_SESSION array, we can now explore some of the real functionality of sessions. When you create a variable and store it in a session, you probably want to use it in the future. However, before you use a session variable it is necessary that you check to see if it exists already!
 
This is where PHP's isset function comes in handy. isset is a function that takes any variable you want to use and checks to see if it has been set. That is, it has already been assigned a value.
 
With our previous example, we can create a very simple num_page_view counter by using isset to check if the num_page_view variable has already been created. If it has we can increment our counter. If it doesn't exist we can create a num_page_view counter and set it to one. Here is the code to get this job done:
 
<?php
session_start();
if(isset($_SESSION['num_page_view']))
    $_SESSION['num_page_view'] = $_SESSION['num_page_view']+ 1;
else
    $_SESSION['num_page_view'] = 1;
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP Tutorial :Working with Session</title>
</head>
<body>
<?php
echo "Page Views  = ". $_SESSION['num_page_view']; //retrieve data
?>
</body>
</html>
 
The first time you run this script on a freshly opened browser the if statement will fail because no session variable num_page_view would have been stored yet. However, if you were to refresh the page the if statement would be true and the counter would increment by one. Each time you reran this script you would see an increase in view by one.
 
img
 
Cleaning and Destroying your Session
 
Although a session's data is temporary and does not require that you explicitly clean after yourself, you may wish to delete some data for your various tasks.
 
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 shopping_cart.
 
<?php
session_start();
if(isset($_SESSION['shopping_cart']))
    unset($_SESSION['shopping_cart']);
?>
 
You can also completely destroy the session completely by calling the session_destroy function.
 
PHP Code:
 
<?php
session_start();
session_destroy();
?>
 
Destroy will reset your session, so don't call that function unless you are completely happy losing all your stored session data!
 
 
 
PHP Advanced
 
Handling File Upload
 
A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.
 
PHP - File Upload: HTML Form
 
Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our XHTML Tutorial's Form lesson for a more in-depth look at forms.
 
HTML Code:
 
<form enctype="multipart/form-data" 
action="<?php echo $PHP_SELF;?>" method="POST"> <input type="hidden"
name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload:
<input name="uploadedfile" type="file" /><br /> <input type="submit"
value="Upload File" name="submit" /> </form>
 
Here is a brief description of the important parts of the above code:
 
. enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly.

. action="uploader.php" - The name of our PHP page that will be created, shortly.
. method="POST" - Informs the browser that we want to send information to the server using POST.

. input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.

. input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.
 
Save that form code into a file and call it upload.php. If you view it in a browser it should look like this:
 
img
 
The complete example: simple-upload.php
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> PHP Tutorial: Working with File Upload </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">

</HEAD>

<BODY>
<form name= "file_upload_form" 
enctype="multipart/form-data" action="<?php echo $PHP_SELF;?>" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" name="submit" /> </form> <?php if (isset($_POST['submit'])) { echo "<hr><hr>"; $filedir="c:/upload/";// of on Linux [/var/www/upload] etc $upload_file=$filedir.basenam
e($_FILES['uploadedfile']['name']) or die ("Unable to retrieve the file."); $tmp=$_FILES['uploadedfile']['tempname']; echo "<pre><b>"; if (move_uploaded_file($_FILES['uploadedfile']['tempname'],$upload_file)) { echo "\nFile ".$_FILES['uploadedfile']['name']." uploaded successfully"; } else echo "Unable to upload file<b>".$tmp."</b>"; } ?> </BODY> </HTML>
 
When executed the above script should display following output:
 
img
 
Uploaded file in the upload directory:
 
img
 
 
 
PHP E-mail
 
The Mail () Function
 
Many websites offer a way for you to send them an email from a simple form on their site. Providing the form as opposed to simply listing your email address not only looks nicer but also serves two purposes.
 
1. First, the form lets the website owner decide what information it is important to collect and prompts the users to fill in the answers to each of their questions. This way the user doesn't forget to include important information.
 
2. Second, if you list your email directly on your site it can be picked up by bots designed to 'farm' email addresses. What that means for you is SPAM. Nobody likes to have their inbox flooded with SPAM, and using a form can help prevent that.
 
The mail function is phrased as: mail (to, subject, body, headers)
 
An example is:
 
mail ( "user123@mkdtutorials.com", "Thanks for your Feedback", "MKDTutorials Education thanks you for your valuable feedback", " feedback@mkdtutorials.com " )
 
Creating the email form:
 
Source code for email.php
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" 
content="text/html; charset=iso-8859-1" /> <title>PHP Tutorial: Sending Email</title> <script language = "Javascript"
type="text/javascript">
<!-- function emailcheck(email) { var at="@" var dot="." var lat=email.indexOf(at) var lstr=email.length var ldot=email.indexOf(dot) if (email.indexOf(at)==-1){ alert("Invalid E-mail ID") return false } if (email.indexOf(at)==-1 || em
ail.indexOf(at)==0 || email.indexOf(at)==lstr){ alert("Invalid E-mail ID") return false } if (email.indexOf(dot)==-1 || email.indexOf(dot)==0
|| email.indexOf(dot)==lstr){ alert("Invalid E-mail ID") return false } if (email.indexOf(at,(lat+1))!=-1){ alert("Invalid E-mail ID") return false } if (email.substring(lat-1,lat)==dot
|| email.substring(lat+1,lat+2)==dot){ alert("Invalid E-mail ID") return false } if (email.indexOf(dot,(lat+2))==-1){ alert("Invalid E-mail ID") return false } if (email.indexOf(" ")!=-1){ alert("Invalid E-mail ID") return false } return true } function validateForm(){ var to=document.emailform.to var message=document.emailform.message if ((to.value==null)||(to.value=="")){ alert("Please Enter your Email ID") to.focus() return false } if (emailcheck(to.value)==false){ to.value="" to.focus() return false } if((message.value.length<10)|| (message.value=="")) { alert("Your message should contain atleast 10 character") return false } return true } --></script> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; } .style1{ background:#0099FF scroll; color:#FFFFFF; font-weight:bold } --> </style></head> <body> <form name="emailform" method="post"
onsubmit="return validateForm()" action="send-email.php"> <table width="75%" border="0" cellspacing="3" cellpadding="0"> <tr> <th width="12%" align="left" scope="row">TO:</th> <td width="88%"><input type="text" name="to" /></td> </tr> <tr> <th align="left" scope="row">Subject</th> <td><input type="text" name="subject" /></td> </tr> <tr> <th align="left" scope="row">Message:</th> <td><textarea name="message" cols="40"
rows="5" class="style1" id="message"></textarea></td> </tr> <tr> <th scope="row"><input name="submit"
type="submit" class="style1" value="Send Email" /></th> <td><input name="reset" type="reset"
class="style1" value="Clear Form" /></td> </tr> </table> </form> </body></html>
 
The above form should look like the one shown below:
 
img
 
The server side PHP script:
 
send-email.php
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 
1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" /> <title><?php echo $msg;?></title> </head> <body> <?php $msg=""; $send_to=$_POST['to']; $from=$_POST['from']; $subject=$_POST['subject']; $msg=$_POST['message']; $headers = 'From: $from' . "\r\n" . 'Reply-To: $from' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($send_to,$subject,$msg,$headers); echo "Message Sent successfully to
<a href=\"mailto:$send_to\">$send_to</a>"; ?> </body> </html>
 
The $headers parameter in the above script is optional, you can also skip it, e.g.
 
mail(($send_to,$subject,$msg)
 
NOTE:
 
In order to execute this PHP script successfully and send emails through it, SMTP should be configured and other mail options should be configured in the php.ini
 
 
 
Date
 
While PHP's date() function may seem to have an overwhelming amount of options available, isn't it always better to have more choices than not enough? With PHP's date function you format timestamps, so they are more human readable.
 
The PHP date() function formats a timestamp to a more readable date and time.
 
Syntax
 
date(format,timestamp)
 
PHP Date - The Timestamp
 
The date function always formats a timestamp, whether you supply one or not. What's a timestamp? Good question!
 
. Timestamp: A timestamp is the number of seconds from January 1, 1970 at 00:00. Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize.
 
PHP Date - What Time Is It?
 
The date function uses letters of the alphabet to represent various parts of a typical date and time format. The letters we will be using in our first example are:
 
. d: The day of the month. The type of output you can expect is 01 through 31.

. m: The current month, as a number. You can expect 01 through 12.

. y: The current year in two digits ##. You can expect 00 through 99
 
We'll tell you the rest of the options later, but for now let's use those above letters to format a simple date! The letters that PHP uses to represent parts of date and time will automatically be converted by PHP.
 
However, other characters like a slash "/" can be inserted between the letters to add additional formatting. We have opted to use the slash in our example.
 
PHP Code:
 
<?php
echo date("m/d/y");
?>
 
If the 2010 Winter Olympics were just finishing up, you would see something like:
 
Display:
 
img
 
Be sure to test this out on your own PHP enabled server, it's really great to see the instant results available with PHP date!
 
PHP Date - Supplying a Timestamp
 
As our first example shows, the first argument of the date function tells PHP how you would like your date and time displayed. The second argument allows for a timestamp and is optional.
 
This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime. The mktime() function returns the Unix timestamp for a specified date.
 
Syntax
 
mktime(hour,minute,second,month,day,year,is_dst)
 
Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp.

. mktime(hour, minute, second, month, day, year, daylight savings time)
 
PHP Code:
 
<?php
echo "Today is :"
.date('m/d/y')."\n<br>Time in [MM/DD/YY]"; $tomorrow=mktime (0,0,0,date("m"),date("d")+1,date("y")); echo "<br />Tomorrow is :"
.date('m/d/y',$tomorrow)."\n<br>Time in [MM/DD/YY]"; ?>
 
Notice that we used one letter at a time with the function date to get the month, day and year. For example the date("m") will return the month's number 01-12.
 
If we were to run our new script just after the 2010 Winter Olympics our display would look like:
 
Display:
 
img
 
PHP Date - Reference
 
Now that you know the basics of using PHP's date function, you can easily plug in any of the following letters to format your timestamp to meet your needs.
 
Important Full Date and Time:
 
. r: Displays the full date, time and timezone offset. It is equivalent to manually entering date("D, d M Y H:i:s O")
 
Time:
 
. a: am or pm depending on the time . A: AM or PM depending on the time

. g: Hour without leading zeroes. Values are 1 through 12.

. G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.

. h: Hour with leading zeroes. Values 01 through 12.

. H: Hour in 24-hour format with leading zeroes. Values 00 through 23.

. i: Minute with leading zeroes. Values 00 through 59.

. s: Seconds with leading zeroes. Values 00 through 59.
 
Day:
 
. d: Day of the month with leading zeroes. Values are 01 through 31.
. j: Day of the month without leading zeroes. Values 1 through 31
. D: Day of the week abbreviations. Sun through Sat
. l: Day of the week. Values Sunday through Saturday
. w: Day of the week without leading zeroes. Values 0 through 6.
. z: Day of the year without leading zeroes. Values 0 through 365.
 
Month:
 
. m: Month number with leading zeroes. Values 01 through 12
. n: Month number without leading zeroes. Values 1 through 12
. M: Abbreviation for the month. Values Jan through Dec
. F: Normal month representation. Values January through December.
. t: The number of days in the month. Values 28 through 31.
 
Year:
 
. L: 1 if it's a leap year and 0 if it isn't.
. Y: A four digit year format
. y: A two digit year format. Values 00 through 99.
 
Other Formatting:
 
. U: The number of seconds since the Unix Epoch (January 1, 1970)

. O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours
 
We suggest that you take a few minutes to create several timestamps using PHP's mktime function and just try out all these different letters to get your feet wet with PHP's date function.
 
 
 
PHP XML
 
In spite of the growing popularity of XML for storing and exchanging data of nearly any kind imaginable, XML is not well suited to act as a direct replacement for some of its defined subsets or sublanguages, like HTML.
 
This is because XML defines only a standard for structuring data XML itself fails (indeed, by design) to provide any standard for how XML data in the general case should be rendered or displayed to the user.
 
Such concerns, particularly in the case of the World Wide Web and the documents that it contains, are the domain of XML-compliant document type definitions such as Hypertext Markup Language (HTML) or Extensible Hypertext Markup Language (XHTML).
 
Displaying and rendering standards like XHTML govern the ways in which the data and tags that form the structure of compliant XML documents are actually rendered onscreen for readers or World Wide Web users.
 
Parsing XML data with SimpleXML
 
What is SimpleXML?
 
When people ask me "What is SimpleXML?" I often quip, "XML is the solution to all your problems; SimpleXML ensures it isn't the root of your problems!" [Andres P. Ferrando]
 
SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout. Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.
 
SimpleXML converts the XML document into an object, like this:
 
. Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array
 
. Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name
 
. Element Data - Text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found
 
SimpleXML is fast and easy to use when performing basic tasks like:
 
. Reading XML files
. Extracting data from XML strings
. Editing text nodes or attributes
 
However, when dealing with advanced XML, like namespaces, you are better off using the Expat parser or the XML DOM.
 
Note: SimpleXML Parser is available only with PHP 5 and above.
 
Example:
 
simpleXML.php
 
When using SimpleXML parser to parse XML files,
 
simplexml_load_file(file_path) method is used to load the XML file.
 
$emp=simplexml_load_file("employee.xml") or die("Unable to Load XML file");
 
The example given below loads the XML file employee.xml and displays the data of the XML file in Table format:
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" /> <title>
<?php echo "PHP Tutorial: Working With SimpleXML Parser";?></title> </head> <body> <?php $emp=simplexml_load_file("employee.xml")
or die("Unable to Load XML file"); $tbl=<<<TBL <table border="1" cellspacing="1"> <tr bgcolor="blue"> <td> Employee ID</td> <td> Name </td> <td> Age</td> <td> Department </td> <td> Designation</td> <td> Phone No</td> <td> Address</td> </tr> TBL; echo $tbl; if($emp) { foreach($emp->employee as $mkdtutorials) { foreach($mkdtutorials->employee_details as $employee_details) { echo "<tr> \n<td>".$employee_details->emp_id."</td>\n"; echo "<td>".$employee_details->fname."
".$employee_details->lname."</td>\n"; echo "<td>".$employee_details->age."</td>\n"; echo "<td>".$employee_details->department."</td>\n"; echo "<td>".$employee_details->designation."</td>\n"; echo "<td>".$employee_details->phone."</td>\n"; echo "<td>".$employee_details->address."</td>\n"; } } } ?> </body> </html>
 
 
Output:
 
img
 
 
 
PHP Filter
 
A PHP filter is used to validate and filter data coming from insecure sources. To test, validate and filter user input or custom data is an important part of any web application. The PHP filter extension is designed to make data filtering easier and quicker.
 
Why we need to use a Filter?
 
Almost all web applications depend on external input. Usually this comes from a user or another application (like a web service). By using filters you can be sure your application gets the correct input type.
 
You should always filter all external data!
 
Input filtering is one of the most important application security issues. What is external data?
 
. Input data from a form
. Cookies
. Web services data
. Server variables
. Database query results
 
Using Server-side validation with PHP filters
 
Following example demonstrate you how we can use PHP filters to validate and filter user input. This example is same to the example given in chapter 11.2 [PHP email] example, but instead of using JavaScript to validate user input on client side, this example validates the user input with the help of PHP filters and other PHP Built-in functions.
 
You can use a combination of both. Using a combination of both Client-side & Server-side can be helpful when Client browser doesn't have JavaScript enabled or it does not support JavaScript.
 
<?php
$msg="";
$send_to=$_POST['to'];
$from=$_POST['from'];
$subject=$_POST['subject'];
$msg=$_POST['message'];
$headers = 'From: $from' . "\r\n" .
    'Reply-To: $from' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
$to_row="valid";
$from_row="valid";
$msg_row="valid";
$flag=0;
if ((strlen($subject)<=0)||(!$subject))
{
 $subject="No Subject Given";
}
if (strlen($msg)<=0)
{
global $msg_row;
$msg_row="invalid";
global $flag;
$flag=-1;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>PHP Tutorial: Working With Filter</title> <style type="text/css"> <!-- body { margin-left: 0px; margin-top: 0px; } .style1{ background:#0099FF scroll; color:#FFFFFF; font-weight:bold } .invalid{ background-color:#FF0000; color:#FFFFFF; } .valid { background-color:#FFFFFF; color:#FF0000; } --> </style></head> <body> <?php if(isset($_POST['submit'])) { if(!filter_input(INPUT_POST,"send_to",FILTER_VALIDATE_EMAIL)) { global $to_row; $to_row="invalid"; global $flag; $flag=-1; } else { global $to_row; $to_row="valid"; global $flag; $flag=1; } if(!filter_input(INPUT_POST,"from",FILTER_VALIDATE_EMAIL)) { global $from_row; $from_row="invalid"; global $flag; $flag=-1; } else { global $from_row; $from_row="valid"; global $flag; $flag=1; } if($flag>0) { send(); } } ?> <form name="emailform" method="post"
onsubmit="return validateForm()"
action="<?php echo $PHP_SELF;?>"> <table width="75%" border="0" cellspacing="0" cellpadding="0"> <?php if($flag<0) { ?> <tr style="background-color:#CC6600;
color:#FFFFFF; font-weight:bold;
text-align:center"> <td colspan="2">Please Re-Enter the Highlighted fields. </td> </tr> <?php } ?> <tr class="<?php echo $to_row;?>"> <td>TO</td> <td> <input type="text" name="to"
value="<?php echo $send_to;?>" />*</td> <tr class="<?php echo $from_row;?>"> <th align="left" scope="row">From</th> <td><input type="text" name="from" value="<?php echo $from;?>" /> *</td> </tr> <tr> <th align="left" scope="row">Subject</th> <td><input type="text" name="subject" value="<?php echo $subject;?>"/></td> </tr> <tr class="<?php echo $msg_row;?>"> <th align="left" scope="row">Message:</th> <td valign="top">
<textarea name="message" cols="40" rows="5" class="style1" id="message">
<?php echo $msg;?></textarea> *</td> </tr> <tr>
<th scope="row"><input name="submit"
type="submit" class="style1" value="Send Email" /></th> <td><input name="reset" type="reset" class="style1" value="Clear Form" /></td> </tr> </table> </form> </body> </html> <?php function send() { global $send_to; global $subject; global $msg; global $headers; @mail($send_to,$subject,$msg,$headers
) or die("Unable to Send EMAIL <br /> Please check your php.ini"); echo "Message Sent successfully
to <a href=\"mailto:$send_to\">$send_to</a>"; } ?>
 
The above example usage built-in PHP function filter_input to filter user input.
 
Syntax of filter_input
 
filter_input ( int $type , string $variable_name [, int $filter [, mixed $options ]] )
 
$type can have any one of the following values: One of INPUT_GET, INPUT_POST,
 
INPUT_COOKIE, INPUT_SERVER, INPUT_ENV,
 
Output:
 
img
 
On submitting the form in this state
 
img
 
Assignment
 
1. Write a PHP Script to upload images and then display the uploaded image.
 
 
 
 
In this section we will provide you download links for all necessary software, required for learning and development.
 
Apache Download
 
Download Apache from: [http://httpd.apache.org/download.cgi]
 
MySQL Download
 
Download MySQL from MySQL website [http://dev.mysql.com/downloads/mysql/]
 
PHP Download
 
Download PHP from: http://www.php.net/downloads.php
 
Windows Apache+ MySQL +PHP bundles
 
XAMPP
 
Download XAMPP form Apache Friends website
[http://www.apachefriends.org/en/xampp-windows.php]
 
WAMP
 
Download WAMP from WAMPServer website [http://www.wampserver.com/en/download.php]
 
PHPTriad
 
http://sourceforge.net/projects/phptriad/
 
EasyPHP
 
http://sourceforge.net/project/showfiles.php?group_id=14045
 
 
 

SHARE THIS PAGE

0 Comments:

Post a Comment

Circle Me On Google Plus

Subject

Follow Us