Why To Learn PHP?: Basic Tutorials
Why To Learn PHP?: Basic Tutorials
Why To Learn PHP?: Basic Tutorials
PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way
back in 1994.
PHP is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning PHP:
PHP is a server side scripting language that is embedded in HTML. It is used to
manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
It is integrated with a number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache
module on the Unix side. The MySQL server, once started, executes even very
complex queries with huge result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and
LDAP. PHP4 added support for Java and distributed object architectures (COM
and CORBA), making n-tier development a possibility for the first time.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP Syntax is C-Like.
Characteristics of PHP
Simplicity
Efficiency
Security
Flexibility
Familiarity
PHP Example
In this tutorial, you will get a lot of PHP examples to understand the topic well. You must
save the PHP file with a .php extension. Let’s see a simple PHP example.
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
Output:
Hello, World!
Applications of PHP
As mentioned before, PHP is one of the most widely used language over the web. I'm
going to list few of them here:
PHP performs system functions, i.e. from files on a system it can create, open,
read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through
email you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Audience
This PHP tutorial is designed for PHP programmers who are completely unaware of
PHP concepts but they have basic understanding on computer programming.
Prerequisites
Before proceeding with this tutorial you should have at least basic understanding of
computer programming, Internet, Database, and MySQL etc is very helpful.
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software
stack. It is available for all operating systems. There are many AMP options available in
the market that are given below:
XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.
If you are on Windows and don't want Perl and other features of XAMPP, you should go
for WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
PHP echo is a language construct not a function, so you don't need to use parenthesis
with it. But if you want to use more than one parameters, it is required to use
parenthesis.
PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
File: echo1.php
<?php
echo "Hello by PHP echo";
?>
Output:
File: echo2.php
<?php
echo "Hello by PHP echo
this is multi line
text printed by
PHP echo statement
";
?>
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
PHP echo: printing escaping characters
File: echo3.php
<?php
echo "Hello escape \"sequence\" characters";
?>
Output:
File: echo4.php
<?php
$msg="Hello Skyapper PHP";
echo "Message is: $msg";
?>
Output:
$variablename=value;
Let's see the example to store string, integer and float values in PHP variables.
File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
File: variable2.php
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Output:
11
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from
Color, COLOR, COLor etc.
File: variable3.php
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
Output:
My car is red
My house is
My boat is
PHP variables must start with letter or underscore only. PHP variable can't be start with
numbers and special symbols.
File: variablevalid.php
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>
Output:
hello
hello
File: variableinvalid.php
<?php
$4c="hello";//number (invalid)
$*d="hello";//special symbol (invalid)
Output:
PHP is a loosely typed language, it means PHP automatically converts the variable to
its correct data type.
PHP constants are name or identifier that can't be changed during the execution of the
script. PHP constants can be defined by 2 ways:
PHP constants follow the same PHP variable rules. For example, it can be started with
letter or underscore only.
File: constant1.php
<?php
define("MESSAGE","Hello Skyapper PHP");
echo MESSAGE;
?>
Output:
File: constant2.php
<?php
define("MESSAGE","Hello Skyapper PHP",true);//not case sensitive
echo MESSAGE;
echo message;
?>
Output:
<?php
define("MESSAGE","Hello Skyapper PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>
Output:
The const keyword defines constants at compile time. It is a language construct not a
function. It is bit faster than define(). It is always case sensitive.
File: constant4.php
<?php
const MESSAGE="Hello const by Skyapper PHP";
echo MESSAGE;
?>
Output:
PHP data types are used to hold different types of data or values. PHP supports 8
primitive data types that can be categorized further in 3 types:
Scalar Types
Compound Types
Special Types
boolean
integer
float
string
array
object
resource
NULL
Topic Title: Operator Types
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
> Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.
< Checks if the value of left operand is less than the value (A < B) is
of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal (A <= B) is
to the value of right operand, if yes then condition true.
becomes true.
Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Show Examples
and Called Logical AND operator. If both the operands are (A and B) is
true then condition becomes true. true.
&& Called Logical AND operator. If both the operands are (A && B) is
non zero then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is
state of its operand. If a condition is true then Logical false.
NOT operator will make false.
Assignment Operators
There are following assignment operators supported by PHP language −
Show Examples
Conditional Operator
There is one more operator called conditional operator. This first evaluates an
expression for a true or false value and then execute one of the two given statements
depending upon the result of the evaluation. The conditional operator has this syntax −
Show Examples
Operators Categories
All the operators we have discussed above can be categorised into following
categories −
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic
and logical operations.
The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression.
Assignment operators, which assign a value to a variable.
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP. In
PHP, we can define Conditional function, Function within Function and Recursive
function also.
Code Reusability: PHP functions are defined only once and can be invoked many times,
like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times.
By the use of function, you can write the logic only once and reuse it.
User-defined Functions
We can declare and call user-defined functions easily. Let's see the syntax to declare
user-defined functions.
Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.
PHP Functions Example
File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
We can pass the information in PHP function through arguments which is separated by
comma. PHP supports Call by Value (default), Call by Reference, Default argument
values and Variable-length argument list.
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
Let's see the example to pass two argument in PHP function.
File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Value passed to the function doesn't modify the actual value by default (call by value).
But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference,
you need to use ampersand (&) symbol before the argument name.
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
We can specify a default argument value in function. While calling PHP function if you
don't specify any argument, it will take the default argument. Let's see a simple example
of using default argument value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
PHP array is an ordered map (contains value on the basis of key). It is used to hold
multiple values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an
array.
Indexed Array
Associative Array
Multidimensional Array
PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string
and object in the PHP array. All PHP array elements are assigned to an index number
by default.
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example
File: array1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
File: array2.php
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
We can associate name with each array elements in PHP using => symbol.
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
File: arrayassociative2.php
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
PHP allows you to include file so that a page content can be reused many times. There
are two ways to include file in PHP.
include
require
Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML
code or PHP script in many PHP scripts.
PHP include is used to include file on the basis of given path. You may use relative or
absolute path of the file. Let's see a simple PHP include example.
File: menu.html
<a href="http://www.skyapper.com">Home</a> |
<a href="http://www.skyapper.com/php-tutorial">PHP</a> |
<a href="http://www.skyapper.com/java-tutorial">Java</a> |
<a href="http://www.skyapper.com/html-tutorial">HTML</a>
File: include1.php
Output:
PHP require is similar to include. Let's see a simple PHP require example.
File: menu.html
<a href="http://www.skyapper.com">Home</a> |
<a href="http://www.skyapper.com/php-tutorial">PHP</a> |
<a href="http://www.skyapper.com/java-tutorial">Java</a> |
<a href="http://www.skyapper.com/html-tutorial">HTML</a>
File: require1.php
Output:
If file is missing or inclusion fails, include allows the script to continue but require halts
the script producing a fatal E_COMPILE_ERROR level error.
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client
sends request to the server, cookie is embedded with request. Such way, cookie can be
received at the server side. In short, cookie can be created, sent and received at server
end.
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set,
you can access it by $_COOKIE superglobal variable.
Syntax
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
PHP $_COOKIE
Example
File: cookie1.php
<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Output:
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
Topic Title #5: PHP Session
PHP session is used to store and pass information from one page to another
temporarily (until user close the website).
PHP session technique is widely used in shopping websites where we need to store
and pass cart information e.g. username, product code, product name, product price etc
from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid
conflict between multiple browsers.
PHP session_start() function is used to start the session. It starts a new or resumes
existing session. It returns existing session if session is created already. If session is not
available, it creates and returns new session.
Syntax
Example
session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to
set and get session variable values.
Example: Store information
$_SESSION["user"] = "Sachin";
echo $_SESSION["user"];
File: session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>
File: session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
File: sessioncounter.php
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
File: session3.php
<?php
session_start();
session_destroy();
?>
Topic Title #6: File Upload
PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allows you to upload binary and text files both. Moreover, you
can have the full control over the file to be uploaded through PHP authentication and file
operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated
with file.
$_FILES['filename']['name']
$_FILES['filename']['type']
$_FILES['filename']['size']
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the
POST request. It moves the file if it is uploaded through the POST request.
Syntax
File: uploadform.html
File: uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>