PHP is a widely-used open source general-purpose scripting language
that is especially suited for web development and can be embedded into HTML.
It is a server-side scripting language designed primarily for web development but also used as a
general-purpose programming language.
Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP
Development Team.
PHP originally stood for Personal Home Page, but it now stands for the recursive acronym PHP: Hypertext
Preprocessor.
PHP runs on different operating systems, like Windows, UNIX, Linux and supports different databases like
MySQL, Microsoft Access, and Oracle.
PHP can not only collect form data, but it can also create, read, write, delete, and close files on the
server.
What can PHP do?
There are three main areas where PHP scripts are used.
Server-side scripting
This is the most traditional and main target field for PHP. You need three things to make this work:
the PHP parser (CGI or server module),
a web server and a web browser. You need to run the web server, with a connected PHP installation.
You can access the PHP program output with a web browser, viewing the PHP page through the server.
All these can run on your home machine if you are just experimenting with PHP programming.
Command line scripting
You can make a PHP script to run it without any server or browser.
You only need the PHP parser to use it this way.
This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task
Scheduler (on Windows).
These scripts can also be used for simple text processing tasks.
Writing desktop applications
PHP is probably not the very best language to create a desktop application with a graphical user
interface,
but if you know PHP very well, and would like to use some advanced PHP features in your client-side
applications you can also use PHP-GTK to write such programs
Instead of lots of commands to output HTML (as seen in C or Perl),
PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP
script!").
Installation
Download the latest PHP 5 ZIP package from www.php.net/downloads.php
Extract the file: PHP can be installed anywhere on your system, but you will need to change the paths
referenced in the following steps
Configure php.ini: Copy C:php php.ini-recommended to C:php php.ini. There are several lines you will
need to change in a text editor.
Define the extension directory: extension_dir = "C:phpext"
extension=php_curl.dll
extension=php_gd2.dll
extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo.dll
extension=php_pdo_mysql.dll
extension=php_xmlrpc.dll
Add C:php to the path environment variable
Configure PHP as an Apache module
Add index.php as a default file name: DirectoryIndex index.php index.html
At the bottom of the file, add the following lines
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"
Save the configuration file and test it from the command line (Start > Run > cmd)
Super Global Variables
$GLOBALS
This is a PHP super global variable which is used to access global variables from anywhere in the PHP
script (also from within functions or methods).
This is widely used to collect form data after submitting an HTML form with method="post". $_POST is
also widely used to pass variables.
Sample Code:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
$_REQUEST
This is used to collect data after submitting an HTML form
Sample Code:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
$_FILES
An associative array of items uploaded to the current script via the HTTP POST method.
The structure of this array is outlined in the POST method uploads section.
Sample Code:
<?php
$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;
}
}
?>
$_COOKIE
PHP transparently supports HTTP cookies.
Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying
return users.
Sessions are a simple way to store data for individual users against a unique session ID.
This can be used to persist state information between page requests.
Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve
existing session data.
Sample Code:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
$_ENV
These variables are imported into PHP's global namespace from the environment under which the PHP
parser is running.
Many are provided by the shell under which PHP is running and different systems are likely running
different kinds of shells,
a definitive list is impossible.
Sample Code:
<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>
Session Handling in PHP
To demontrate the Session Handling in Php here is a simple Log in(login.php) and profile(profile.php)
system.
To access profile.php, user must log in first and log-in name will be used until log out or browser close
(session terminate when browser closed).
To handle session, you must first start it and store some value to any session variable. You can create any
amount of session variable you wish.
To validate whether Session is active or not, we use isset() function and finally to destroy it we use
unset() function.
Creating the login.php
Code:
<?php
if(isset($_POST['user_name']))
{
session_start();
$_SESSION['name']=$_POST['user_name'];
//Storing the name of user in SESSION variable.
header("location: profile.php");
}
?>
<html>
<head>
<title>Session Handling in PHP</title>
</head>
<body>
<form action="" method="post" id="main_form">
<input type="text" name="user_name" size="40"><br />
<input type="submit" value="Log in">
</form><br><br>
</body>
</html>
After submitting the form, we store the name of user in session and in next page we use the same name.
Code:
<?php
session_start();
if(!isset($_SESSION['name']))
{
header("location: index.php");
}
$name=$_SESSION['name'];
?>
<html>
<head>
<title>Profile of <?php echo $name;?></title>
</head>
<h1>Hello <?php echo $name;?></h1>
<h3><a href="logout.php">Click here to log out</a></h3>
</html>
In this code, first we are checking whether the SESSION is set or not.
If not then we will redirect the user to main page, else we will store the name of user into
variable and displaying it in HTML code.
Lastly, we let user log out from system.
Code:
<?php
if(isset($_SESSION['name']))
{
unset($_SESSION['name']);
}
echo '<h1>You have been successfully logout</h1>';
?>
Redirection in Php
PHP Code Syntax for Redirection:
<?php
/* Redirect browser */
header("Location: http://theos.in/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
Including and Requiring Files
Include
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 the include statement. Including files is very useful when you want to
include the same PHP, HTML, or text on multiple pages of a website.
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
</body>
</html>
Require
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
Database Connectivity
In Php database conectivity is fairly easy and straight forward. As compared to other programming language
such as Java, the lines of code of the database connectivity in Php is fairly shorter. There are two ways to
connect in a database either use the database function-specific access or use the PDO (PHP Data Objects)
which is database agnostic. I'll illustrate using PDO since it is database agnostic - meaning it can be use
in any database
Database Connection via mysqli
<?php
$con = mysqli_connect("localhost","root","password","webtek-database-finals");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Database Connection via PDO
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webtek-database-finals";
try {
// Instatstiate connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Bind the parameters
$stmt = $conn->prepare("INSERT INTO registration (firstname, lastname, username)
VALUES (:firstname, :lastname, :username)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':username', username);
// insert a row
$firstname = "Chris";
$lastname = "Espiritu";
$username = "cee";
$stmt->execute();
// insert another row
$firstname = "Maureen";
$lastname = "Calpito";
$username = "mcalpito";
$stmt->execute();
// insert another row
$firstname = "Chris";
$lastname = "Santos";
$username = "crissantos";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
There are many ways to connect to any database in Php, arguably the best way is to use PDO since it does
not depend on vendor-specific implementation
Frameworks
Laravel
Laravel is a free, open-source PHP web framework intended for the development of web applications
following the model–view–controller (MVC)
architectural pattern. Some of the features of Laravel are a modular packaging system with a
dedicated dependency manager,
different ways for accessing relational databases, utilities that aid in application deployment and
maintenance,
and its orientation toward syntactic sugar.
CodeIgniter
CodeIgniter is an open-source software rapid development web framework, for use in building dynamic
web sites with PHP.
It is a powerful PHP framework with a very small footprint, built for developers who need a simple
and elegant toolkit to
create full-featured web applications.
Symfony
Symfony is a PHP web application framework and a set of reusable PHP components/libraries.
Symfony is an internationally recognized, stable development environment.
Reference
(n.d.). Retrieved May 20, 2017, from https://www.w3schools.com/php/func_http_header.asp
(n.d.). Retrieved May 20, 2017, from https://www.w3schools.com/php/func_mysqli_connect.asp
Buckler, C. (2015, December 02). How to Install PHP on Windows — SitePoint. Retrieved May 20, 2017, from
https://www.sitepoint.com/how-to-install-php-on-windows/
PHP. (2017, May 17). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/PHP
How to Start PHP Programming: Basic PHP Scripts. (2017, February 16). Retrieved May 20, 2017, from
https://www.cloudways.com/blog/how-to-start-php-programming/
(n.d.). Retrieved May 20, 2017, from https://mothereff.in/html-entities
HTML. (n.d.). Retrieved May 20, 2017, from https://www.w3schools.com/
Shaikh, S. (. (2014, August 13). Session handling in php. Retrieved May 20, 2017, from
https://codeforgeek.com/2014/08/session-handling-php/
laravel. (2017, May 13). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/Laravel
CodeIgniter Rocks. (n.d.). Retrieved May 20, 2017, from https://www.codeigniter.com/
CodeIgniter. (2017, May 03). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/CodeIgniter
Symfony. (2017, May 06). Retrieved May 20, 2017, from https://en.wikipedia.org/wiki/Symfony
S. (n.d.). Symfony explained to a Developer. Retrieved May 20, 2017, from
http://symfony.com/explained-to-a-developer