document php
document php
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose
scripting language that is especially suited for web development and can be embedded into HTML. It
allows web developers to create dynamic content that interacts with databases. PHP is basically used for
developing web based software applications.
PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do,
such as collect form data, generate dynamic page content, or send and receive cookies. Code is executed
in servers, that is why you’ll have to install a sever-like environment enabled by programs like XAMPP
which is an Apache distribution.
Back in 1994, Rasmus Lerdorf unleashed the very first version of PHP. However, now the reference
implementation is now produced by The PHP Group. The term PHP originally stood for Personal Home
Page but now it stands for the recursive acronym: Hypertext Preprocessor. PHP 4 and PHP 5 are
distributed under the PHP Licence v3.01, which is an Open Source licence certified by the Open Source
Initiative.
In this article, we’ll have a detailed look at the server-side scripting using PHP.
1.1.1 Why PHP?
There stand convincing arguments for all those who wonder why PHP is so popular today:
• Compatible with almost all servers used nowadays
A web server is an information technology that processes requests via HTTP, the basic network protocol
used to distribute information on the World Wide Web. There exist many types of web servers that
servers use. Some of the most important and well-known are: Apache HTTP Server, IIS (Internet
Information Services), lighttpd, Sun Java System Web Server etc. As a matter of fact, PHP is compatible
with all these web servers and many more.
• PHP will run on most platforms
Unlike some technologies that require a specific operating system or are built specifically for that, PHP is
engineered to run on various platforms like Windows, Mac OSX, Linux, Unix etc)
• PHP supports such a wide range of databases
An important reason why PHP is so used today is also related to the various databases it supports (is
compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo, MaxDB, MongoDB,
mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so on.
• PHP is free to download and open source
Anyone can start using PHP right now by downloading it from php.net. Millions of people are using PHP
to create dynamic content and database-related applications that make for outstanding web systems. PHP
is also open source, which means the original source code is made freely available and may be
redistributed and modified.
• Easy to learn & large community
PHP is a simple language to learn step by step. This makes it easier for people to get engaged in exploring
it. It also has such a huge community online that is constantly willing to help you whenever you’re stuck
(which actually happens quite a lot).
XAMPP Setup
XAMPP is a free and open source cross-platform web server solution developed by Apache Friends,
consisting mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in
the PHP and Perl programming languages. In order to make your PHP code execute locally, first install
XAMPP.
• Download XAMPP
• Install the program (check the technologies you want during installation)
• Open XAMPP and click on "Start" on Apache and MySQL (when working with databases)
Figure 1.2: XAMPP window after a successful installation with Apache and
MySQL enabled
•
• Place your web project inside the htdocs directory. In the common case, if you installed XAMPP directly
inside the C: drive of your PC, the path to this folder would be: C:xampphtdocs
Figure 1.3: XAMPP Directory for Web Projects
To test the services are up and running you can just enter localhost in your address bar and expect the
welcoming page.
There are four ways the PHP parser engine can differentiate PHP code in a webpage:
This is the most popular and effective PHP tag style and looks like this:
<?php...?>
• Short-open Tags
These are the shortest option, but they might need a bit of configuration, and you might either choose the
--enable-short- tags configuration option when building PHP, or set the short_open_tag setting in your php.ini
file.
<?...?>
• ASP-like Tags
In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:
<%...%>
<script language="PHP">...</script>
Just like other languages, there are several ways to comment PHP code. Let’s have a look at the
most useful ones: Use # to write single-line comments
<?
Use // to also write
# this is a single-line
comment in comments
PHP, a single line comment
?>
<?
// this is also a comment in PHP, a single line comment
?>
Hello World
The very basic example of outputting a text in PHP would be:
<?
print("Hello World");
echo "Hello World";
printf("Hello
World");
?>
The result of the above statements would be the same: "Hello World". But why are there three different ways to
output?
• print returns a value. It always returns 1.
The following snippet shows all of these data types declared as variables:
<?
$intNum = 472;
$doubleNum = 29.3;
$boolean = true;
$string = ’Web Code Geeks’;
$array = array("Pineapple", "Grapefruit", "Banana");
The If statement
The if statement executes a piece of code if a condition is true. The syntax is:
if (condition) {
// code to be executed in case the condition is true
}
The If. . . Else statement executed a piece of code if a condition is true and another piece of code if the
if (condition) {
// code to be executed in case the condition is true
}
else {
// code to be executed in case the condition is false
}
condition is false. The syntax is:
This kind of statement is used to define what should be executed in the case when two or more conditions
are present. The syntax of this case would be:
if (condition1) {
// code to be executed in case condition1 is true
elseif (condition2) {
// code to be executed in case condition2 is true
}
else {
// code to be executed in case all conditions are false
}
Loops in PHP
In PHP, just like any other programming language, loops are used to execute the same code block for a
specified number of times. Except for the common loop types (for, while, do. . . while), PHP also support
foreach loops, which is not only specific to PHP. Languages like Javascript and C# already use foreach
loops. Let’s have a closer look at how each of the loop types works.
The for loop is used when the programmer knows in advance how many times the block of code should
The while loop is used when we want to execute a block of code as long as a test expression continues to be true.
The result of this code snippet would be just the same as before:
This is loop number 0
This is loop number
1 This is loop
number 2 This is
loop number 3 This
is loop number 4
The do...while loop is used when we want to execute a block of code at least once and then as long as a
test expression is true.
The foreach loop is used to loop through arrays, using a logic where for each pass, the array element is
considered a value
and the array pointer is advanced by one, so that the next element can be processed.
foreach (array as value) {
// executable code
}
This time the first loop number would be 1, because the first echo was executed only after variable
Element is a
Element is b
Element is c
Element is d
Element is e
incrementation:
PHP Arrays
Arrays are used to store multiple values in a single variable. A simple example of an array in PHP would be:
<?php
$languages = array("JS", "PHP", "ASP", "Java");
?>
Array elements are accessed like this: $arrayName[positionIndex]. For the above example we could
access "PHP" this way: $languages[1]. Position index is 1 because in programming languages the first
element is always element 0. So, PHP would be 1 in this case.
Indexed Arrays
We can create these kind of arrays in two ways shown below:
<?php
$names = array("Fabio", "Klevi", "John");
?>
<?php
// this is a rather manual way of doing it
$names[0] = "Fabio";
$names[1] = "Klevi";
$names[2] = "John";
?>
// RESULT
My friends are Fabio, Klevi and John
Associative Arrays
Associative arrays are arrays which use named keys that you assign. Again, there are two ways we can create
<?php
$namesAge = array("Fabio"=>"20", "Klevi"=>"16", "John"=>"43");
?>
<?php
// this is a rather manual way of doing it
$namesAge[’Fabio’] = "20";
$namesAge[’Klevi’] = "18";
$namesAge[’John’] = "43";
?>
them:
// RESULT
Fabio’s age is 20 years old.
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
<?php
$socialNetowrks = array (
array("Facebook", "feb",
21),
array("Twitter","dec", 2),
array("Instagram","aug", 15));
?>
three-dimensional array is an array of arrays of arrays. An example of this kind of array would be:
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
<?php
function functionName($argument1, $argument2...) {
// code to be executed
}
<?php
function showGreeting() { // function definition
echo "Hello Chloe!"; // what this function
does
}
of procedure to be followed within the body, that is, code to be executed. Let’s see some basic functions:
Hello Chloe!
greetPerson("Fabio"); // function
call greetPerson("Michael");
?>
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.
<?php
function difference($a, $b) { // function definition with arguments
$c = $a - $b;
return $c;
}
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
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.
Connecting to MySQL Databases
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.1.4 Connecting to MySQLi Databases (Procedurial)
1.1.5 The MySQLi stands for MySQL improved. The syntax for connecting to a database using MySQLi
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
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.
$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";
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.
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.
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:
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
<?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"])) {
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.
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"
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.
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:
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
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>
</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
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>
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
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.
• 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.
PHP Classes
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
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 24 / 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->printDetails();
$car2->printDetails();
?>
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.