This is default featured slide 1 title

Easy to customize it, from your blogger dashboard, not needed to know the codes etc. Video tutorial is available, also a support forum which will help to install template correctly. By DeluxeTemplates.net

This is default featured slide 2 title

Easy to customize it, from your blogger dashboard, not needed to know the codes etc. Video tutorial is available, also a support forum which will help to install template correctly. By DeluxeTemplates.net

This is default featured slide 3 title

Easy to customize it, from your blogger dashboard, not needed to know the codes etc. Video tutorial is available, also a support forum which will help to install template correctly. By DeluxeTemplates.net

This is default featured slide 4 title

Easy to customize it, from your blogger dashboard, not needed to know the codes etc. Video tutorial is available, also a support forum which will help to install template correctly. By DeluxeTemplates.net

This is default featured slide 5 title

Easy to customize it, from your blogger dashboard, not needed to know the codes etc. Video tutorial is available, also a support forum which will help to install template correctly. By DeluxeTemplates.net

Thursday, April 9, 2015

Cookies and Sessions

The ‘Statelessness’ Problem

The web is ‘statelessness’. That is after a web server has ‘served’ a page your connection to the server is closed and it no longer cares you exist. Knowing who is connected to a page is obviously useful for web applications. For example, it allows pages to be personalized and is essential for features such as shopping carts.
The ‘statelessness’ can be overcome by making users register and then passing information from one page to another using a URL query string. This method is unsatisfactory for the user, insecure and time consuming to implement (as every page in your web site would need some $_GET or $_REQUEST variable handling)
Two alternative approaches are cookies and sessions.

Cookies

Cookies work by storing data on the user’s machine when they visit a page. That is the data is stored on the user’s own machine, the web server writes data to the client computer via the browser. As this is done by the browser the user can change their browser settings to block cookies and stop a web server writing data to it. Cookies will only therefore work on browsers that have cookies enabled. Most web users work with cookies ‘on’ but be aware they can and are switched off by some users. As such when using cookies you will need to test for their presence.
Testing for Cookies
To define a cookie use setcookie(). You must ensure that this function is before any output from a script as cookies are set via the HTTP headers of a HTML document. Any output here includes whitespacing. If setcookie() appears after any output then an error will occur.
Warning: If you place setcookie() after any outputs from echo or print it will fail. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).
This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

The setcookie() function and $_COOKIE

setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);
CookieName:
The name of the cookie.
CookieValue:
The value of the cookie. This value is stored on the clients computer; do not store sensitive information.
CookieExpireTime:
The time the cookie expires in seconds. Thus ‘time()+60*60*24*10’ will set the cookie to expire in 10 days. If not set, the cookie will expire at the when the browser closes (end of the session).
Path:
directory under web server this cookie is for. Default is to the directory of the requested page.
Doman:
The domain name this cookie can be used under. Default is the domain of the requested page. The domain must have two '.' in it, so if you decide to specify you're top level domain, you must use ".mydomain.com".
Secure:
If set to '1', indicates that the cookie should only be transmitted over a secure HTTPS connection.

Please note that cookies will not become visible until the next loading of a page that the cookie should be visible for. To call the cookie use $_COOKIE['mycookie'].


setcookie("visitor", $_POST[‘login’]);

The above code creates a cookie ‘visitor’ to hold a login value. No expiration time is set so the cookie will expire when the browser is closed.

setcookie("count", $count, time()+600);

The above code creates a cookie ‘count’. This takes it values from a variable $count. The expiration time is 600 seconds (10 minutes) from the current time.
Use isset() in an if condition to check for the presence of a cookie.

if(isset($_COOKIE["count"])) {
..
}

Tip: When changing the value of an existing cookie use setcookie() to re-set/re-create the cookie with the same name.

Removing Cookies

Cookies will expire on the date set via setcookie(). If you do not set an expiry that then when the browser is closed the cookies are removed. To remove a cookie via your code you need to re-set the cookie with a negative expiry date ie a date in the past.

setcookie("myname", '', time()-600);

Cookie Settings in Browsers

Whether cookies will work with your application depends on whether the client browser will accept the cookie. The user can choose to reject cookies through settings in the browser.
For example with to change cookie support in Internet Explorer select Tools > Internet Options and choose the Privacy tab.
Use the slider to change the privacy setting. If this slider is moved to the top the setting is ‘Block All Cookies’.
In Mozilla Firefox similar settings are accessed by selecting Tools > Options and choosing the Privacy tab. This has a cookie tab where cookies can be blocked.

Working with Sessions

Sessions can be used as an alternative to cookies. Whilst cookies are stored on the client machines hard disk, a session is generally stored on the web server.
A session is available as long as the browser is opened.

Every page that makes use of sessions MUST begin with the following.

<?php
session_start();
?>

If no session exists this commands starts one, if one is already started this command recalls values in this session such that they can be displayed via the $_SESSION global array.
Session variables are set using the normal variable assignment method.

$_SESSION['user'] = $_POST['userID'];

To remove session variables use:

<?php
session_start();
unset($_SESSION['user']);
?>

Sessions versus Cookies

As the end result is the same for the user which is the better option? Sessions are generally considered to be more secure as the key data is stored on the server. They also allow you to store more data. Cookies on the other hand require less of the server. However, the irony is that by default, sessions actually use cookies. That is they store a session ID as a cookie on the browser. This session ID then relates to a value stored on the server.

Source : http://www.mustbebuilt.co.uk/php/cookies-and-sessions/

INSERT, UPDATE and DELETE with mysqli

Three SQL commands - INSERT, UPDATE and DELETE - usually form the basis of any content management system.
These SQL commands are all going to be the recipients of user derived data most often from HTML forms but possibly through querystrings.
As such the mysqli prepare statement with its separation of the query from the data is a good secure approach to take.

INSERT


Assuming a HTML form of method $_POST with the appropriate fields in it the following would insert a new record in a table called 'movies'.

$stmt = $mysqli->prepare("INSERT INTO movies(filmName,
filmDescription,filmImage,filmPrice,filmReview) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssdi', $_POST['filmName'],
$_POST['filmDescription'],
$_POST['filmImage'],
$_POST['filmPrice'],
$_POST['filmReview']);
$stmt->execute();
$stmt->close();

Notice the use of the flags 'sssdi' in the bind_param() method and the position placeholders (?) in the prepare statement.
For a reminder as to how these relate take at look at this interactive example.

Getting Auto Increment Key Values with insert_id

When using SQL INSERT you may have set up your database table with an auto_increment field to ensure your primary keys remain unique. You may need to know what this value is as soon as the database creates it. In this scenario the prepare statement insert_id property can be used. Create a variable from this property after the execute() method but before the close() method of the prepare statement. An amended version of the above that captures the new primary key value would look as follows:

$stmt = $mysqli->prepare("INSERT INTO movies(filmName,
filmDescription,filmImage,filmPrice,filmReview) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssdi', $_POST['filmName'],
$_POST['filmDescription'],
$_POST['filmImage'],
$_POST['filmPrice'],
$_POST['filmReview']);
$stmt->execute();
$newId = $stmt->insert_id;
$stmt->close();

UPDATE

An UPDATE example would work in the same fashion this time the SQL has a WHERE clause to identify which record to update.

$stmt = $mysqli->prepare("UPDATE movies SET filmName = ?,
   filmDescription = ?,
   filmImage = ?, 
   filmPrice = ?, 
   filmReview = ? 
   WHERE filmID = ?");
$stmt->bind_param('sssdii',
   $_POST['filmName'],
   $_POST['filmDescription'],
   $_POST['filmImage'],
   $_POST['filmPrice'],
   $_POST['filmReview'],
   $_POST['filmID']);
$stmt->execute();
$stmt->close();

DELETE

Finally a DELETE statement. Like the UPDATE a WHERE clause ensures the correct record is removed.

$stmt = $mysqli->prepare("DELETE FROM movies WHERE filmID = ?");
$stmt->bind_param('i', $_POST['filmID']);
$stmt->execute();
$stmt->close();


Source : http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-mysqli/

Select Statements with PDO

Creating a Simple SELECT Query

Once you have created a PDO you can begin querying the database. There are two ways queries can be created – firstly through the query() method and secondly through the prepare() method.
The prepare() method allows for prepare statements with all the security benefits that entails.

However, for our first simple SELECT we'll use the query() method as no parameter are been sent into it. To keep things really simple we'll also only extract one record.


require_once('includes/conn.inc.php');
$sql= "SELECT filmName, filmDescription FROM movies WHERE filmID = 10";
$stmt = $pdo->query($sql);
$row =$stmt->fetchObject();
echo $row->filmName;
echo $row->filmDescription;


The above uses the PDO 'object' style syntax by calling the PDO fetchObject() method. Each field value retrieved from the database can be referenced by the $row variable using PHP object arrow syntax (->)
If you prefer you can use associate array syntax which you may be familiar with from older database connection techniques in PHP.
To use an associate array we would change the above to:



require_once('includes/conn.inc.php'); 
$sql= "SELECT filmName, filmDescription FROM movies WHERE filmID = 10";
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['filmName'];
echo $row[filmDescription];


In the above the values are retrieved using the square brackets of the associate array.

Queries that extract multiple rows

The above queries use the primary key of our test data table to only extract one record. If we need more that one record then we could do the following:

require_once('includes/conn.inc.php');
$sql = "SELECT * FROM movies";

Here we use the query() method of the PDO to create an array which is looped to extract the data as follows:



foreach($pdo->query($sql) as $row){
    echo "<li>{$row['filmName']}</li>";
}

This is a cheap and cheerful approach for various reasons - for example it makes it more difficult to ascertain how many records have been retrieved.
Using prepare()

The PDO prepare() and execute() methods are considered a more secure approach especially with queries using values from forms or querystrings. You will be familiar with this approach if you have read the section on mysqli.

$sql= "SELECT filmID, filmName, filmDescription, filmImage, filmPrice, filmReview FROM movies WHERE filmID = :filmID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmID', $filmID, PDO::PARAM_INT);
$stmt->execute();



Look on line 1 above (you may need to scroll to the right). Notice the use of the : (colon) in the SQL statement before :filmID. This equates to the parameter created and bound to that value via the PDO bindParam() method. The colon performs the same role as using the ? (question mark) position placeholders with mysqli.

The bindParam() takes three values:

Syntax
Parameter name, Parameter value, Parameter type

In the example above an integer value was used and such the parameter type was PDO::PARAM_INT. The following binds a string parameter.

$stmt->bindParam(':country', $country, PDO::PARAM_STR); 

Note: For numbers/floats and dates use the PDO::PARAM_STR binding type.

The Array Approach

Once executed the values from the query can be retrieved a number of ways. An associate array can be retrieved using the fetchAll() method.

require_once('includes/conn.inc.php');
$sql= "SELECT * FROM movies";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

The $result variable contains an array of all the result's rows and can be looped:


foreach($result as $row){
    echo "<li>{$row['filmName']}</li>";
}

The total number of records returned could be calculated the PHP count() method as $result is an array.

$total = count($result);

The Object Approach

Alternatively we could achieve the same as the above but with using Object syntax. First build and execute the query.

require_once('includes/conn.inc.php');
$sql= "SELECT * FROM movies";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$total = $stmt->rowCount();

The above uses the rowCount() method of the PDO statement to give us a record count.
To output the values held in the PDO statement we could do the following:

while ($row = $stmt->fetchObject()) {
    echo "<li>{$row->filmName}</li>";
}

If your SQL only extracts only one value then no need for the while loop.


$sql= "SELECT filmID, filmName, filmDescription, filmImage, filmPrice, filmReview FROM movies WHERE filmID = :filmID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmID', $filmID, PDO::PARAM_INT);
$stmt->execute();
$obj = $stmt->fetchObject();
echo $obj->filmName;

Notice the use of the object arrow (->) syntax to reference the values.

Search / Results Page

To build a simple search / results page we would need a user input - in this example a GET from a form. If you would like to use the SQL LIKE statement and its wildcards, then we need to concatenate % (percentages) to the variable to be used in the bindParam() method. Note that we will not need to put the variable in quotes in the SQL, as the bindParam() method and the use of PDO::PARAM_STR to declare the data type will resolve that for us.

if(isset($_GET['filmName'])){
    $filmName = "%".$_GET['filmName']."%";
}else{
    $filmName = "none";
}
$sql= "SELECT * FROM movies WHERE filmName LIKE :filmName";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmName', $filmName, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();

... and then to output.


while ($row = $stmt->fetchObject()) {
   echo $row->filmName;
}

Source : http://www.mustbebuilt.co.uk/php/select-statements-with-pdo/

INSERT, UPDATE and DELETE with PDO

We have seen how to use mysqli to Insert, Update and Delete - now lets do the same for PDO.

INSERT

Assuming a HTML form of method $_POST with the appropriate fields in it, the following would insert a new record in a table called movies. Note that in a real world example all the variables from $_POST would be validated before been sent to the query.

$sql = "INSERT INTO movies(filmName,
            filmDescription,
            filmImage,
            filmPrice,
            filmReview) VALUES (
            :filmName,
            :filmDescription,
            :filmImage,
            :filmPrice,
            :filmReview)";
                                          
$stmt = $pdo->prepare($sql);
                                              
$stmt->bindParam(':filmName', $_POST['filmName'], PDO::PARAM_STR);      
$stmt->bindParam(':filmDescription', $_POST['filmDescription'], PDO::PARAM_STR);
$stmt->bindParam(':filmImage', $_POST['filmImage'], PDO::PARAM_STR);
// use PARAM_STR although a number 
$stmt->bindParam(':filmPrice', $_POST['filmPrice'], PDO::PARAM_STR);
$stmt->bindParam(':filmReview', $_POST['filmReview'], PDO::PARAM_STR);  
                                      
$stmt->execute();

 
Notice the use of colons as position placeholder for the bindParam() methods.

Getting Auto Increment Key Values with lastInsertId()

When using SQL INSERT you may have set up your database table with an auto_increment field to ensure your primary keys remain unique. You may need to know what this value is as soon as the database creates it. In this scenario the PDO method lastInsertId() can be used. Create a variable from this property after the execute() method as follows:

$stmt->execute();
$newId = $pdo->lastInsertId();




UPDATE

An UPDATE example would work in the same fashion this time the SQL has a WHERE clause to identify which record to update.

$sql = "UPDATE movies SET filmName = :filmName,
            filmDescription = :filmDescription,
            filmImage = :filmImage, 
            filmPrice = :filmPrice, 
            filmReview = :filmReview 
            WHERE filmID = :filmID";
$stmt = $pdo->prepare($sql);                                 
$stmt->bindParam(':filmName', $_POST['filmName'], PDO::PARAM_STR);      
$stmt->bindParam(':filmDescription', $_POST['$filmDescription'], PDO::PARAM_STR);   
$stmt->bindParam(':filmImage', $_POST['filmImage'], PDO::PARAM_STR);
// use PARAM_STR although a number 
$stmt->bindParam(':filmPrice', $_POST['filmPrice'], PDO::PARAM_STR);
$stmt->bindParam(':filmReview', $_POST['filmReview'], PDO::PARAM_STR);  
$stmt->bindParam(':filmID', $_POST['filmID'], PDO::PARAM_INT);  
$stmt->execute();

DELETE

Finally a DELETE statement. Like the UPDATE a WHERE clause ensures the correct record is removed.

$sql = "DELETE FROM movies WHERE filmID =  :filmID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmID', $_POST['filmID'], PDO::PARAM_INT);  
$stmt->execute();

That covers the basics of getting started with PDO.


Source : http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/