0% found this document useful (0 votes)
23 views

php_cookbook-21-42

PHP Book 4

Uploaded by

dhivakar.m23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

php_cookbook-21-42

PHP Book 4

Uploaded by

dhivakar.m23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PHP Programming Cookbook 12 / 63

<?php
$namesAge = array("Fabio"=>"20", "Klevi"=>"16", "John"=>"43");
echo "Fabio’s age is " . $namesAge[’Fabio’] . " years old.";
?>

// RESULT
Fabio’s age is 20 years old.

Looping through an associative array is done like so:


<?php
$namesAge = array("Fabio"=>"20", "Klevi"=>"16", "John"=>"43");

foreach($namesAge as $i => $value) {


echo "Key = " . $i . ", Value = " . $value;
echo "";
}
?>

Key = Fabio, Value = 20


Key = Klevi, Value = 16
Key = John, Value = 43

Multidimensional Arrays
This is a rather advanced PHP stuff, but for the sake of this tutorial, just understand what a multidimensional array is. Basically,
it is an arrays the elements of which are other arrays. For example, a three-dimensional array is an array of arrays of arrays. An
example of this kind of array would be:
<?php
$socialNetowrks = array (
array("Facebook", "feb", 21),
array("Twitter","dec", 2),
array("Instagram","aug", 15));
?>

1.5 PHP Functions

Functions are a type of procedure or routine that gets executed whenever some other code block calls it. PHP has over 1000
built-in functions. These functions help developers avoid redundant work and focus more on the logic rather than routine things.
Apart from its own functions, PHP also let’s you create your own functions. The basic syntax of a function that we create is:
<?php
function functionName($argument1, $argument2...) {
// code to be executed
}

functionName($argument1, $argument2...); // function call


?>

Every function needs a name, optionally has one or more arguments and most importantly, defines some kind of procedure to be
followed within the body, that is, code to be executed. Let’s see some basic functions:
<?php
function showGreeting() { // function definition
echo "Hello Chloe!"; // what this function does
}
PHP Programming Cookbook 13 / 63

showGreeting(); // function call


?>

This function would just print the message we wrote:


Hello Chloe!

Another example would be a function with arguments:


<?php
function greetPerson($name) { // function definition with arguments
echo "Hi there, ".$name; // what this function does
}

greetPerson("Fabio"); // function call


greetPerson("Michael");
?>

This time we’d have:


Hi there, Fabio
Hi there, Michael

More than one argument can be used whenever needed:


<?php
function personProfile($name, $city, $job) { // function definition with arguments
echo "This person is ".$name." from ".$city.".";
echo "";
echo "His/Her job is ".$job.".";
}

personProfile("Fabio", "Tirana", "Web Dev");


echo "";
personProfile("Michael", "Athens", "Graphic Designer");
echo "";
personProfile("Xena", "London", "Tailor");
?>

The result would include the printed message together with the arguments:
This person is Fabio from Tirana.
His/Her job is Web Dev.
This person is Michael from Athens.
His/Her job is Graphic Designer.
This person is Xena from London.
His/Her job is Tailor.

In PHP, just like in many other languages, we can tell functions to return a value upon executing the code. Such example would
be:
<?php
function difference($a, $b) { // function definition with arguments
$c = $a - $b;
return $c;
}

echo "The difference of the given numbers is: ".difference(8, 3);


?>

The result would be:


PHP Programming Cookbook 14 / 63

The difference of the given numbers is: 5

PHP also provides quite useful functions for developers to use. One of them is the mail() function. Have a detailed look of
how you can use this function to send e-mails in this article

1.6 Connecting to a Database

There are four ways you can generally consider when you want to connect to a previously created database. Below, we’ll explain
how you can use each of them beginning with the easiest one.

1.6.1 Connecting to MySQL Databases

The syntax for connecting to a MySQL database would be:


<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";

//connection to the database


$dbConnect = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL";

//select a specific database


$dbSelect = mysql_select_db("dbName", $dbConnect)
or die("Could not select dbName");
?>

Considering your entered information is correct, you’d be successfully connected to the right database and ready to start writing
and test your queries. Else, the respective error message would appear as defined by the die function. However, do keep in mind
that the mysql extension is deprecated and will be removed in the future, so the next methods can be used for databases.

1.6.2 Connecting to MySQLi Databases (Procedurial)

The MySQLi stands for MySQL improved. The syntax for connecting to a database using MySQLi extension is:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";

//connection to the database


$dbConnect = mysqli_connect($hostname, $username, $password)

// another way of checking if the connection was successful


if (!$dbConnect) {
die ("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

//select a specific database


mysqli_select_db($dbConnect, "dbName")
?>

This is a good way to start, because it is easy to understand and gets the job done. However, object oriented logic that we’ll see
below is what everyone should be getting into because of the other components of programming being used in this paradigm and
also because it is kind of more structured way of doing things.
PHP Programming Cookbook 15 / 63

1.6.3 Connecting to MySQLi databases (Object-Oriented)

Although the functionality is basically the same, this is another way, the object-oriented way of connecting to a database using
the MySQLi extension.
$username = "your_name";
$password = "your_password";
$hostname = "localhost";

// create connection
$dbConnect = new mysqli($hostname, $username, $password);

// check connection
if ($dbConnect->connect_error) {
die("Connection failed: " . $dbConnect->connect_error);
}
echo "Connected successfully";

// select a specific database


$mysqli->select_db("dbName");

Even in this case, you can check to see if the database was successfully selected, but it is a matter of choice. Object-Oriented
MySQLi is not a different MySQLi as far as code functionality is concerned, but rather a different way/logic of writing it.

1.6.4 Connecting to PDO Databases

PDO stands for PHP Data Objects and is a consistent way to access databases, which promises much easier portable code. PDO
is more like a data access layer which uses a unified API rather than an abstraction layer. The syntax for connecting to a database
using PDO is:
$username = "your_name";
$password = "your_password";
$hostname = "localhost";

// try to create connection


try {
$dbConnect = new PDO("mysql:host=$hostname;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
// show an error if the connection was unsuccessful
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

PDO is widely used today for a bunch of advantages it offers. Among them, we can mention that PDO allows for prepared
statements and rollback functionality which makes it really consistent, it throws catchable exceptions which means better error
handling and uses blind parameters in statements which increases security.

1.7 PHP Form Handling

In HTML, forms are used to collect user input/information. But, as far as HTML goes, it just provides the graphical interface
and the ability to write on the input fields. However, the aim we collect user information is because we need to process this
information. That usually means saving the inputs to a database so that they can be accessed later for several purposes. In
this section, we will not send information to the database, as that requires an active database that is already set up and includes
knowledge form SQL language, but we can retrieve information that the user has given us. That being said, it is important to
PHP Programming Cookbook 16 / 63

have a way to get information, becuase what you use it for and where you want to show/save it depends. Let’s have a look at the
HTML form below:
<form method="POST" action="wcg.php">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="E-Mail">
<input type="number" name="age" placeholder="Age">
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="submit" name="submit" value="Submit">
</form>

This form is just a regular one, and includes inputs for name, e-mail, age and gender. This information will be subject of a print
when the Submit button is clicked. That just proves that we got the information from the user. For now, let’s see what we got and
fill the form:

Figure 1.5: HTML form we just created

Next, we check each input to make sure the user has written/chosen something, and the input is not empty. We do this using two
well-known functions in PHP, the isset() and empty(). After making sure we have this right, we can also validate fields. In
this case, only the name input may need some sort of validation to make sure one simply doesn’t write numbers in there, while
other inputs are more or less validated from HTML5, in the case of email and age.
<?php
if (isset($_POST["name"]) && !empty($_POST["name"])) {
$name = $_POST["name"];
if (!preg_match("/^[a-zA-Z ]*$/",$name))
echo "Name: Only letters and whitespace allowed";
else
echo "Name: ".$_POST["name"]."";
}
if (isset($_POST["email"]) && !empty($_POST["email"])) {
echo "E-Mail: ".$_POST["email"]."";
}
if (isset($_POST["age"]) &&!empty($_POST["age"])) {
PHP Programming Cookbook 17 / 63

echo "Age: ".$_POST["age"]."";


}
if (isset($_POST["gender"]) && !empty($_POST["gender"])) {
echo "Gender: ".$_POST["gender"];
}
?>

Validation is a must for all fields when considering real web projects. We recommend having a closer look to our article on PHP
Form Validation Example
If the fields have been set, information about each field will be printed. After clicking the "Submit" button, the result we’d have
is:
Name: Alex Brown
E-Mail: [email protected]
Age: 28
Gender: Male

As you may have noticed by now, we used this $_POST["name"] to get information the user posted.
What about implementing a login form in PHP? Have a look at our Login Form in PHP Example.

1.8 PHP Include & Require Statements

PHP code can get cluttered, which means that if you want to later change something, it becomes a hard task to do. Include and
require statements are two almost identical statements that help in an important aspect of coding, the organization of code, and
making it more readable and flexible. The include/require statement copies all text, code or any other markup from one existing
file to the file using the statement. In a simple viewpoint, do consider these statements like this:
PHP Programming Cookbook 18 / 63

Figure 1.6: PHP Include Statement

The include and require statements are the same, except upon failure of code execution where:

• require will produce a fatal error (E_COMPILE_ERROR) and stop the script from executing
• include will only produce a warning (E_WARNING) and the script will continue

The syntax of these two statements is as follows:


<?php
include ’file.php’; // in case of include
require ’file.php’; // in case of require
?>

Let’s now see a real-world example where we use a header and footer using include and require into our main file:
header.php
<header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
PHP Programming Cookbook 19 / 63

</ul>
</nav>
</header>
// styling to make the menu look right
<style type="text/css">
ul, li {
list-style-type: none;
display: inline-block;
margin-right: 1em;
padding: 0;
}
</style>

footer.php
<footer>All Rights Reserved. Do not reproduce this page.</footer>

In our main file, we’ll use require for the header.php and include for the footer.php file:
index.php
<?php require ’header.php’; ?>

<body>
<h2>Main Content Goes Here</h2>
</body>

<?php include ’footer.php’ ?>

The result, as you might have an idea by now, would be the whole code being shown as one:

Figure 1.7: The result of using include and require in our main file

1.9 Object Oriented Concepts

Object oriented programming is a programming language model in the center of which are objects. Let’s see some of the core
concepts of classes and objects before we see actual examples of them:

• Class

A class is a predefined (by a programmer) data type, part of which are local data like variables, functions etc.

• Object

An object is an instance of a class. Objects can only be created after a class has been define. A programmer can create several
objects.
PHP Programming Cookbook 20 / 63

• Constructor

A constructor refers to the concept where all data and member functions are encapsulated to form an object. A destructor, on the
other hand, is called automatically whenever an object is deleted or goes out of scope.

1.9.1 PHP Classes

Let’s now define a new clas in PHP.


<?php
class myClass { // use ’class’ followed by the name of the class
var $var1; // declared an undefined variable
var $var2 = 5; // declared a number defined variable
var $var3 = "string"; // declared a string defined variable

function myFunction ($argument1, $argument2) { // function definition


// function code here
}
}
?>

But that is just how the syntax looks like. Below, we give an example of a real-world class, for example class Vehicle:
<?php
class Vehicle {
var $brand; // just a declared undefined variable
var $speed = 80; // a declared and defined variable

function setSpeed($speedValue) { // a function to change speed


$this->speed = $speedValue; // this will replace speed with our value
}

function setBrand($brandName) { // a function to change brand


$this->brand = $brandName; // this will set a brand name
}

function printDetails(){ // a function to print details


echo "Vehicle brand is: ".$this->brand;
echo "";
echo "Vehicle speed is: ".$this->speed;
}
}

$myCar = new Vehicle; // an instance of our Vehicle class (an object)


$myCar->setBrand("Audi"); // calling the function setBrand to define a brand
$myCar->setSpeed(120); // calling the function setSpeed to change speed
$myCar->printDetails(); // calling the printDetails function to see details
?>

The result of this code would be:


Vehicle brand is: Audi
Vehicle speed is: 120

As you can see, the speed is changed to the latest value set by us.

1.9.2 PHP Constructor Function

PHP provides a special function called __construct() to define a constructor, which can take as many arguments as we
want. Constructors are called automatically whenever an object is created. Let’s see how we adopt this into our previously
created class. The following code snipper is found inside the class:
PHP Programming Cookbook 21 / 63

<?php
class Vehicle {
function __construct ($brandName, $speedValue) {
$this->brand = $brandName; // initialize brand
$this->speed = $speedValue; // initialize speed
}
function printDetails(){
echo "Vehicle brand is: ".$this->brand;
echo "
";
echo "Vehicle speed is: ".$this->speed;
echo "

";
}
}

$car1 = new Vehicle("Toyota", 130);


$car2 = new Vehicle ("Ferrari", 450);

$car1->printDetails();
$car2->printDetails();
?>

The result now is:


Vehicle brand is: Toyota
Vehicle speed is: 130

Vehicle brand is: Ferrari


Vehicle speed is: 450

PHP contains such object oriented rules just like other languages like Java, and as you go on learning it in further details, you’ll
see that you can do more with those variables we declare inside a class, you can set scope to them so that they can only be
accessed within a class, a function etc. Also, other concepts like methods overriding is normal when using PHP, as declaring
the same method for the second time but with different arguments or code logic, will make the program execute only the latest
method it finds in the file.

1.10 Conclusion

PHP is the fundamental back-end development technology regarding usage and learning curve. It combines such features that
make for interactive web pages that people love to use everyday. In this article, we detailed the basic concepts to give you a clear
idea of how it can be used in different aspects and information that you might as well relate to other programming languages like
loops and conditionals, as most languages recognize these concepts and make use of them.
In the early days, everyone used PHP in a rather procedurial style, as a way to get things done when you don’t know a lot, but
as you learn more and more, you’ll love working with object-oriented PHP which will make your programming life way much
easier and sustainable in big projects. It is important to understand that there are many ways pages could be made dynamic in
PHP, and different developers might as well have a totally distinct code that does the same task, that is some kind of flexibility
that you get to decide how you are going to implement certain functions (randomly called procedures in PHP). So, just give it a
try, you have nothing to lose.

1.11 Download the source code

Download You can download the full source code of this example here: PHP-Tutorial-Samples
PHP Programming Cookbook 22 / 63

Chapter 2

Upload Script Example

In this example, we are going to see how to make file uploads with PHP, that is, how to upload a file from the client side, to the
server side.
The process itself is pretty simple, but several checks have to be done to ensure that the file upload is made safely, i.e., to neutralise
any hypothetical malicious misuse; and to be able to detect every possible error to act accordingly, so, this is something that must
be done carefully.
For this tutorial, we will use:

• Ubuntu (14.04) as Operating System.


• Apache HTTP server (2.4.7).
• PHP (5.5.9).

2.1 Preparing the environment

2.1.1 Installation

Below, are shown the commands to install Apache and PHP:


sudo apt-get update
sudo apt-get install apache2 php5 libapache2-mod-php5
sudo service apache2 restart

2.1.2 PHP configuration

Is necessary to configure PHP to allow file uploads. With your favourite editor, open the php.ini file:
sudo vi /etc/php5/apache2/php.ini

And check that the file_uploads directive value is set to On:


file_uploads = On

If you want, you can change the upload_max_filesize directive, to change the maximum size allowed for upload.
Don’t forget to restart Apache after doing any change.
Note: if you want to use Windows, installing XAMPP is the fastest and easiest way to install a complete web server that meets
the prerequisites.
PHP Programming Cookbook 23 / 63

2.2 Upload form

First, we need to create a form, where the file will be attached. It should be similar to this:
upload_form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Upload form</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">

<label for="file">Select a file to upload:</label>


<input type="file" name="file" id="file">

<input type="submit" value="Upload file!">

</form>
</body>
</html>

There are several things to take into account:

• Form action must point to the PHP file that will perform the upload (this is quite obvious).
• Submission method must be POST.
• Form enctype attribute must be specified, with multipart/form-data value. This is not to make the form encode the
characters.

2.2.1 Accepting only certain type of files

It is possible to restrict the uploading files to only expected file types. This can be made in several ways:

• By file extension. For example, if we are expecting a document, we can restrict the extensions to .pdf and .doc.

• By file type. We can directly say that we are expecting an image, an audio or/and a video.
• By media type, specifying the MIME type. An example could be text/plain, if we are expecting plain files.

All of these can be combinated, so we could say, for example, that we are expecting a document file, and it can be accepted in
pdf, doc, docx and odt and format.
Applying this last example to the form above (line 11), the result would be the following:
upload_form.html
<input type="file" name="file" id="file" accept=".pdf,.doc,.docx,.odt">

As you can see, the conditions are sepparated by comma.


Note: keep always in mind that client-side validation is never enough. Every validation we do in the client-side, it should be
done also in the server - remember that here is the person in the client-side who has the control, not you!
PHP Programming Cookbook 24 / 63

2.3 PHP upload script

Once the form is submitted, is time for the server to handle the upload. The following script will do the job:
upload.php
<?php

define(’UPLOAD_DIRECTORY’, ’/var/php_uploaded_files/’);

$uploadedTempFile = $_FILES[’file’][’tmp_name’];
$filename = $_FILES[’file’][’name’];
$destFile = UPLOAD_DIRECTORY . $filename;

move_uploaded_file($uploadedTempFile, $destFile);

Easy, isn’t it? We just define the target directory where the file will be stored, we get the file PHP uploaded temporarily, original
file’s name, and we move that file to the defined target directory, with its name.
But, as we said in the introduction, in this task we must focus the efforts into the security. This script does not check:

• File size. We should set a maximum allowed size (what if an user is trying to upload a file bigger than server’s available space?)

• File type. If we are expecting, for example, a document, receiving an executable file would be quite suspicious, wouldn’t it?
• That the file was properly uploaded to the server, and moved to the target directory. We can’t take anything for granted. With
that script, we won’t notice if an error occurs in the upload.

2.3.1 A secure file upload script

Let’s update our script to make a safe file upload, supposing that we expect only document-type files, as we defined 2.1 section,
of pdf, doc, docx and odt format:
upload.php
<?php

define(’UPLOAD_DIRECTORY’, ’/var/php_uploaded_files/’);
define(’MAXSIZE’, 5242880); // 5MB in bytes.

// Before PHP 5.6, we can’t define arrays as constants.


$ALLOWED_EXTENSIONS = array(’pdf’, ’doc’, ’docx’, ’odt’);
$ALLOWED_MIMES = array(’application/pdf’, // For .pdf files.
’application/msword’, // For .doc files.
’application/vnd.openxmlformats-officedocument.wordprocessingml.document’, // For .docx ←-
files.
’application/vnd.oasis.opendocument.text’, // For .odt files.
);

/**
* Checks if given file’s extension and MIME are defined as allowed, which are defined in
* array $ALLOWED_EXTENSIONS and $ALLOWED_MIMES, respectively.
*
* @param $uploadedTempFile The file that is has been uploaded already, from where the MIME
* will be read.
* @param $destFilePath The path that the dest file will have, from where the extension ←-
will
* be read.
* @return True if file’s extension and MIME are allowed; false if at least one of them is ←-
not.
*/
PHP Programming Cookbook 25 / 63

function validFileType($uploadedTempFile, $destFilePath) {


global $ALLOWED_EXTENSIONS, $ALLOWED_MIMES;

$fileExtension = pathinfo($destFilePath, PATHINFO_EXTENSION);


$fileMime = mime_content_type($uploadedTempFile);

$validFileExtension = in_array($fileExtension, $ALLOWED_EXTENSIONS);


$validFileMime = in_array($fileMime, $ALLOWED_MIMES);

$validFileType = $validFileExtension && $validFileMime;

return $validFileType;
}

/**
* Handles the file upload, first, checking if the file we are going to deal with is ←-
actually an
* uploaded file; second, if file’s size is smaller than specified; and third, if the file ←-
is
* a valid file (extension and MIME).
*
* @return Response with string of the result; if it has been successful or not.
*/
function handleUpload() {
$uploadedTempFile = $_FILES[’file’][’tmp_name’];
$filename = basename($_FILES[’file’][’name’]);
$destFile = UPLOAD_DIRECTORY . $filename;

$isUploadedFile = is_uploaded_file($uploadedTempFile);
$validSize = $_FILES[’file’][’size’] <= MAXSIZE && $_FILES[’file’][’size’] >= 0;

if ($isUploadedFile && $validSize && validFileType($uploadedTempFile, $destFile)) {


$success = move_uploaded_file($uploadedTempFile, $destFile);

if ($success) {
$response = ’The file was uploaded successfully!’;
} else {
$response = ’An unexpected error occurred; the file could not be uploaded.’;
}
} else {
$response = ’Error: the file you tried to upload is not a valid file. Check file ←-
type and size.’;
}

return $response;
}

// Flow starts here.

$validFormSubmission = !empty($_FILES);

if ($validFormSubmission) {
$error = $_FILES[’file’][’error’];

switch($error) {
case UPLOAD_ERR_OK:
$response = handleUpload();
break;

case UPLOAD_ERR_INI_SIZE:
$response = ’Error: file size is bigger than allowed.’;
break;
PHP Programming Cookbook 26 / 63

case UPLOAD_ERR_PARTIAL:
$response = ’Error: the file was only partially uploaded.’;
break;

case UPLOAD_ERR_NO_FILE:
$response = ’Error: no file could have been uploaded.’;
break;

case UPLOAD_ERR_NO_TMP_DIR:
$response = ’Error: no temp directory! Contact the administrator.’;
break;

case UPLOAD_ERR_CANT_WRITE:
$response = ’Error: it was not possible to write in the disk. Contact the ←-
administrator.’;
break;

case UPLOAD_ERR_EXTENSION:
$response = ’Error: a PHP extension stopped the upload. Contact the ←-
administrator.’;
break;

default:
$response = ’An unexpected error occurred; the file could not be uploaded.’;
break;
}
} else {
$response = ’Error: the form was not submitted correctly - did you try to access the ←-
action url directly?’;
}

echo $response;

Now, let’s see the key instructions added to this script:

• We first check the $_FILES superglobal, in line 70. If it’s empty, it would be because the access to this script has not been
done through a form submission, so, we shouldn’t perform any action.
• We get the error property of the superglobal, in line 73. Here is saved the state of the file submission, indicating if it has
been done correctly, or if any error occured. The state is later evaluated in the switch, where we perform different actions
depending on the state.
• Getting the basename of the file, in line 47. This PHP built-in gives us the file name. Even if it is defined in $_FILES[’fil
e’][’name’], it is always recommended to get file names using this function.
• Checking if the file is actually an uploaded file, in line 50. This function checks that the given file is really a file uploaded
through HTTP POST. This check is necessary to avoid malicious actions that may want to have access server files.

• Checking the size of the file, in line 51. Before proceding, we ensure that the uploading file doesn’t exceed the maximum size
set. Because the limit does not always have to be the one set in php.ini.
• Checking the file type, in line 53. This is probably one of the most interesting checks. Here, we ensure that the receiving file
is actually a document, in two steps: getting the file extension (line 27), and the file MIME (line 28). It is not enough checking
only one of these. Consider the following scenario: we are checking only the file extension, which is expected to be one of
those defined in the array. If an evil user wants to upload an executable file, it only has to change its extension to one of those.
But the content type is not modified with the extension. So, we have to check both to ensure that the files are real documents.
• Finally, we check that the file has been moved correctly to the target directory, with its original name (line 54). The difference
here compared with the previous script, is that we retrieve the boolean value returned by the move_uploaded_files
function, because it may fail, for any reason. As we said before, we can’t take anything for granted.
PHP Programming Cookbook 27 / 63

2.3.2 Considerations

You may noticed that the temp files created by PHP ($_FILES[’file’][’tmp_name’]) are not being deleted. This is
because we don’t have to care about it; when the script finishes it execution, PHP will delete them for us.
About the checking of allowed files, in some cases, when the upload is not oriented only to a very specific file type, it may be
more interesting to have a blacklist where not allowed file types are defined, instead of having a whitelist, like in the script above.
Generally, we won’t expect to receive files that can be harmful, like executable files, or even scripts.

2.4 Summary

With this script, files will be safely uploaded to our server, ensuring that the received file is of the type/types we are expecting
(remember that the validation must reside always in the server-side), and also that doesn’t exceed the established size. And, if
something goes wrong, we will be able to identify the exact error, that will allow us to take the most appropiate decision for each
case.

2.5 Download the source code

This was an example of file uploading with PHP.


Download You can download the full source code of this example here: PHPUploadScript
PHP Programming Cookbook 28 / 63

Chapter 3

Mail Function Example

In this example, we will see how we can send emails with PHP. After seeing this example, you will be able to send emails
programmatically, which is especially useful in scenarios like the following:

• Registration confirmation.
• Password recovery.
• Notification delivery.

And any other scenario where a service needs to contact a user.


PHP has a built-in function called mail that will do all the job but, first, we have to make some configurations in order to make
this function work.
For this tutorial, we will use:

• Ubuntu (14.04) as Operating System.


• Apache HTTP server (2.4.7).
• PHP (5.5.9).
• sSMTP (2.64), a lightweight MTA (Mail Transfer Agent).

3.1 Preparing the environment

3.1.1 Installation

Below, the commands to install Apache and PHP are shown:


sudo apt-get update
sudo apt-get install apache2 php5 libapache2-mod-php5
sudo service apache2 restart

Now, we install sSMTP:


sudo apt-get install ssmtp

With this MTA, now, we will be able to send mails from our machine, to a SMTP server. In other words, we can make a SMTP
server (like Gmail’s, Outlook’s, etc.) deliver the mails we want to send.
PHP Programming Cookbook 29 / 63

3.1.2 sSMTP configuration

The sSMTP configuration consists of two things:

• Defining the SMTP service we are going to use.


• Provide credentials for that service.

In this example, we will use Google’s Gmail SMTP server., and supposing that we have an account named [email protected],
with mygmailpassword as password.
So, taking that into account, the /etc/ssmtp/ssmtp.conf file will remain as:
ssmtp.conf
UseSTARTTLS=YES
mailhub=smtp.gmail.com:587
[email protected]
AuthPass=mygmailpassword

This is what we are setting:

• UseSTARTTLS: necessary for using Gmail’s SSL/TLS sever.


• mailhub: the smtp server itself, in port 587, for SSL/TLS.
• AuthUser and AuthPass: credentials for loging in Gmail.

Note: take care of who has access to this file - anyone having access to the file, can access the mail account set.

3.1.3 PHP configuration

The last step, is to make PHP now how to use sSMTP. For that, we have to specify the path to sSMTP executable, in PHP config
file, /etc/php5/apache2/php.ini file:
php.ini
sendmail_path = /usr/sbin/sendmail

Don’t forget to restart Apache after making any change in PHP configuration:
sudo service apache2 restart

3.2 PHP mail sending script

The PHP code is all about calling a function, named mail. Here an example that sends a mail to someone, with a subject and the
message itself:
send_mail_example.php
<?php

$to = ’[email protected], [email protected]’;


$subject = ’Mail from PHP’;
$message = "Hi,\r\nThis mail has been sent using PHP!";

$success = mail($to, $subject, $message);

if ($success) {
PHP Programming Cookbook 30 / 63

$response = ’Message has been sent successfully.’;


} else {
$response = ’The message could not be sent.’;
}

echo $response;

There are a few things that have to be taken into account:

• It is possible to set multiple mails to send the mail to, separated by commas, as in the example above.

• mail function does not perform any encoding. This can be a problem, that we will see below how to deal with.
• The lines must be separated with Windows line ending format, i.e., the CRLF: ’rn’.
• Unfortunately, mail function only returns a boolean value so, if something goes wrong, we cannot have any details at runtime.

Mail function has two more optional parameters: for setting additional headers, and for setting additional parameters. The first
one is to add additional headers, as we would do, for example, in a HTML page. The last one is, actually, a MTA command line
parameter, used to pass additional flags and commands.
Let’s see how can we use these additional options.

3.2.1 Setting additional headers

Consider the following scenario: we have a system that sends greetings to the users registered within, each one in the language
set by the user. If we have, for example, a Chinese user, the message body would be:
send_mail_example.php
$message = ’ä½~å$\yen$½’; // ’Hello’ in Chinese.

With the example we saw above, the result would be an ugly string of characters that don’t match with the expected Chinese
characters. For a scenario like this, is not enough to rely the encoding only in the language setting. The solution would be to
encode the message properly, encoding it to UTF-8, and, for that, we have to set the header manually.
For that, we need to perform two additional steps:
send_mail_example.php
$headers = ’Content-Type: text/plain; charset=UTF-8’;

$success = mail($to, $subject, $message, $headers);

Quite simple: define the headers, and pass them to the function. If we try now the script, we will receive a mail with those nice
Chinese characters.
It is also usual to use this additional headers, for example, to add carbon copies (cc) and blind carbon copies (bcc).
Note: Multiple headers must be separated as same as new lines in the message, with a CRLF.

3.2.2 Setting additional parameters

As told before, when we are setting additional parameters, we are actually passing instructions that will be executed by the server,
te binary we set to sendmail_path, in php.ini.
For example, we could set the verbose mode, to see how is going the whole process, which can be useful for troubleshooting.
For this, we just declare another variable, for the parameters, and we pass it as last parameter to the function:
send_mail_example.php
PHP Programming Cookbook 31 / 63

$parameters = ’-v’;

$success = mail($to, $subject, $message, $headers, $parameters);

If we execute now the script, we will see the whole process: from the initial handshake with the server, to the connection close.
In this case, to pass several parameters, they must be separated by a blank space.
You can see the whole list of available options in sSMTP manual:
man ssmtp

3.3 Troubleshooting

If you have not been able to make this example work, in this section we are going to see which can be the possible causes, and
finding solutions for them.

3.3.1 Set verbose mode

Before doing anything else, the first recommended step would be to set the verbose mode, to see in detail what’s happening. You
can see how to do it in section 2.2.

3.3.2 Login is rejected by SMTP server

It may occur that Gmail considered the login attempt through sSMTP as insecure or suspicious, because of trying to login using
an external service or app.
To confirm that this is the problem, login into the account you set in sSMTP configuration file, and you should have received
and email from Google with a subject similar to: Suspicious sign in prevented. To disable this security measure, in
Gmail, go to My Account/Sign-in & security, and in Connected apps & sites section, enable the "Allow less secure apps" toggle
to "on".

3.3.3 Firewall is filtering outgoing traffic

Maybe, a firewall is filtering the connection. Normally, by default, firewalls do not filter outgoing traffic, but it can be a possibility.
Check that you don’t have any firewall filtering outgoing traffic that would affect to this example (remember that we configured
the MTA to use the port 587).

3.3.4 Check PHP error log

If it continues not working, check the PHP error log, to see which is the error thrown by PHP, to get more hints of which can be
the error. By default, the error log is located in /var/log/apache2/error.log.

3.4 Alternatives to sSMTP

For this example, we have chosen sSMTP as it is the easiest and fastest way to deliver mails, only needing the simple configuration
we saw in section 1.2, and also because it is very light; is not using daemons, and its impact in CPU and memory is negligible.
But, if you are looking for a more advanced, full-featured MTA, Postfix and Exim are probably the most used ones.
PHP Programming Cookbook 32 / 63

3.5 Summary

In this example, we have seen how to send mails with PHP, which is pretty simple - only a function call is needed. But we have
also seen that, that alone is not enough, and that a MTA is needed, to connect with the SMTP server we are using. We have also
analysed the most common errors that we can face in this task, and how to solve them, apart from the problem that can suppose
the sending of not properly encoded mails.

3.6 Download the source code

This was an example of mail sending with PHP.


Download You can download the full source code of this example here: PHPMailFunctionExample
PHP Programming Cookbook 33 / 63

Chapter 4

Date Format Example

In this example, we shall show how to deal with dates in PHP. As dates can be represented in many different ways. It is important
to find a way that helps to avoid possible unexpected errors that may arise.
For this example, we will use:

• Ubuntu (14.04) as Operating System.


• Apache HTTP server (2.4.7).
• PHP (5.5.9).

4.1 Preparing the environment

4.1.1 Installation

Below, commands to install Apache and PHP are shown:


sudo apt-get update
sudo apt-get install apache2 php5 libapache2-mod-php5
sudo service apache2 restart

Note: if you want to use Windows, installing XAMPP is the fastest and easiest way to install a complete web server that meets
the prerequisites.

4.2 How should dates be stored?

As you will probably know, the date representation varies from region to region. For example, in UK, we would say that today is
13/05/2016; whereas in US, we would represent it as 05/13/2016.
This can lead to a problem. If we have a system that needs to do some calculations basing on the date, if a date is in an unexpected
format, we would have nonsense results.
To solve this, a system known as Unix time, also known as Epoch time was proposed. What this system does, is describe time
instants: it’s defined as the number of seconds passed from 01/01/1970 at 00:00:00 (UTC). So, the date we mentioned above, in
Unix time, would be 1463097600 (truncated to the day start, at 00:00:00).
We could define it as a "cross-region/language time representation".
The Unix time is universally used not only in Unix-like systems, but also in many other computational systems. So, with Unix
time, we have widely used standard that does not depend on any region or system configuration. In the case a user has to deal
with this data, the only thing we would have to do is to transform it to a human-readable format.
Note: Unix time is not a real representation of UTC, as it does not represent leap seconds that UTC does.

You might also like