PHP Tutorial For Beginner’s Guide to PHP
A scripting language is a language that interprets scripts at runtime. The purpose of the scripts is usually to enhance the performance or perform routine tasks for an application. This PHP Tutorial will provide you with a comprehensive knowledge about the server side scripting language in the following sequence:
Introduction to PHP
PHP stands for Hypertext Preprocessor and it is a server side scripting language that is used to develop Static websites or Dynamic websites or Web applications. It is the preferred scripting language for tech giants such as Facebook, Wikipedia, and Tumblr despite full-stack JavaScript gaining popularity with upcoming developers. This PHP Tutorial will help you know about the various aspects involved in the learning of PHP.
What is the difference between HTML & PHP?
Now many of you might ask that why do we need PHP when we already have HTML. Unlike HTML, PHP allows the coder to create an HTML page or section of it dynamically. PHP is also capable of taking data and use or manipulate it to create the output that the user desires.
- In HTML, anything you put in creates an output but PHP would not give you an output if something is wrong with your code. The learning curve of PHP is also much steeper compared to HTML.A PHP script can be placed anywhere in the document.
- It starts with <?php and ends with ?>:
- Syntax
<?php
// PHP code goes here
?>
- Now that you know the basic syntax of PHP, let’s move forward with the PHP Tutorial and have a look at the prerequisites to learn PHP.
Prerequisites to learn PHP
Learning a new programming language can be a bit overwhelming. Many people don’t know where to start and give up before they begin. Learning PHP is not as overwhelming as it might seem. One of the reasons for PHP’s success is that it has really great documentation. One can just dive into the documentation and get started without having any particular set of skills.
But once you have gained some knowledge in PHP, you will need to learn other languages for using PHP effectively. The languages include:
- HTML
- MySQL
- CSS
- JavaScript
Why do we need PHP?
You must be wondering that why do we need PHP for web programming when we already have other scripting languages like HTML.
So let’s move ahead with the PHP Tutorial and find out some of the compelling reasons for using PHP:
- It is open-source and free scripting language
- It has short learning curve compared to other languages such as JSP, ASP etc.
- Most web hosting servers support PHP by default
- It is a server-side scripting language so you need to install it on the server and client computers requesting for resources from the server do not need to have PHP installed
- PHP has in built support for working hand in hand with MySQL
- It is cross platform so you can deploy your application on a number of different operating systems such as windows, Linux, Mac OS etc.
Where do we use PHP?
There are three main areas where we use PHP:
- Server-side Scripting– This is the most traditional and main target field for PHP. The three things required to make this work include a PHP parser, a web server and a web browser. The web server runs with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server.
- Command line Scripting– PHP script can also run without any server or browser. You only need the PHP parser to use the command line scripting. This type of usage is ideal for scripts regularly executed using cron on 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 most preferable language to create a desktop application with a graphical user interface. But if you are well versed with PHP, you can use some advanced PHP features in your client-side applications and also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way.
So far in this PHP Tutorial we have learnt about when and where should we use PHP. Now let’s have a look at how to run the scripting language.
How to run PHP?
Manual installation of a Web server and PHP requires in-depth configuration knowledge but the XAMPP suite of Web development tools, created by Apache Friends, makes it easy to run PHP. Installing XAMPP on Windows only requires running an installer package without the need to upload everything to an online Web server. This PHP Tutorial gives you an idea of XAMPP and how it is used for executing the PHP programs.
What is XAMPP?
It is a free and open source cross-platform web server solution stack package developed by Apache Friends that consists of the Apache HTTP Server, MariaDB & MySQL database, and interpreters for scripts written in the PHP and Perl programming languages. XAMPP stands for Cross-Platform (X), Apache (A), MariaDB & MySQL (M), PHP (P) and Perl (P). It is a simple, lightweight Apache distribution that makes it extremely easy for developers to create a local web server for testing and deployment purposes.
PHP using WAMP Server
If you’re working on a project for the production environment and have a PC running the Windows OS then you should opt for WAMP server because it was built with security in mind. You can use this method to run PHP scripts you may have obtained from somewhere and need to run with little or no knowledge of PHP. You can execute your scripts through a web server where the output is a web browser.
Let’s have a look at the steps involved in using WAMP Server:
- Install the Server Software
- Set up the Server
- Save PHP Scripts
- Run PHP Scripts
- Troubleshoot
Now let’s move ahead with our PHP Tutorial and find out the suitable IDE for PHP.
PHP IDE
In order to remain competitive and productive, writing good code in minimum time is an essential skill that every software developer must possess. As the number and style of writing code increases and new programming languages emerge frequently, it is important that the software developers must opt for the right IDE to achieve the objectives.
An Integrated Development Environment or IDE is a self-contained package that allow you to write, compile, execute and debug code in the same place. So let’s have a look at some of the best IDE’s for PHP:
- PHPStorm
- Netbeans
- Aptana Studio
- Eclipse
- Visual Studio (with Xamarin)
- ZendStudio
PHP Data Types
A variable can store different types of Data. Let’s have a look at some of the data types supported by PHP:
PHP String
A string is a sequence of characters. In PHP, you can write the string inside single or double quotes.
<?php
$a = “Hello Edureka!”;
$b = ‘Hello Edureka!’;
echo $a;
echo “<br>”;
echo $b;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. An integer must have at least one digit and can be either positive or negative.
The following example takes $a as an integer. The PHP var_dump() function returns the data type and value.
<?php
$a = 0711;
var_dump($a);
?>
PHP Float
A float or floating point number is a number with a decimal point or a number in exponential form.
The following example takes $a as a float and the PHP var_dump() function returns the data type and value.
<?php
$a = 14.763;
var_dump($a);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE. They are often used in conditional testing.
$a = true;
$b = false;
PHP Object
An object is a data type which stores data and information on how to process that data. In PHP, an object must be explicitly declared. We need to declare a class of object using the class keyword.
<?php
class Student
{
function Student()
{
$this->name = “XYZ”;
}
}
// create an object
$Daniel = new Student();
// show object properties
echo $Daniel->name;
?>
PHP Array
An array stores multiple values in one single variable. In the following example, the PHP var_dump() function returns the data type and value.
<?php
$students = array(“Daniel”,”Josh”,”Sam”);
var_dump($students);
?>
Now that you have learnt about the various Data Types, let’s move ahead with the PHP Tutorial and have a look at the different PHP Variables.
PHP Variables
Variables are containers for storing information. All variables in PHP are denoted with a leading dollar sign ($). Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
Declaring PHP Variables:
<?php
$txt = “Hello Edureka!”;
$a = 7;
$b = 11.5;
?>
The PHP echo statement is often used to output data to the screen.
PHP Variables Scope
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be used.
In PHP we have three different variable scopes:
- Local – A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php
function myTest()
{
$a = 7; // local scope
echo “<p>Variable a inside function is: $a</p>”;
}
myTest();
// using x outside the function will generate an error
echo “<p>Variable a outside function is: $a</p>”;
?>
- Global– A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. The global keyword is used to access a global variable from within a function:
<?php
$a = 9; // global scope
function myTest() {
// using a inside this function will generate an error
echo “<p>Variable a inside function is: $a</p>”;
}
myTest();
echo “<p>Variable a outside function is: $a</p>”;
?>
- Static– When a function is executed, all of its variables are deleted. But if you want any variable not to be deleted, the static keyword is used when you first declare the variable:
<?php
function myTest() {
static $a = 0;
echo $a;
$a++;
}
myTest();
myTest();
myTest();
?>
Now that you know about the declaration of variables, let’s move ahead with the PHP Tutorial and have a look at the operators in PHP.
PHP Operators
Operators are used for performing different operations on variables. Let’s have a look at the different operators in PHP:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Array operators
Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
Operator | Name | Example | Result |
+ | Addition | $a + $b | Sum of $a and $b |
– | Subtraction | $a – $b | Difference of $a and $b |
* | Multiplication | $a * $b | Product of $a and $b |
/ | Division | $a / $b | Quotient of $a and $b |
% | Modulus | $a % $b | Remainder of $a divided by $b |
** | Exponentiation | $a ** $b | Result of raising $a to the $b’th power |
Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
Assignment | Similar to | Result |
a = b | a = b | The left operand gets set to the value of the expression on the right. |
a += b | a = a + b | Addition |
a -= b | a = a – b | Subtraction |
Comparison Operators
The PHP comparison operators are used to compare two numbers or strings
Operator | Name | Example |
== | Equal | $a == $b |
=== | Identical | $a === $b |
!= | Not equal | $a != $b |
<> | Not equal | $a <> $b |
!== | Not identical | $a !== $b |
> | Greater than | $a > $b |
< | Less than | $a < $b |
>= | Greater than or equal to | $a >= $b |
<= | Less than or equal to | $a <= $b |
Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator | Name | Example |
and | And | True if both $a & $b are true |
or | Or | True if either $a or $b are true |
xor | Xor | True if either $a or $b are true, but not both |
&& | And | True if both $a & $b are true |
|| | Or | True if either $a or $b are true |
! | Not | True if $a is not true |
Array Operators
The PHP array operators are used to compare arrays.
Operator | Name | Example |
+ | Union | $a + $b |
== | Equality | $a == $b |
=== | Identity | $a === $b |
!= | Inequality | $a != $b |
<> | Inequality | $a <> $b |
!== | Non-identity | $a !== $b |
Now let’s move ahead with our PHP Tutorial and have a look at the various OOP concepts in PHP.
Object Oriented Programming in PHP
The object oriented programming concepts assume everything as an object and implement a software using different objects. It is a programming paradigm that uses objects and their interactions to design applications.
The Object Oriented concepts in PHP include:
Class
This is a programmer-defined data type, which includes local functions as well as local data. A class is a construct or prototype from which objects are created and defines constituent members which enable class instances to have state and behavior.
<?php
class Books{
public function name(){
echo “Dans Books”;
}
public function price(){
echo “500 Rs/-”;
}
}
To create php object we have to use a new operator. Here php object is the object of the Books Class.
$obj = new Books();
$obj->name();
$obj->price();
?>
Object
Objects are basic building blocks of a PHP OOP program. An object is a combination of data and methods. In a OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages, and process data.
<?php
class Data {}
$object = new Data();
print_r($object);
echo gettype($object), " ";
?>
Inheritance
The inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes.
In order to declare that one class inherits the code from another class, we use the extends keyword. There are two types of inheritance:
- Single Level Inheritance
- Multilevel Inheritance
Example for Single Level Inheritance:
<?php
class X {
public function printItem($string) {
echo ' Hello : ' . $string;
}
public function printPHP() {
echo 'I am from Edureka' . PHP_EOL;
}
}
class Y extends X {
public function printItem($string) {
echo 'Hello: ' . $string . PHP_EOL;
}
public function printPHP() {
echo "I am from Bangalore";
}
}
$x = new X();
$y = new Y();
$x->printItem('Sam');
$x->printPHP();
$y->printItem('Josh');
$y->printPHP();
?>
Example for Multilevel Inheritance:
<?php
class A {
public function myage() {
return ' age is 70';
}
}
class B extends A {
public function mysonage() {
return ' age is 50';
}
}
class C extends B {
public function mygrandsonage() {
return 'age is 20';
}
public function myHistory() {
echo "Class A " .$this->myage();
echo "Class B ".$this-> mysonage();
echo "Class C " . $this->mygrandsonage();
}
}
$obj = new C();
$obj->myHistory();
?>
Interface
An interface is a description of the actions that an object can do. It is written in the same way as the class the declaration with interface keyword.
<?php
interface A {
public function setProperty($x);
public function description();
}
class Mangoes implements A {
public function setProperty($x) {
$this->x = $x;
}
public function description() {
echo 'Describing' . $this->x . tree;
}
}
$Apple = new Apples();
$Apple->setProperty(apple);
$Apple->description();
?>
Abstraction
An abstract class is a class that contains at least one abstract method. The abstract method is function declaration without anybody and it has the only name of the method and its parameters.
<?php
abstract class Cars {
public abstract function getCompanyName();
public abstract function getPrice();
}
class Baleno extends Cars {
public function getCompanyName() {
return "Maruti Suzuki" . '<br/>';
}
public function getPrice() {
return 850000 . '<br/>';
}
}
class Santro extends Cars {
public function getCompanyName() {
return "Hyundai" . '<br/>';
}
public function getPrice() {
return 380000 . '<br/>';
}
}
$car = new Baleno();
$car1 = new Santro();
echo $car->getCompanyName();
echo $car->getPrice();
echo $car1->getCompanyName();
echo $car1->getPrice();
?>
PHP Array
An array is a variable that holds more than one value at a time. An array can hold many values under a single name, and you can access the values by referring to an index number. This PHP Tutorial will give you an insight to the different types of arrays in PHP.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
There are three types of arrays in PHP:
- Indexed arrays – Arrays with a numeric index
- Associative arrays – Arrays with named keys
- Multidimensional arrays – Arrays containing one or more arrays
Indexed Arrays
In PHP, the index can be assigned automatically or manually. The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
<?php
$cars = array("Audi", "Toyota", "Ferrari");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them. The following example shows how to create an associative array:
<?php
$age = array("Sam"=>"32", "Ben"=>"37", "Josh"=>"41");
echo "Sam is " . $age['Sam'] . " years old.";
?>
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP – Two Dimensional Arrays
A two-dimensional array is an array of arrays. The following example shows how to initialize two dimensional arrays in PHP:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
PHP Conditional Statements
Conditional statements are used to perform different actions for different conditions. In PHP we have the following conditional statements:
- if statement – executes some code if one condition is true
- if…else statement – executes some code if a condition is true and another code if that condition is false
- if…elseif…else statement – executes different codes for more than two conditions
- switch statement – selects one of many blocks of code to be executed
The if Statement
The if statement executes some code if one condition is true.
<?php
$t = date("H");
if ($t < "15") {
echo "Have a good day!";
}
?>
The if…else Statement
The if…else statement executes some code if a condition is true and another code if that condition is false.
<?php
$t = date("H");
if ($t < "15") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
The if…elseif…else Statement
The if…elseif…else statement executes different codes for more than two conditions.
<?php
$t = date("H");
if ($t < "15") {
echo "Have a good morning!";
} elseif ($t < "25") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
The Switch Statement
The switch statement is used to perform different actions based on different conditions. It is used to select one of many blocks of code to be executed.
<?php
$favcolor = "blue";
switch ($favcolor) {
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
case "black":
echo "Your favorite color is black!";
break;
default:
echo "Your favorite color is neither blue, green nor black!";
}
?>
PHP Loops
When we write a code, we want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform the same task. In this PHP Tutorial we will learn about the three looping statements.
In PHP, we have the following looping statements:
- while – loops through a block of code as long as the specified condition is true
- do…while – loops through a block of code once, and then repeats the loop as long as the specified condition is true
- for – loops through a block of code a specified number of times
The While Loop
The while loop executes a block of code as long as the specified condition is true.
<?php
$a = 3;
while($a <= 5) {
echo "The number is: $a <br>";
$a++;
}
?>
The do..while Loop
The do…while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.
<?php
$a = 3;
do {
echo "The number is: $a <br>";
$a++;
} while ($a <= 5);
?>
The For Loop
PHP for loops execute a block of code a specified number of times. It is used when you know in advance how many times the script should run.
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Now that you have learnt about the Conditional Statements and Loops in PHP, let’s move ahead with the PHP Tutorial and learn about the Functions in PHP.
PHP Functions
The real power of PHP comes from its built-in functions. Besides the built-in PHP functions, we can also create our own functions. A function is a block of statements that can be used repeatedly in a program and will not execute immediately when a page loads.
Creating User-defined function in PHP
A user-defined function declaration starts with the word function. A function name can start with a letter or underscore but not a number.
<?php
function writeMsg() {
echo "Hello edureka!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments and it is just like a variable. Arguments are specified after the function name, inside the parentheses. We can add as many arguments as we want.
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Dash");
familyName("Dev");
familyName("Stale");
familyName("Jim");
familyName("Sandin");
?>
- I hope you have understood the basics of PHP so far and gained a deep insight in to the various functions involved. Now let’s move ahead with the PHP Tutorial and learn about Cookies and Sessions in PHP.
PHP Cookies
A cookie is often used to identify a user. It is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, we can both create and retrieve cookie values. In this PHP Tutorial we will learn about creating, modifying and deleting a cookie.
Creating cookies with PHP
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Example
<?php
$cookie_name = "user";
$cookie_value = "Smith Joe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<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>
Modifying a Cookie
To modify a cookie, just set (again) the cookie using the setcookie() function:
<?php
$cookie_name = "user";
$cookie_value = "Hannah";
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>
Deleting a Cookie
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>
PHP Sessions
A session is a way to store information to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer. By default, session variables last until the user closes the browser. In this PHP Tutorial, we will learn about starting, modifying and destroying a session.
Starting a PHP Session
A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "blue";
$_SESSION["favanimal"] = "dog";
echo "Session variables are set.";
?>
</body>
</html>
Modifying a PHP Session
To modify a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "green";
print_r($_SESSION);
?>
</body>
</html>
Destroying a PHP Session
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>
Now with this, we have come to the end of the PHP Tutorial. I Hope you guys enjoyed this article and understood the concepts of PHP. So, with the end of this PHP Tutorial, you are no longer a newbie to the scripting language.