What is Php
Php is a Server-side Programming/Scripting language designed to be used for writing software in the widest variety of application domains. Php stands for Hypertext Preprocessor but its original name is Personal Home Page. Rasmus Lerdorf developed this language in 1994. Php runs on various platform such as Window, Unix, Linux, Mac OS X, etc. PHP is faster than other scripting languages like ASP and JSP. Php is compatible with almost server Apache, IIS etc.Php 7.2.0 is the latest version of Php. PHP is an open source general-purpose scripting language and its file extension is . (dot)php. Php is especially well versed for Web development and can be embedded into HTML.
Let’s take an example:
<!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <?php echo "Hello, My first PHP script!"; ?> </body> </html>
Output: Hello, My first PHP script.
Table of Contents
There are three main uses of PHP
- Server-side script: This is the most common field for PHP. for the function of server-side scripting it requires: the PHP parser that is CGI (common gateway interface), a web server and a web browser. You can run the PHP server after the installation. You can access the PHP program output with a web browser or page with the server. All these can run on your personal computer or laptop.
- Command line script: You can make a PHP program to run it without any server or browser. To run the program, you only need the PHP parser. These programs can also be used for simple tasks.
- Writing desktop applications: PHP is mainly not considered the very best language to create a desktop application with a graphical user interface, but it has some advanced features which you can use in your client-side applications.
Some other uses of the PHP are:
- Create dynamic page
- Handle button click
- Make a database application
- Client or server application
- Student registration application
- Online course
- Online shopping cart
- Chat rooms
Characteristic of Php
In PHP you have the freedom to choose web server and operating system. As it has some flexible and best characteristics that make it use easily.
- Simple
- Efficient
- Secure
- Flexible
- Familiar/Easy
Php in Web Development
PHP is an open source language that’s why it is widely used in web development nowadays. Using PHP you can create dynamic websites easily. But you must have the basic knowledge of following technologies for PHP web development as well.
- HTML
- CSS
- JavaScript
- Ajax
- XML and JSON
- jQuery
How to Install Php
In order to develop and run PHP Programs, three important components need to be installed on your computer system.
- Web Server − PHP will work with almost all Web Server software, including Microsoft’s Internet Information Server (IIS) but most often used is freely available Apache Server.
To download Apache for free − https://httpd.apache.org/download.cgi
- Database − PHP will work with almost all database software, including Oracle but mostly used is freely available MySQL database.
To download MySQL for free here − https://www.mysql.com/downloads/
- PHP Parser − In order to process PHP programs instructions a parser must be installed to generate HTML output so that it can be sent to the Web Browser. Given below steps will help you to know how to install PHP parser on your computer.
PHP Parser Installation
Before you proceed it is important to make sure that you have a proper environment set up on your desktop or laptop to develop your web programs using PHP.
Type the following address into your browser’s address box.
http://127.0.0.1/info.php
If the page displays PHP installation related information then it means you have PHP and Web Server installed properly. If not, you have to follow the given procedure to install PHP on your computer.
Apache Configuration
If you are using Apache Web Server then follow these guidelines to edit Apache Configuration Files.
PHP.INI File Configuration
PHP.INI is the PHP configuration file which is the final and most immediate way to affect PHP’s functionality.
Windows IIS Configuration
To configure IIS on your Windows you can refer your IIS Reference Manual come along with IIS.
To install PHP, we will suggest you install AMP (Apache, MySQL, PHP) software stack. This is available for all operating systems.
There are several AMP options available in the market below:
- WAMP for Windows Os
- LAMP for Linux Os
- MAMP for Mac Os
- SAMP for Solaris Os
- FAMP for FreeBSD
- XAMPP (Cross, Apache, MySQL, PHP, and Perl) for Cross-Platform: It includes some other components also such as OpenSSL, Webalizer, Mercury Mail, etc.
If you are using Windows and don’t want Perl and other features of XAMPP, you should go for WAMP. In a similar way, you may use a LAMP for Linux and MAMP for Macintosh.
Syntax of PHP
All PHP code goes between the PHP tag. Syntax of PHP tags is given below:
- <?PHP
- //your code here
- ?>
Write your first program in PHP, which you can run easily. For writing a Code on PHP you can use Notepad or Notepad++ editor.
Example: <?php Echo “My 1st Php program”; ?>
Result (output)= My 1st Php
# The statements or expression in PHP is terminated by a semicolon(;)
Commenting in PHP
For single line comment(# or //): It is used to make a particular line as a comment.
<? # This is a comment, and # This is the second line of the comment // This is a comment too. Each style comments only print "An example with single line comments"; ?> For multiple line comment( enclosed between /* */) <? /* This is a comment with multiline Author: Mohammad Mohtashim Purpose: Multiline Comments Demo Subject: PHP */ print "An example with multi-line comments"; ?>
- Php is case sensitive
Yes, PHP is case sensitive. Take a look at this example:
<html> <body> <?php $rupees = 67; print("Variable rupees is $rupees<br>"); print("Variable Rupees is $Rupees<br>"); ?> </body> </html>
The output of the code:
Variable rupees is 67
Variable Rupees is
Curly braces make blocks of statements
Although statements cannot be combined like expressions, you can always put a sequence of statements in a set of curly braces(opening{ and }closing braces).
Example:
if (4 == 2 + 2) print("correct.<br>"); if (4 == 2 + 2) { print("yeah I haven't totally"); print("lost my mind.<br>"); }
PHP Variable Types
Variable is the main way to store information in the middle of a PHP program.
Here are the most important points to know about variables in PHP.
- All variables in PHP are denoted with a dollar sign ($).
- The value of a variable is of its most recent assignment.
- Variables are assigned with the (equal to)= operator, the left-hand side and the expression to be evaluated on the right.
- Variables can be declared before the assignment but not mandatory.
- Variables in PHP do not have a prior definition means a variable does not know in advance whether it is going to store a number or a string of characters.
- Variables have their default values before they are assigned to use.
- PHP can automatically convert types from one to another when necessary.
- PHP variables are like Perl variables.
Php Data Types
PHP has a total of eight data types which is used to construct variables −
- Integers − are whole numbers like 2125.
- Doubles − are floating-point numbers, decimal numbers like 2.14159 or 47.1.
- Booleans −It holds only two values, either TRUE or FALSE.
- NULL − It is a special type that only has one value: “NULL”.
- Strings − are sequences of characters like ‘PHP supports boolean operations.’
- Arrays − Store multiple elements of similar data type under a single variable.
- Objects − These are defined as instances of user-defined classes that can hold both values and functions
- Resources − These are basically used to store references to some function call or to external PHP resources
The first five are simple types, and the next two (arrays and objects) are compound – the compound types that allow for multiple items of the same type to be collected under a single entity, whereas the simple types cannot.
Variable Scope
The scope of a variable can be defined as the range of availability to the program in which it is declared. PHP variables have four scope types −
- Local variables: A variable declared within the function.
- Function parameters: it is a local variable whose value is passed to the function by calling code.
- Global variables: declared outside of any function and represent by Global keyword.
- Static variables: when a function is completed normally its variable is deleted. Sometimes you want a local variable not to delete for that you can use static. Represent by Static keyword.
Variable Naming
How to name a variable −
- Variable names must start with a letter or underscore character.
- A variable name can be consist of numbers, letters, underscores but cannot use characters like + , – , % , ( , ) . & , etc.
- There is no size limit is defined for variables and also it cannot start with a number.
Php constant types
A constant is an identifier or a simple names assigned any fixed value. A constant value cannot change during the execution or runtime and also a case. -sensitive. By default, constants are always uppercase. It is global and can be used across the entire PHP script.
Php Operator Types
Operators are used to performing operations on variables and values.
PHP divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Increment/Decrement operators
- Logical operators
- String operators
- Array operators
Arithmetic operators
These arithmetic operators are used to perform common arithmetical operations with a numeric value, such as multiplication, division, subtraction, and addition.
Let assume A=10 and B=20.
Operator | Description | Example |
+ | Adds two operands | A + B will give 30 |
– | Subtracts second operand from the first | A – B will give -10 |
* | Multiply both operands | A * B will give 200 |
/ | Divide numerator by the denominator | B / A will give 2 |
% | Modulus Operator and the remainder of after a division | B % A will give 0 |
Assignment operators
The PHP assignment operators are used with numeric values to assign a value to a variable.
Operator | Same as | Description |
X=Y | X=Y | Left side operand gets to set the value of assignment expression of the right side. |
X+=y | X=X+Y | Addition |
X-=Y | X=X-Y | Subtraction |
X*=Y | X=X*Y | Multiplication |
X/=Y | X=X/Y | Division |
X%=Y | X=X%Y | Modulus |
Comparison operators
The PHP comparison operators are used to compare two values whether it is number or string.
Operator | Description | Example |
== | Returns true if $A is equal to $B | $A == $B |
!= | Returns true if $A is not equal to $B | $A != $B |
> | Returns true if the value of the left operand has greater than the value of the right operand | $A > $B |
< | Returns true if the value of the left operand has less than the value of the right operand | $A < $B |
>= | Return true if the value of the left operand is greater than or equal to the value of the right operand | $A >= $B |
<= | Return true if the value of the left operand is less than or equal to the value of the right operand | $A <= $B |
=== | Return true if the $A is equal to $B and of the same type | $A===$B |
Increment/Decrement operators
The PHP increment operators are used to increase a variable’s value.
The PHP decrement operators are used to decrease a variable’s value
Operator | Name | Description |
++$a | Pre-increment | Increments $a by one, then returns $a |
$a++ | Post-increment | Returns $a, then increments $a by one |
–$a | Pre-decrement | Decrements $a by one, then returns $a |
$a– | Post-decrement | Returns $a, then decrements $a by one |
Logical operators
These logical operators are used to combine the statements.
Operator | Name | Example | Result |
and | And | $a and $b | True if both $a and $b are true |
or | Or | $ or $b | True if either $a or $b are true |
xor | Xor | $a xor $b | True if either $a or $b is true, but not both |
&& | And | $a&&$b | True if both $a and $b are true |
|| | Or | $a || $b | True if either $a or $b is true |
! | Not | !$a | True if $a is not true |
String operators
PHP has two operators for strings.
Operator | Name | Description |
. | Concatenation | Used to join the statements |
.= | Concatenation assignment | Append two statements |
Array operators
Operator | Name | Example | Result |
+ | Union | $a + $b | Union of $a and $b |
== | Equality | $a == $b | Returns true if $a and $b have the same value pairs |
=== | Identity | $a === $b | Returns true if $a and $b have the same value pairs in the same order and of the same types |
!= | Inequality | $a!=$b | Returns true if $a is not equal to $b |
<> | Inequality | $a<>$b | Returns true if $a is not equal to $b |
!== | Not identity | $a!==$b | Returns true if $a is not identical to $b |
Php Conditional statements
In PHP we have the following conditional statements:
if statement
It only executes code if condition is true
Syntax of if statement
if(condition)
{
//code;
}
if…else statement
It executes if code when a condition is true and else code when that condition is false
Syntax of if…else statement
if (condition) {
//code;
} else {
code to be executed if the condition is false;
}
if…elseif….else statement
Execution of different programs for more than two conditions.
if…else….else statement Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
Switch statement
The switch statement is to select the block of code for different conditions. Selects one of many blocks of code to be executed according to the conditions.
switch (n) {
case 1:
code to be executed if n=label1;
break;
case 2:
code to be executed if n=label2;
break;
case 3:
code to be executed if n=label3;
break;
…
default:
code to be executed if n is different from all labels;
}
Take a example of Switch case
<html>
<body>
<?php
$day = date(“D”);
switch ($day){
case “Mon”:
echo “Today is Monday”;
break;
case “Tue”:
echo “Today is Tuesday”;
break;
case “Wed”:
echo “Today is Wednesday”;
break;
case “Thu”:
echo “Today is Thursday”;
break;
case “Fri”:
echo “Today is Friday”;
break;
case “Sat”:
echo “Today is Saturday”;
break;
case “Sun”:
echo “Today is Sunday”;
break;
default:
echo “ohhh! which day is this ?”;
}
?>
</body>
</html>
Output: Today is Monday
Php Loops
Often when you write a code and want to run the code over and over again. For the execution of the same code again we can use looping. In PHP we have the following looping statements:
- While
- Do while
- For
- Foreach
While loop:
This loop executes the block of code as long as the specified condition is true.
Syntax:
while(condition)
{
Code to be executed;
}
Do while loop:
This loop executes the code once then after it will check the condition.
do{
Code to be executed;
}
while(condition)
For loop:
This loop runs the code at a specified number of times.
Syntax
for(initialization; test counter;increment)
{
Code to be executed;
}
Foreach loop
This loop is used through arrays.
Syntax
(array as value)
{
Code to be executed;
}
Php Functions
Php has more than a functions built-in function that is the real power of the PHP. The best thing with PHP is that we can create a function also that is known as a user-defined function.
- A user-defined function is a block of statements that can be used repeatedly in a program.
- It will not immediately execute when a page loads.
- It will be executed by a call to the function.
Php user-defined functions
- A user-defined function is a block of statements that can be used repeatedly in a program.
- It will not immediately execute when a page loads.
- It will be executed by a call to the function.
Create a user-defined function in PHP
A user-defined function declaration begins with the word function.
Syntax
function function name()
{
Code to be executed;
}
A function name can be started with an underscore or letter but not with the number. By convention, the function name is not case sensitive.Give a function that name which reflects what it does.
Let’s take an example
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMsg() {
echo “You are really a nice person, Have a nice day!”;
}
/* Calling a PHP Function */
writeMsg();
?>
</body>
</html>
Output: You are really a nice person, Have a nice day!
Php function Arguments
An argument is just like a variable and the information is passed to function through it. You can add as many arguments as you want just by separating them with a comma.
Take an example:
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo “$fname devenson.<br>”;
}
familyName(“Jani”);
familyName(“Hege”);
familyName(“Stale”);
familyName(“Kai”);
familyName(“Borge”);
?>
</body>
</html>
Output:
Jani Devenson.
Hege Devenson.
Stale Devenson.
Kai Devenson.
Borge Devenson.
Php default Argument value
If we call the function without argument it will take the default value.
<!DOCTYPE html>
<html>
<body>
<?php
function setheight($height = 50) {
echo “The height is : $height <br>”;
}
setheight(250);
setheight();
setheight(235);
setheight(180);
?>
</body>
</html>
output: The height is: 250
The height is: 50
The height is: 235
The height is: 180
Passing Arguments by Reference
It is possible to pass arguments to the tasks by reference. This means that instead of copying the value of the variable, the function’s reference to the variables is manipulated.
If any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding the ampersand (&) to the variable name in the function call or function definition.
Php function returning value
To let the function return value, use the return statement.
<?php
function sum($a, $b) {
$c = $a + $b;
return $c;
}
echo “15+ 50 = ” . sum(15, 50) . “<br>”;
echo “17 + 23 = ” . sum(17, 23) . “<br>”;
echo “12 +2 4 = ” . sum(12, 24);
?>
Output:
It will return the value
15 + 50 = 65
17 + 23 = 40
12 +2 4 =3 6
Php Arrays
An array is a special variable which can store multiple values of the same data types and you can access the values by using to an index number. The array is created by using an array() function.There are three types of the array in PHP
- Indexed arrays or Numeric arrays
- Associative arrays
- Multidimensional arrays
Indexed arrays or Numeric arrays
An array with a numeric index in which values are stored and accessed in a linear fashion.
Example:
In php it assigned automatically
$days = array(“Mon”, “Tue”, “Wed”);
Index assign manually:
$days[0] = “Mon”;
$days[1] = “Tue”;
$days[2] = “Wed”;
Associative arrays
An array with strings as an index in which element values are stored in association with key values.
Example:
$age = array(“Rohan”=>”35”, “Shyam”=>”37”, “Sunil”=>”43”);
Or
$age[‘Rohan’] = “35”;
$age[‘Shyam’] = “37”;
$age[‘Sunil’] = “43”;
Multidimensional arrays
It contains one or more arrays and the values are accessed using multiple indices.
Example:
$cars = array
(
array(“Toyota”,22,18),
array(“BMW”,15,13),
array(“Mercedes”,5,2),
array(“Land Rover”,17,15)
);
To access the values we have to set it in the form of row and column.
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array(“Toyota”,22,18),
array(“BMW”,15,13),
array(“Mercedes”,5,2),
array(“Land Rover”,17,15)
);
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>”;
?>
</body>
</html>
Output:
Toyota: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Mercedes: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
To get the length of the array count() function is used.
Php sort function for Arrays
- sort() – This function is used to sort arrays in ascending order
- rsort() – It is used to sort arrays in descending order
- asort() – This is to sort associative arrays in ascending order, according to the value
- ksort() – To sort associative arrays in ascending order, according to the key
- arsort() – This function is used to sort associative arrays in descending order, according to the value
- krsort() – It is used to sort associative arrays in descending order, according to the key
PHP Global Variables- SuperglobalsVarious predefined variables in PHP are “superglobals” means they are always accessible regardless of scope, it can access from any file, function or class. These are as follows:
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_FILES
- $_ENV
- $_COOKIE
- $_SESSION
Get and Post Method
There are two ways by which the browser can send information to the web server.
- The GET Method: It requests data from a particular resource.
- The POST Method: It submits data to be processed to a particular resource.
The GET MethodThe GET method sends the encoded user information attached to the page request. Page and encoded information are separated by? Character.
- GET method produces a long string appearing in your server log in the Browser’s Location: box.
- The GET method is restricted to sending up to 1024 characters only.
- Never use the GET method if you have passwords or other sensitive information sent to the server.
- GET cannot be used to send binary data, such as a picture or word document to the server.
- Data sent by GET method can be accessed using the QUERY_STRING environment variable.
- The $ _GET companion array provides access to all sent information using PHP GET method.
The POST MethodPOST method transfers information through HTTP header. The information described in the case of GET method has been coded and is placed in the title named QUERY_STRING.
- There is no restriction on the data size to be sent to the POST method.
- The POST method can be used to send ASCII and binary data.
- The data sent by POST method goes through the HTTP header hence the security depends on the HTTP protocol. By using secure HTTP you can ensure that your information is safe.
- The $ _POST provides associative array for accessing all sent information using PHP POST method.
The $_REQUEST variable
- The PHP $ _REQUEST variable contains content of $ _GET, $ _POST and $ _COOKIE. When we tell about cookies, we will discuss the $ _COOKIE variable.
- PHP $ _REQUEST variable can be used to get results from form data sent with both GET and POST methods.
File Handling in PHP
- Opening a file: fopen()
- Reading a file: fread()
- Writing a file: fwrite()
- Closing a file: fclose()
Opening and Closing of fileThe fopen () function is used to open a file. In order to operate the first file name and the mode, two arguments are required.It is important to close the file with the fclose () function after making the changes in the opened file. The fclose () function requires file pointer as its argument and then returns back when it is closed or failed.
Reading a FileOnce a file is opened using the Fopen () function, it can be read with a function called Fread () and two arguments are required. These file pointer and bytes should have the length of the file being expressed.Files can be found using the filesize () function, which takes the file name as its arguments and returns the size of the file expressed in the bytes.
Writing a file
A new file can be written or text can be added to the existing file using the fwrite () function. For this function, two arguments that specify the file indicator and the string of data that are required to be written. Alternatively, a third integer argument can be used to specify the length of the data to write. If the third argument is included, the writing will be closed after reaching the specified length.
Take a look of a few programs which are mentioned below:
For loop
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo “The number is: $x <br>”;
}
?>
</body>
</html>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
While loop
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
echo “The number is: $x <br>”;
$x++;
}
?>
</body>
</html>
Output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Array
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array(“Volvo”, “BMW”, “Toyota”);
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo “<br>”;
}
?>
</body>
</html>
Output
Volvo
BMW
Toyota
File handling
<!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen(“dictionary.txt”, “r”) or die(“Unable to open file!”);
echo fread($myfile,filesize(“dictionary.txt”));
fclose($myfile);
?>
</body>
</html>
Output
Unable to open file!