Having seen Pablo posts in the Beginner forum, i feel an overwhelming urge to make a tutorial based on his post.
So here goes:
1. benifits of sessions over cookies and why use session and how, vise versa.
2. a simple while loop
3. simple for loop
4. insert/dele/update mySQL by users selection (say checkbox or txt fields)
5. simple date fuction with each explaning what M, m, y, D etc... =
6. explaination of != || && in IF statments
7. code reformat so if they post here it will be proply displayed and easy to see an error, instead of clutter
8. the hint to search forum to see if anyone has had problem before or to search php.net before posting.
On top of these i will also delve into {If Else} statements and a few other things that i feel are important for a newbie to PHP.
So lets start!
Sessions .VS. CookiesWhat are they? Both of these two are methods of storing data for the visitors use (eg, page styles, usernames etc), however the defining difference and the most argued point is:
Cookies are stored on the users computer and can be designated a period of time that the information will exist for.
Eg: The user clicks on a link that changes the background to Green, this link activates a cookies which stores that information into a little file on the users computer. Everytime the user comes back tot he site the background will be green. Now this cookie can be given a time limit, so say the site owner only wants the user to have the background of their choice for 2 hours, the cookie can be set to hold the data for 2 hours then destroy it.
Sessions on the other hand, are server-side, and are usually stored in a /tmp folder under your webviewable folder, and can only hold data for the amount of time that a user has a browser open for. Once all browsers are closed, the session is destroyed.
Now, each of these methods have pro's and cons.
Sessions Pros & ConsP : You can store information server-side so you have almost TOTAL control over it.
P : Gives the user MORE security then cookies, as the the data is only available for a single session.
P : There are no worries if the user has disabled cookies.
C : Information can only be stored for the time that the user has a browser open. Once the browsers are closed the information is lost and needs to be re-entered.
C : Because the information is kept Server-Side, it uses system resources and when inexcess of 2000 sessions are running simultaneously RAM and CPU usage
can be exhausted.
Cookies Pros & ConsP : Information can be stored for long periods of time (including infinite)
P : Information is stored Client-Side, so there is no hinderences on System resources.
C : Cookies can be disabled from the clients machines, meaning NO information can be stored for the user.
C : Exploits have been found where cookies can be altered to use on other websites.. (nasty)
C : Timed cookies can have issues with the Clients time vs the time on the server.
C : if a cookie is stored indefinately on the users computer without their knowledge, anyone who logs onto that computer and that site will see the original users information.
Conclusion on Sessions .VS. CookiesIts really a matter of weighing up what you want, or the purpose of using either. For sites that want to have a user logged in for long periods of time, cookies are the way to go. However, cookies can be disable Client-Side, so the site would be rendered ineffective. Sessions on the other hand can't be forced off by the user as it kept server-side. Sessions are also more secure and cannot be used to exploit other websites.
Personally i use Sessions and find them much easier to use and better for my users.
Using CookiesCookies are relatively easy to Setup using PHP. Scenario's are always good to help.
Say a user has come to my site and i have form that asks what their favourite Cookie is (Chocolate, Almond or Apricot).
The user has chosen Apricot and clicked on the Submit button. Now for each cookie choice a variable has been created out of it. In this scenario the user has chosen Apricot, and for that choice a variable called $Apricot has been created (Fancy that!).
Now to store that information into the database, you would do this:
<?php
setcookie( "Flavour" , $Apricot );
?>
That cookie is now stored on the users computer, and will be used by the website everytime they go there.
Now setcookie has a few options. if you want to further your cookie and put more information into you can.
setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])
"name" : The name of the cookie. 'cookiename' is called as $_COOKIE['cookiename']
"value" : The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']
"expire" : The time the cookie expires. This is a unix timestamp so is in number of seconds since the epoch. In otherwords, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes).
"path" : The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
"domain" : The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to http://www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details.
"secure" : Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0. 0 or 1
Now thats straight out of the PHP.Net manual, but as i have seen not many people know it exists.
Basically what that says is you can further add usefulness and security to your cookie by adding extra string values into it.
Now back to the scenario. Say the web owner only wants the user to have their favourite flavour stored in a cookie for an hour, he can add the expire string into the cookie like so:
<?php
setcookie( "Flavour" , $Apricot , time() +3600 );
?>
Now the users favourite cookie flavour will only be stored for 3600 seconds, or 1 hour, then the cookie will expire and be rendered useless.
Lets say the website owner wants to go one step further and have the cookie only useful in 1 folder of their site, say http://www.website.com/flavours.
The owner would set the cookie like so:
<?php
setcookie( "Flavour" , $Apricot , time() +3600 , "/flavour" );
?>
Now the "path" string is being used and the cookie will only reproduce the information stored in it for that folder.
OK, lets take this to the extreme. the website own now has sub-domains on the site:
http://www.website.com
chip.website.com
nocookies.website.com
The owner, now only wants the cookie to work on chip.website.com, by utilising the domain string, thats not a problem.
<?php
setcookie( "Flavour" , $Apricot , time() +3600 , "/flavour" , "chip.website.com" );
?>
The cookie will now only work at: chip.website.com/flavour
When setting cookies, you MUST enter null values for all the different cookie options eg:
You only want your cookie to last for 10 seconds and in the subdomain chip.website.com, you have to define it like so:
<?php
setcookie( "Flavour" , $Apricot , time() +3600 , [b]""[/b] , "chip.website.com" );
?>
Checking for an Existing Cookie, and Using its DataUsing the scenario above, i will go through how to use the information stored in a cookie, and how to check if a cookie has actually been set.
OK, now the user has selected apricot as their favourite cookie, and the site owner wants their choice to be printed on the page. But a check to see whether the user has chosen a flavour is needed. This is where the If Else statements will be used in conjunction with cookies.
<?php
if ( isset( $_COOKIE['Flavour'] ) )
{
$Cookie_Value = $_COOKIE['Flavour']; // Get Value from Cookie and assign it to a variable
echo $Cookie_Value; // Print this variable onto the page
}
else
{
echo "Html Form with a choice list here"; // Give the Option to choose their flavour
}
?>
The code is fairly self explanitory, If the cookie exists --> create a varible and add the cookies value to it $Cookie_Value --> Print that value onto the page <-- Else --> Give the user a form to choose which flavour they like the best.
At the risk of making this article to long and boring, i've decided to end it here, i hope this has been useful. If you have any questions regarding cookies or would like further explanation on how to use them, just post a reply and i'll edit the tutorial with what you require.
Seeyas.