Thursday, 29 January 2015

Using Cookies with PHP

Using Cookies with PHP

Cookies allow the webmaster to store information about the site visitor on their computer to be accessed again the next time they visit. One common use of cookies is to store your username and password on your computer so you don't need to login again each time you visit a website. Cookies can also store other things such as your name, last visit, shopping cart contents, etc.
The main difference between a cookie and a session is that a cookie is stored on your computer, and a session is not. Although cookies have been around for many years and most people do have them enabled, there are some who do not. Cookies can also be removed by the user at any time, so don't use them to store anything too important.
A cookie is set with the following code:setcookie(name, value, expiration)
<?php  $Month = 2592000 + time();  //this adds 30 days to the current time  setcookie(AboutVisit, date("F jS - g:i a"), $Month); ?>
The above code sets a cookie in the visitor's browser called "AboutVisit". The cookie sets the value to the current date , and set's the expiration to be be in 30 days (2592000 = 60 seconds * 60 mins * 24 hours * 30 days.)
Now let's retrieve the cookie.
<?php 
if(isset($_COOKIE['AboutVisit'])) { 
$last = $_COOKIE['AboutVisit']; 
echo "Welcome back! <br> You last visited on ". $last; 
}  else  {
 echo "Welcome to our site!"; 
}
 ?>
This code first checks if the cookie exists. If it does, it welcomes the user back and tells them when they last visited. If they are new, it skips this and prints a generic welcome message.
TIP: If you are calling a cooking on the same page you plan to set one - be sure you retrieve it first, before you overwrite it!
To destroy the cookie, simply use setcookie again, only set the expiration date to be in the past. This is often done when you 'logout' of a site. Here is an example: 
<?php 
$past = time() - 10; 
//this makes the time 10 seconds ago 
setcookie(AboutVisit, date("F jS - g:i a"), $past);
 ?>

 

An Introduction to the PHP DateInterval Class

An Introduction to the PHP DateInterval Class:
Date and time manipulation is an unavoidable part of programming; there will inevitably be a part of a project that requires a date to be modified. While, on the surface, echoing a date in the future brings a small bit of accomplishment, it can be quickly eradicated when one is tasked with manipulating that date.
Without being aware of the arsenal of tools PHP provides you with regards to working with dates, you might find yourself writing kludges that convert strings into timestamps for various comparisons.
Today we’re going to dissect the PHP DateInterval class, a power tool for dealing with dates in a web app.
But before learning about the DateInterval object, one needs to first understand what an interval is.

What is an Interval?

Simply put, an interval is a duration of time.
When we converse about the topic of duration, we wouldn’t say, "Honey, I’ll be home on Dec 3rd, 2015 15:19pm".
Instead, we would simplify and say "I’ll be home in 5 minutes". Although this is ideal when conversing with another person, this is not so great as a data construct.
So how do we define "in 5 minutes" for a web app?
Fortunately, there’s an ISO for that.
ISO 8601 is the international standard that defines how to use, store, and transfer date, time, and duration information.
The specific string to define durations is an easy-to-remember pattern:
PYMDTHMS
  • P: period
  • Y: years
  • M: months
  • D: days
  • T: time
  • H: hours
  • M: minutes
  • S: seconds
Except for P, each designator is optional.
Immediately preceding each designator is the quantity of time you want to store.
Below is a table showing samples of different date and time ranges:
StringEquivalent to…
P1Y1 year
P1M1 month
P1D1 day
P30D30 days
PT1H1 hour
PT5M5 minutes
PT35S35 seconds
P1Y6M29DT4H34M23S1 year, 6 months, 29 days, 4 hours, 34 minutes, 23 seconds

Creating a DateInterval Object

Now that we understand what an interval is — it’s simply a duration of time — and that ISO 8601 defines our duration’s format, we can start playing around with the PHPDateInterval class.
Let’s define a predictable duration, create a DateInterval object, and output the result to the screen.
We’ll start with "1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds".
$Duration = new DateInterval( "P1Y2M3DT4H5M6S" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 1
[m] => 2
[d] => 3
[h] => 4
[i] => 5
[s] => 6
...
)
You will notice that the constructor for the DateInterval class has parsed your duration and stored the individual values in its own properties. $Duration->ymatches the 1Y from the duration string you passed in.
Let’s try another more practical duration: 1 month. You’ll notice that any undefined durations are automatically defaulted to 0.
$Duration = new DateInterval( "P1M" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 0
[h] => 0
[i] => 0
[s] => 0
...
)
So now we know what’s happening, but what do we really have? What’s so great and tangible about this?
The real benefit to what we have here is that the $Duration object itself represents a duration of time. We don’t need to know a source or destination date; $Duration is simply 1 month.
Note: It’s important to note that creating a DateInterval with 13 months (P13M) will not roll over and provide you with "1 year 1 month".
That makes sense because we don’t have a source or destination date. Imagine the case of 61 days:
  • On October 1, it’s 2 months
  • On December 1, it’s only 1 month and 30 days
  • On February 1, it’s 2 months and 2 days (or only 2 months and 1 day on leap years)

Manipulating Dates with Durations

Durations tame the manipulation of PHP DateTime objects.
The PHP DateTime class has three methods that work with a DateInterval object:
  • add
  • sub
  • diff
Both add and sub will modify a DateTime object by a DateInterval, while diff will compare two DateTime objects and return a DateInterval.
$Now = new DateTime();
echo $Now->format('Y-m-d'); // 2014-06-12

$Duration = new DateInterval('P1M'); // 1 month
$Now->add( $Duration );
echo $Now->format('Y-m-d'); // 2014-07-12

$Duration = new DateInterval('P2M'); // 2 months
$Now->sub( $Duration );
echo $Now->format('Y-m-d'); // 2014-05-12
In the above example you can see how date manipulation becomes much easier and more predictable by using DateInterval objects to modify DateTime objects.
The diff method is just as easy to use, but provides an extra piece of information:total days. This is important because when using the DateTime object to find a difference, we have a source and destination date, and therefore we can reduce the units of time into larger denominations. However, having the total number of days in between is a valuable piece of information.
$Year = new DateInterval('P1Y');
echo $Year->days; // 0

$Date1 = new DateTime();
$Date2 = new DateTime();
$Date2->add( $Year );

$Difference = $Date1->diff( $Date2 );
echo $Difference->days; // 365

Reading Durations and Extracting Intervals

There are inevitably going to be times where you want to extract portions of the stored interval (much the same as you would a date).
The DateInterval class has a handy format method. PHP docs has a table for the format method that is a useful reference.
You use the format method like this:
$Duration = new DateInterval('P345D');
echo $Duration->format('I am %d days'); // I am 345 days
Note: It’s important to note, for those familiar with the strftime method, that the recognized characters are completely different. For example, theDateInterval::format method interprets %a as total days while strftime interprets it as a textual representation of the day (i.e. "Sun").
Oddly enough, DateInterval doesn’t natively have a way to extract the entire interval spec without the zero values. This leaves you with two options:
  1. Extract it with 0 elements, which is perfectly acceptable
  2. Extend the DateInterval class
The second option, extending the DateInterval class, brings upon it’s own difficulties that we won’t touch on here today.
To extract the interval spec with the 0 elements intact, you can use the same format method like so:
$Duration = new DateInterval('P345D');
echo $Duration->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
If you want to confirm the above, simply create a new DateInterval with the result of the first:
$interval_spec = 'P345D';
$Duration1 = new DateInterval( $interval_spec );
echo $Duration1->format('%d'); // 345

$interval_spec = $Duration1->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
$Duration2 = new DateInterval( $interval_spec );
echo $Duration2->format('%d'); // 345
You should now have a grasp on using the PHP DateInterval class, and it’s capabilities.
Hopefully you’re able to apply this current and future web app projects.

How to validate input variables using filter_input function

<?php

/**
 * PHP filter module
 * validate input variables using filter_input() function
 */
//creating simple POST form
$formPOST = <<<FORM
<form method="POST">
Enter <b>email</b> for POST validation: <input type="text" name="email" value="{$_POST['email']}">
<input type="submit" name="validate" value="validate">
</form>
FORM;

//creating simple GET form
$formGET = <<<FORM
<form method="GET">
Enter <b>url</b> for GET validation: <input type="text" name="url" value="{$_GET['url']}">
<input type="submit" name="validate" value="validate">
</form>
FORM;

echo '<center>';
echo $formPOST;
echo $formGET;

//POST validation
if (isset($_POST['validate']) && trim($_POST['email']) != '') {
    //validate POST input
    $validatePOST = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    echo '<div style="background-color:yellow;padding:10px;color:#000;font-size:16px;">POST METHOD</div>';
    if ($validatePOST) {
        echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_POST['email'] . '</b> is a valid email address
          </div>';
    } else {
        echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_POST['email'] . '</b> is  not a valid email address
          </div>';
    }
}
//GET validation
elseif (isset($_GET['validate']) && trim($_GET['url']) != '') {
    //validate GET input
    $validateGET = filter_input(INPUT_GET, 'url', FILTER_VALIDATE_URL);
    echo '<div style="background-color:yellow;padding:10px;color:#000;font-size:16px;">GET METHOD</div>';
    if ($validateGET) {
        echo '<div style="background-color:green;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_GET['url'] . '</b> is a valid URL
          </div>';
    } else {
        echo '<div style="background-color:red;padding:10px;color:#fff;font-size:16px;">
            <b>' . $_GET['url'] . '</b> is  not a valid URL
          </div>';
    }
}
echo '</center>';


?>
Another important Syntax:
$data   = filter_input(INPUT_POST, 'data', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

PHP - cross-site scripting (XSS)

 cross-site scripting (XSS)

Notice that predefining a set of values that are acceptable for a certain parameter is always best. Take an example, we may as well have set the font size in pixels as a parameter and then written that to the document—but then we would have needed a good validation script to prevent end users from sending bad values or even malicious code through the parameter.
Sending malicious code via a parameter without filtering is called cross-site scripting (XSS), and it is one of the big security problems of the Web. You can prevent it by not printing out the values of parameters, and instead using them in comparisons, and by using the filters provided by PHP.

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page.

Types of Cross-Site Scripting

Background

This article describes the many different types or categories of cross-site scripting (XSS) vulnerabilities and how they relate to each other.
Early on, two primary types of XSS were identified, Stored XSS and Reflected XSS. In 2005, Amit Klein defined a third type of XSS, which he coined DOM Based XSS. These 3 types of XSS are defined as follows:

Stored XSS (AKA Persistent or Type I)

Stored XSS generally occurs when user input is stored on the target server, such as in a database, in a message forum, visitor log, comment field, etc. And then a victim is able to retrieve the stored data from the web application without that data being made safe to render in the browser. With the advent of HTML5, and other browser technologies, we can envision the attack payload being permanently stored in the victim’s browser, such as an HTML5 database, and never being sent to the server at all.

Reflected XSS (AKA Non-Persistent or Type II)

Reflected XSS occurs when user input is immediately returned by a web application in an error message, search result, or any other response that includes some or all of the input provided by the user as part of the request, without that data being made safe to render in the browser, and without permanently storing the user provided data. In some cases, the user provided data may never even leave the browser (see DOM Based XSS next).

DOM Based XSS (AKA Type-0)

As defined by Amit Klein, who published the first article about this issue[1], DOM Based XSS is a form of XSS where the entire tainted data flow from source to sink takes place in the browser, i.e., the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser. For example, the source (where malicious data is read) could be the URL of the page (e.g., document.location.href), or it could be an element of the HTML, and the sink is a sensitive method call that causes the execution of the malicious data (e.g., document.write)."

Types of Cross-Site Scripting

For years, most people thought of these (Stored, Reflected, DOM) as three different types of XSS, but in reality, they overlap. You can have both Stored and Reflected DOM Based XSS. You can also have Stored and Reflected Non-DOM Based XSS too, but that’s confusing, so to help clarify things, starting about mid 2012, the research community proposed and started using two new terms to help organize the types of XSS that can occur:
  • Server XSS
  • Client XSS

Server XSS

Server XSS occurs when untrusted user supplied data is included in an HTML response generated by the server. The source of this data could be from the request, or from a stored location. As such, you can have both Reflected Server XSS and Stored Server XSS.
In this case, the entire vulnerability is in server-side code, and the browser is simply rendering the response and executing any valid script embedded in it.

Client XSS

Client XSS occurs when untrusted user supplied data is used to update the DOM with an unsafe JavaScript call. A JavaScript call is considered unsafe if it can be used to introduce valid JavaScript into the DOM. This source of this data could be from the DOM, or it could have been sent by the server (via an AJAX call, or a page load). The ultimate source of the data could have been from a request, or from a stored location on the client or the server. As such, you can have both Reflected Client XSS and Stored Client XSS.
With these new definitions, the definition of DOM Based XSS doesn’t change. DOM Based XSS is simply a subset of Client XSS, where the source of the data is somewhere in the DOM, rather than from the Server.
Given that both Server XSS and Client XSS can be Stored or Reflected, this new terminology results in a simple, clean, 2 x 2 matrix with Client & Server XSS on one axis, and Stored and Reflected XSS on the other axis as depicted here:
Server-XSS vs Client-XSS Chart.jpg

Recommended Server XSS Defenses

Server XSS is caused by including untrusted data in an HTML response. The easiest and strongest defense against Server XSS in most cases is:
  • Context-sensitive server side output encoding
The details on how to implement Context-sensitive server side output encoding are presented in the OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet in great detail.
Input validation or data sanitization can also be performed to help prevent Server XSS, but it’s much more difficult to get correct than context-sensitive output encoding.

Recommended Client XSS Defenses

Client XSS is caused when untrusted data is used to update the DOM with an unsafe JavaScript call. The easiest and strongest defense against Client XSS is:
  • Using safe JavaScript APIs
However, developers frequently don’t know which JavaScript APIs are safe or not, never mind which methods in their favorite JavaScript library are safe. Some information on which JavaScript and jQuery methods are safe and unsafe is presented in Dave Wichers’ DOM Based XSS talk presented at OWASP AppSec USA in 2012: Unraveling some of the Mysteries around DOM Based XSS
If you know that a JavaScript method is unsafe, our primary recommendation is to find an alternative safe method to use. If you can’t for some reason, then context sensitive output encoding can be done in the browser, before passing that data to the unsafe JavaScript method. OWASP’s guidance on how do this properly is presented in the DOM based XSS Prevention Cheat Sheet. Note that this guidance is applicable to all types of Client XSS, regardless of where the data actually comes from (DOM or Server).

Related OWASP Articles

Acknowledgements

A number of us in the industry have been discussing the new terms Server XSS and Client XSS since mid 2012 and we all agree that these terms help bring more clarity and order to the XSS terminology landscape.
  • Dave Wichers
  • Arshan Dabirsiaghi
  • Stefano Di Paolo
  • Mario Heiderich
  • Eduardo Alberto Vela Nava
  • Jeff Williams

<?php
  $search_html = filter_input(INPUT_GET, 's',
                              FILTER_SANITIZE_SPECIAL_CHARS);
  $search_url = filter_input(INPUT_GET, 's',
                             FILTER_SANITIZE_ENCODED);
?>
<form action="index.php" method="get">
  <div>
    <label for="search">Search:</label>
    <input type="text" name="s" id="search" 
           value="<?php echo $search_html;?>">
  </div>
  <div class="bar"><input type="submit" value="Make it so"></div>
</form>
<?php
if(isset($_GET['s'])){
  echo '<h2>You searched for '.$search_html.'</h2>';
  echo '<p><a href="index.php?search='.$search_url.'">Search again.</a></p>';
}
?>

See this filtering example in action. Without the filters, attackers could send parameters like index.php?s="<script>, which would execute third-party code on your website. With filtering, this malicious code is converted to HTML entities.
If you want to use POST as the method to send the data in your form, then the PHP variables will change accordingly to $_POST for the array and INPUT_POSTfor the filter.