PHP Cookies

This item was filled under [ PHP & MySql, References ]

Cookies are just like sessions used for storing data that needs to be remembered and accessed from different files. However, unlike sessions, cookies are saved on the user’s browser ( client-sided ). They can be stored in there for any period unlike sessions ( which are saved for a constant ‘session period’ ). However, they are dependent of the user’s browser and browser settings. If the user chooses to turn off cookies or if the browser simply does not allow cookies, they will not work. But none the less cookies can be quite useful and are used a lot. This is especially because they can save data for ‘unlimited’ time. Just like sessions, each cookie is a sub-variable of an array: $_COOKIES. To create a cookie variable, you simply create a sub-variable of this array. However, this time a function is needed to do so: the function set_cookie.

full function usage


set_cookie( name, value, expire, path, domain, secure, httponly );

basic function usage


set_cookie( name, value, expire);

The arguments of the function are quite a lot, however you usually only need the name, value and expiration data to be set. In fact, only the name must be given for the function to work. The other arguments are optional.

You can as well access any of your cookie variables on any page of your website. They do not need to be ‘activated’ or something, like for sessions, as they’re dependent of the browser. Al though, unlike sessions, cookies need to be created at the very TOP of the page.

Example1.php


<?php
set_cookie( “username”, “Admin”);

// now the cookie can be used anywhere in any file 

// ... rest of your webpage ...

?>

Example2.php


<?php
if(isset($_COOKIES[‘username’]) && !empty($_COOKIES[‘username’])) {

	echo “Welcome back, “.$_COOKIES[‘username’];

}else{

 	echo “You are not logged in.”;

}
?>

You cannot use the set_cookie function after any graphical content ( HTML output ). However you can of course USE your cookies anywhere in your scripts, though they need to be created at the top of a script. For the rest, it can be used just the same way as sessions.

Tagged with: [ , , ]

PHP Sessions

This item was filled under [ PHP & MySql, References ]

Sessions are special kind of variables which are used to store data into that needs to be ‘remembered’ and needs to be accessed from different files. For example: you need to store the username of the logged in user on your website. Once the username is stored into a variable, you do not want the username to be lost when the user reloads the page or goes to another page of your website. Therefore, you can use special variables: sessions. All sessions belong to one array of sessions ( they are sub-variables of the array ): $_SESSION. To create a session variable, you simply create a sub-variable of this array. E.g.:

$_SESSION[‘username’] = “Admin”;

You can access any of your session variables on any page of your website. However, there’s one requirement that has to be fulfilled: you need to activate sessions before you can use them. This can be done by calling the function session_start. This must be done before outputting anything graphical ( e.g. HTML / Text ). For example:

<?php
session_start();

$_SESSION[‘username’] = “Admin”;

//… here goes the rest of your webpage …

echo “Hi there, “.$_SESSION[‘username’].”!”;

?>

Calling the function at the beginning of the file is always good.

Example of usage:

create_session.php

<?php
session_start();

$_SESSION[‘username’] = “Admin”;

?>

Note: You have to run this file to make it create the session.

use_session.php


<?php
session_start();

if(isset($_SESSION[‘username’]) && !empty($_SESSION[‘username’])) {

	$username = $_SESSION[‘username’];

}else{

	$username = “guest”;

}

if($username == “Admin”)) {

	echo “Welcome back, Admin!”;

}else{

	echo “You’re not allowed to be here, “.$username.”!”;

}

?>
Tagged with: [ , ]

PHP Arrays

This item was filled under [ PHP & MySql, References ]

An array is a special kind of ‘variable’. It consists of a group of sub-variables. Each sub-variable has, like any variable, a name ( which is called the key for a sub-variable of an array ) and a value. There is two ways to define an array.

Manner 1

$my_array = array(
                   “sub_var_1” => “value_1”,
                   “sub_var_2” => “value_2”,
                   “sub_var_3” => “value_3”
                 );

Manner 2

$my_array[‘sub_var_1’] = “value_1”;
$my_array[‘sub_var_2’] = “value_2”;
$my_array[‘sub_var_3’] = “value_3”;

However, as you may already have noticed, the first manner is more like a first declaration of the array. The second manner can be used anywhere to alter the array dynamicly or add new sub-variables to it. These sub-variables work just the same way as normal variables ( a name = key, and a value ) and can be used the same way. However this time the ‘prefix’ is different as it’s not just a ‘stand-alone’ variable, but it belongs to an array of sub-variables. A sub-variable of an array is called this way:

$array_name[‘sub_variable_name’]

You can as well have multiple dimensional arrays. For example:

$products = array(
                  1 => array(
                             “name” => “product one”,
                             “price” => “9.95”
                             ),
                  2 => array(
                             “name” => “another product”,
                             “price” => “14.95”
                             )
		);

Now we have 2 sub-variables of the array ( each representing a product’s ID ) which as well have their own array of 2 sub-variables ( for the name and price ). They could as well be created in this manner:

$products[1] = array(“name” => “product one”, “price” => “9.95”);
$products[2] = array(“name” => “another product”, “price” => “14.95”)

Or even:

$products[1][‘name’] = “product one”
$products[1][‘price’] = “9.95”;
$products[2][‘name’] = “another product”;
$products[2][‘price’] = “14.95”;

Which is as well the way how you can use the variables when calling them ( by $array['sub-variable-name'], or a sub-variable of a sub-variable: $array['sub-variable-name1']['sub-variable-name2'] ).

Tagged with: [ , , ]

PHP Functions

This item was filled under [ PHP & MySql, References ]

Functions are used for processes that need to be executed various times. They make it easier, faster and more efficient to get a certain process done. To create your own function, the following structure is used:

function funcName ( ... arguments ... ) {
	... function process code ...
}

You can give the function any name you like as long as there’s not already an existing PHP function with the same name. The arguments of the function are variables where the function needs values for ( data that’s required for your function to run ). For example: a function that retrieves all data of a user would require the user’s ID to be given as argument to the function. Upon calling the function, these arguments should be given values to. A function is called by its name followed by values for the variables that need to be given as arguments to the specific function, between brackets.

funcName( … arguments … );

The function’s return can be of any type ( boolean, String, integer, anything ). However, do notice that returning a value is different from echoing a value. When a value is returned, it can be catched by a variable. When a value is echoed, it automaticly is displayed on the webpage. For example, a function that returns a value can be compared:

$num = 9;
if(sqrt($num) == 3) {
	echo “The number is 9.”;
}

The function sqrt is a premade function that returns the integer square root of the number given as argument to the function.

Tagged with: [ , , ]

PHP While – Do While Loop

This item was filled under [ PHP & MySql, References ]

The While Loop is used to repeat executing a certain code as long as a given condition is (still) true.

while( … condition … ) {
	… execute code …
}

The code between accolades is only executed when the condition between brackets is true ( just like the If Loop) however after it executed the code, it will go back to check the condition again; if it’s still true, it will execute the code again, etc.. This will be repeated until the condition between brackets is no longer true. Only then, it will stop executing the code and continue with the rest of your script ( below the while loop ). Therefore, you should watch out for endless while loops ( which keep repeating themselves for an infinitive time ), for ex.:

$num = 1;
while($num == 1) {
	echo “Num equals 1.”;
}

As num is always equal to 1, this code will be executed forever. When that happens, the rest of your script is no longer executed and the browser will be stuck in executing the while loop script which will cause the browser to crash ( mostly ). A valid example of the use of a while loop could be for ex.:

$num = 1;
while($num <= 10) {
	echo “<p>”.$num.”</p>”;
	$num++;
}

Which shows the value of $num as long as it’s not greater than 10 and then increases it by 1. In other words: it counts to 10.

Now, another form of the while loop is the do while loop. The difference with the while loop is that the code of the do while loop is atleast executed ONCE ( no matter if the condition is true or not ). For example:

$num = 1;
do {
	echo “<p>”.$num.”</p>”;
	$num++;
}while($num <= 0);

Will result in displaying the number 1. However when we’d use the while loop instead, it would result in displaying nothing. The code would not be executed because the variable $num equals 1, which is greater than 0. The condition is false so the code won’t be executed ( not once ) in a while loop. However in a do while loop it executes it at least once but also after that it will check the condition and no longer execute the code when this condition is false.

Tagged with: [ , , , ]