PHP HEADER()

Standard

the header() method sends a raw http header
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
it is an error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called
the same problem exists when using a single PHP/HTML file

<html>
<?php
// this will give an error, because the <html> tag is placed before the header() call
header(‘Location: http://www.example.com/&#8217;);
exit;
?>

there are two special-case header calls:

header(“HTTP/1.0 404 Not Found”);

the first is a header that starts with the string “HTTP/”, which will be used to figure out the HTTP status code to send
for example, if APACHE has been configured with a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code

header(“Location: http://www.example.com/&#8221;);
the second special case is the “Location:” header, that sends this header back to the browser and also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set

per fare un redirect PHP è necessario utilizzare la funzione header()
questa è una funzione nativa del PHP, mediante la quale possiamo inviare intestazioni HTTP al client che sta visitando la nostra pagina web, è possibile impostare una nuova location verso la quale reindirizzare la navigazione dell’utente, in poche parole possiamo far “rimbalzare” l’utente portandolo su un’altra pagina del nostro o di un altro sito

effettuare un redirect automatico dell’utente verso una diversa pagina del sito o di un sito differente
// redirect verso pagina interna
header(“location: /nuova-pagina.php”);

// redirect verso una risorsa esterna al sito
header(“location: http://www.sito.it/pagina.php&#8221;);

l’uso di questo codice deve essere fatto prima di aver generato alcun output, altrimenti l’interprete PHP restituirà un errore
echo “print it before the redirect”;
header(“location: http://www.sito.it/pagina.php&#8221;);
// error

dopo l’uso della funzione header(), bisogna inserire un exit se all’interno dello script c’è altro codice da eseguire dopo quello che fa il redirect

if ($utente_loggato == false) {
header(“location: http://www.sito.it/pagina.php&#8221;);
exit;
}
// segue altro codice php

PHP IF($VARIABLE)

Standard

this construct tests to see if $variable evaluates to any “truthy” value
it can be a boolean TRUE, or a non-empty, non-NULL value, or non-zero number

list of boolean evaluations
var_dump((bool) “”);
// bool(false)

var_dump((bool) 1);
// bool(true)

var_dump((bool) -2);
// bool(true)

var_dump((bool) “foo”);
// bool(true)

var_dump((bool) 2.3e5);
// bool(true)

var_dump((bool) array(12));
// bool(true)

var_dump((bool) array());
// bool(false)

var_dump((bool) “false”);
// bool(true)

var_dump((bool) false);
// bool(false)

if($variable) is not appropriate to use when testing if a variable or array key has been initialized
if it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable

PHP SESSIONS

Standard

a session is a way to store information (in variables) to be used across multiple pages
this information is not stored on the users computer like a cookie

when you work with an application, you open it, do some changes, and then you close it: this is a session
the local computer knows who you are, when you start the application and when you end
however, on the internet the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state

session variables solve this problem by storing user information to be used across multiple pages (like username, favorite color, etc)
by default, session variables last until the user closes the browser and hold information about one single user, make them available to all pages in an application (if is needed a permanent storage, store data in a database)

SESSION_START()
a session is started with the session_start() function
session variables are set with the PHP global variable: $_SESSION

in the page demo_session1.php is started a new PHP session, with the setting of some session variables
<?php
// session_start() function must be the very first thing in your document, before any HTML tags
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// set session variables
$_SESSION[“favcolor”] = “orange”;
$_SESSION[“favanimal”] = “dog”;
echo “session variables are set.”;
?>

</body>
</html>

from another page, called demo_session2.php, it’s possible to access the session information we set on the first page, demo_session1.php
session variables are not passed individually to each new page, instead they are retrieved from the session opened at the beginning of each page with session_start()
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// echo session variables that were set on previous page
echo “favorite color is ” . $_SESSION[“favcolor”] . “<br>”;
echo “favorite animal is ” . $_SESSION[“favanimal”];
?>

</body>
</html>

another way to show all the session variable values for a user session is to run the following code
<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

***
how does it work? how does it know it’s me?
most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12
when a session is opened on another page, it scans the computer for a user-key
if there is a match, it accesses that session, if not, it starts a new session
***

to change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION[“favcolor”] = “yellow”;
print_r($_SESSION);
?>

</body>
</html>
// outputs Array ( [favcolor] => yellow )

SESSION_UNSET() and SESSION_DESTROY()
to remove all global session variables and destroy the session, use session_unset() and session_destroy()
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>

PHP COOKIES

Standard

a cookie is often used to identify a user
it is a small file that the server embeds on the user’s computer, so each time the same computer requests a page with a browser, it will send the cookie too
PHP can create and retrieve cookie values

SETCOOKIE()
the syntax is:
setcookie(name, value, expire, path, domain, secure, httponly)
only the name parameter is required, all other parameters are optional

the code below creates a cookie named “user” with the value “john”
the cookie will expire after 30 days (86400 * 30)
“/” means that the cookie is available in entire website (otherwise, select a specific directory)
to retrieve the value of the cookie “user” is used the global variable $_COOKIE

// the setcookie() function must appear BEFORE the <html> tag
<?php
$cookie_name = “user”;
$cookie_value = “john”;
// the value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead)
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”);
// 86400 = 1 day
?>

<html>
<body>

<?php
// the isset() function checks if the cookie has been set
if(!isset($_COOKIE[$cookie_name])) {
echo “cookie named ‘” . $cookie_name . “‘ is not set”;
} else {
echo “cookie ‘” . $cookie_name . “‘ is set<br>”;
echo “value is: ” . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

to modify a cookie, just set (again) the cookie using the setcookie() function:
<?php
$cookie_name = “user”;
$cookie_value = “jack”;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”);
?>

<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo “cookie named ‘” . $cookie_name . “‘ is not set”;
} else {
echo “cookie ‘” . $cookie_name . “‘ is set<br>”;
echo “value is: ” . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

to delete a cookie, use the setcookie() function with an expiration date in the past
<?php
// set the expiration date to one hour ago
setcookie(“user”, “”, time() – 3600);
?>
<html>
<body>

<?php
echo “cookie ‘user’ is deleted.”;
?>

</body>
</html>

the code below is a small script that checks whether cookies are enabled
try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable
<?php
setcookie(“test_cookie”, “test”, time() + 3600, ‘/’);
?>

<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo “cookies are enabled.”;
} else {
echo “cookies are disabled.”;
}
?>

</body>
</html>

PHP FILE HANDLING

Standard

file handling is when a web application need to open and process a file
PHP has builtin functions for creating, reading, uploading, and editing files

READFILE()
this function reads a file and writes it to the output buffer

webdictionary.txt is stored on server
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

the PHP code to read the file and write it to the output buffer, returning the number of bytes read on success at the end
echo readfile(“webdictionary.txt”);
// output
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language236

FOPEN()
this is a better method to open file because it gives more options than readfile()
fopen(filename, option)
the first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened
$myfile = fopen(“webdictionary.txt”, “r”) or die(“unable to open file”);
the die() function generates a message if the fopen() function is unable to open the specified file

the file can be opened in the following modes
r open a file for read only, file pointer starts at the beginning of the file
w open a file for write only, erases the contents of the file or creates a new file if it doesn’t exist, file pointer starts at the beginning of the file
a open a file for write only, the existing data in file is preserved, file pointer starts at the end of the file, creates a new file if the file doesn’t exist
x creates a new file for write only, returns FALSE and an error if file already exists
r+ open a file for read/write, file pointer starts at the beginning of the file
w+ open a file for read/write, erases the contents of the file or creates a new file if it doesn’t exist, file pointer starts at the beginning of the file
a+ open a file for read/write, the existing data in file is preserved, file pointer starts at the end of the file, creates a new file if the file doesn’t exist
x+ creates a new file for read/write, returns FALSE and an error if file already exists

FREAD()
this function reads from an open file
fread(filename, bytes)
the first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read

to the “webdictionary.txt” file to the end
fread($myfile,filesize(“webdictionary.txt”));

FCLOSE()
this function is used to close an open file
fclose(filename)
it’s a good practice to close all files after you have finished with them (running opened files take up resources on the server)
fclose() requires the name of the file (or a variable that holds the filename)
fclose($myfile);

FGETS()
the fgets() function is used to read a single line from a file
fget(filename)
after a call to the fgets() function, the file pointer has moved to the next line
echo fgets($myfile);
// outputs the first line of the file

FEOF()
this checks if the “end-of-file” (EOF) has been reached
it’s useful for looping through data of unknown length
feof(filename)
this code reads the file line by line, until end-of-file is reached
$myfile = fopen(“webdictionary.txt”, “r”) or die(“unable to open file”);
while(!feof($myfile)) {
echo fgets($myfile);
}
// outputs one line until end-of-file
fclose($myfile);

FGETC()
the fgetc() function is used to read a single character from a file
after a call to the fgetc() function, the file pointer moves to the next character
fgetc(filename)
this code reads the file character by character, until end-of-file is reached
$myfile = fopen(“webdictionary.txt”, “r”) or die(“unable to open file”);
while(!feof($myfile)) {
echo fgetc($myfile);
}
// outputs one character until end-of-file
fclose($myfile);

*** the last two code snippet give the same output: to see the difference in working, add a breakline after fgets() or fgetc() function ***

PHP FILE CREATION
the fopen() function is also used to create a file: in PHP, a file is created using the same function used to open files
using fopen() on a file that does not exist, will create it, given that the file is opened for writing (w) or appending (a)

the code below creates a new file called “testfile.txt” and the file will be created in the same directory where the PHP code resides
$myfile = fopen(“testFile.txt”, “w”)

to create a file it’s compulsory to have the right permissions
if there are errors when trying to get this code to run, check if the PHP file has the grant access to write information to the hard drive

FWRITE()
it is used to write to a file
fwrite(filename, stringtobewritten)
the first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written
$myfile = fopen(“testFile.txt”, “w”) or die(“unable to open file”);
$txt = “hello\n”;
fwrite($myfile, $txt);
$txt = “john\n”;
fwrite($myfile, $txt);
fclose($myfile);

// output
the code have written the file twice, sending “hello, and then “john”
testFile.txt will look as
hello
john

PHP OVERWRITING
if the testFile.txt is opened for writing, all its existing data will be ERASED and it’s started an empty file
$myfile = fopen(“testFile.txt”, “w”) or die(“unable to open file”);
$txt = “hi\n”;
fwrite($myfile, $txt);
$txt = “brian\n”;
fwrite($myfile, $txt);
fclose($myfile);

// output
now, testFile.txt contains
hi
brian

PHP FILE UPLOAD
firstly, configure the php.ini file to allow file uploads
the file_uploads directive has to be setted equal to On
file_uploads = On

then, create an HTML form that allow users to choose the image file they want to upload
<!DOCTYPE html>
<html>
<body>

<form action=”upload.php” method=”post” enctype=”multipart/form-data”>
select image to upload:
<input type=”file” name=”fileToUpload” id=”fileToUpload”>
<input type=”submit” value=”upload image” name=”submit”>
</form>

</body>
</html>

these are the rules to follow:
– form uses method=”post
– form needs the attribute: enctype=”multipart/form-data“, that specifies which content-type to use when submitting the form
without these requirements the file upload will not work
– the type=”file” attribute of the <input> tag shows the input field as a file-select control, with a “browse” button next to the input control
– the action=”script.php“, which is the script the form above sends data to

the upload.php file contains this code is the script PHP to which the actual form is linked and it will be something like this
$target_dir = “uploads/”;
$target_file = $target_dir . basename($_FILES[“fileToUpload”][“name”]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// check if image file is an actual image or fake image
if(isset($_POST[“submit”])) {
$check = getimagesize($_FILES[“fileToUpload”][“tmp_name”]);
if($check !== false) {
echo “file is an image – ” . $check[“mime”];
$uploadOk = 1;
} else {
echo “file is not an image”;
$uploadOk = 0;
}
}

// WHERE
$target_dir specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet, but it will be useful
$imageFileType holds the file extension of the file
the directory called uploads in the directory where upload.php resides and where the uploaded files will be saved, has to exist

after the first upload, when a file is uploaded it has to be checked if it already exists
if it does, an error message is displayed, and $uploadOk is set to 0
// check if file already exists
if (file_exists($target_file)) {
echo “error, file already exists”;
$uploadOk = 0;
}

it is also useful to limit uploaded files size
the file input field in our HTML form above is named fileToUpload
if the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0
// check file size
if ($_FILES[“fileToUpload”][“size”] > 500000) {
echo “error, your file is too large”;
$uploadOk = 0;
}

then, it can also possible to choose what file types can be uploaded
for example, this code only allows users to upload JPG, JPEG, PNG, and GIF files
all other file types gives an error message before setting $uploadOk to 0
// allow certain file formats
if($imageFileType != “jpg” && $imageFileType != “png” && $imageFileType != “jpeg”
&& $imageFileType != “gif” ) {
echo “only JPG, JPEG, PNG & GIF files are allowed”;
$uploadOk = 0;
}

the complete upload.php file will look something like this
$target_dir = “uploads/”;
$target_file = $target_dir . basename($_FILES[“fileToUpload”][“name”]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// check if image file is a actual image or fake image
if(isset($_POST[“submit”])) {
$check = getimagesize($_FILES[“fileToUpload”][“tmp_name”]);
if($check !== false) {
echo “file is an image – ” . $check[“mime”];
$uploadOk = 1;
} else {
echo “file is not an image”;
$uploadOk = 0;
}
}
// check if file already exists
if (file_exists($target_file)) {
echo “error, file already exists”;
$uploadOk = 0;
}
// check file size
if ($_FILES[“fileToUpload”][“size”] > 500000) {
echo “error, your file is too large”;
$uploadOk = 0;
}
// allow certain file formats
if($imageFileType != “jpg” && $imageFileType != “png” && $imageFileType != “jpeg”
&& $imageFileType != “gif” ) {
echo “only JPG, JPEG, PNG & GIF files are allowed”;
$uploadOk = 0;
}
// check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo “your file was not uploaded.”;
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES[“fileToUpload”][“tmp_name”], $target_file)) {
echo “the file “. basename( $_FILES[“fileToUpload”][“name”]). ” has been uploaded”;
} else {
echo “there was an error uploading your file”;
}
}

PHP INCLUDE

Standard

the include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses it
including files is great when the same PHP, HTML, or text has to be used on multiple pages of a website

it’s possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement: these two directives are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
to make the execution go on and show users the output, even if the include file is missing, use the include statement
in case of a complex PHP application coding, always use the require statement to include a key file to the flow of execution

with file inclusion allows to create a standard header, footer, or menu file for all your web pages, and, when the header needs to be updated, do it one time only

include ‘filename’;
or
require ‘filename’;

include a standard footer file called “footer.php”, that looks like this
the footer.php file will be
echo “<p>copyright &copy; 1990-” . date(“Y”) . ” sample.com</p>”;

then include the footer file in a page, at the end of the HTML body
include ‘footer.php’;

the same thing will be done for the standard menu.php
echo ‘<a href=”/default.asp”>home</a> –
<a href=”/item1/default.asp”>itemOne</a> –
<a href=”/item2/default.asp”>itemTwo</a> –
<a href=”/item3/default.asp”>itemThree</a>;

all pages in the web site should use this menu file, included in their div class=”menu”
include ‘menu.php’;

another useful way to use include
the file vars.php contains some variables
$element=’fire’;
$color=’orange’;

if this file is included, these variables can be used in the calling file
include ‘vars.php’;
echo “the $element is $color”;

INCLUDE VS REQUIRE
when a file is included with the include statement and PHP cannot find it, the script will continue to execute
include ‘noFileExists.php’;
echo “the $element is $color”;
// print “the is”

doing the same sample using the require statement, the echo statement will not be executed
the script execution dies after the require statement returned a fatal error
require ‘noFileExists.php’;
echo “the $element is $color”;
// outputs nothing

PHP DATE AND TIME

Standard

DATE()
the PHP date() function is used to format a timestamp (for a more readable date)

date(format, timestamp)
the format specifies how to format the date (or time)
the default timestamp parameter is the current date and time

FORMATTING DATE
d – is days of the month (01 to 31)
m – is months (01 to 12)
Y – is the year (1990)
l – is the day of the week

characters, like “/”, “.”, or “-” can be inserted between the characters to add additional formatting

here there are three format samples, with the current day of the week
echo “today is ” . date(“Y/m/d”) ;
echo “today is ” . date(“Y.m.d”);
echo “today is ” . date(“Y-m-d”) ;
echo “today is ” . date(“l”);

FORMATTING TIME
h – is 12-hour format of an hour with leading zeros (01 to 12)
i – is minutes with leading zeros (00 to 59)
s – is seconds with leading zeros (00 to 59)
a – lowercase ante meridiem and post meridiem (am or pm)

$date = date(“d-m-Y”);
$time = date(“h-i-s”);
echo “today is “.$date.” with a time of ” . $time;

SETTING THE TIMEZONE
if the time the code got back is not the right time, it’s probably because the server is in another country or set up for a different timezone

to be correct according to a specific location, the right timezone has to be set

date_default_timezone_set(“Europe/Rome”);
echo “the time is ” . date(“h:i:s”);

*** the PHP date() function will return the current date/time of the server ***

*** the date() function is used to automatically update the copyright year on a website
&copy; 2010-<?php echo date(“Y”);?>

MKTIME()
the optional timestamp parameter in the date() function specifies a timestamp: if it isn’t specified, the current date and time will be used
the mktime() function returns the unix timestamp for a date: it contains the number of seconds between the unix epoch (january 1 1970 00:00:00 GMT) and the time specified
mktime(hour, minute, second, month, day, year)

with the parameters in the mktime() function is possibile to create a timestamp to format
$d=mktime(11, 14, 54, 8, 12, 2014);
echo “the created date is ” . date(“Y-m-d h:i:sa”, $d);

STRTOTIME()
this function is used to convert a human readable string to a unix time
strtotime(time,now)

sample 1
$d=strtotime(“10:30pm April 15 2014”);
echo “the date created is ” . date(“Y-m-d h:i:sa”, $d);

sample 2
$d=strtotime(“tomorrow”);
echo date(“Y-m-d h:i:sa”, $d);

sample 3
$d=strtotime(“next monday”);
echo date(“Y-m-d h:i:sa”, $d);

sample 4
$d=strtotime(“+1 month”);
echo date(“Y-m-d h:i:sa”, $d);

PHP has its own intelligence in converting a string to a date, so you can put in various values
however, strtotime() is not perfect, so remember to check the strings you put in there

this code outputs the dates for the next six saturdays
$startdate = strtotime(“saturday”);
$enddate = strtotime(“+6 weeks”, $startdate);

while ($startdate < $enddate) {
echo date(“M d”, $startdate);
$startdate = strtotime(“+1 week”, $startdate);
}

$d1=strtotime(“july 04”);
$d2=ceil(($d1-time())/60/60/24);
echo “there are ” . $d2 .” days until 4th of july.”;