Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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:
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.
<?php
// PHP code goes here
?>
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:
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:
Where do we use PHP?
There are three main areas where we use PHP:
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.
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.
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:
Now let’s move ahead with our PHP Tutorial and find out the suitable IDE for PHP.
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:
A variable can store different types of Data. Let’s have a look at some of the data types supported by PHP:
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;
?>
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);
?>
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);
?>
A Boolean represents two possible states: TRUE or FALSE. They are often used in conditional testing.
$a = true;
$b = false;
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;
?>
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.
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.
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:
<?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>”;
?>
<?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>”;
?>
<?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.
Operators are used for performing different operations on variables. Let’s have a look at the different operators in PHP:
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 |
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 |
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 |
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 |
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.
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:
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();
?>
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), " ";
?>
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:
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();
?>
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();
?>
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();
?>
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:
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 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.";
?>
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>";
?>
Conditional statements are used to perform different actions for different conditions. In PHP we have the following conditional statements:
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 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 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 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!";
}
?>
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:
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 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);
?>
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.
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.
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
?>
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");
?>
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.
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>
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>
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>
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.
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>
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>
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.
If you found this PHP Tutorial blog relevant, check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
Got a question for us? Please mention it in the comments section of ”PHP Tutorial” and I will get back to you.
edureka.co