Monday, 5 August 2019

Introduction to PHP


Chapter 4:-Introduction to PHP

Characteristics Of PHP

Familiarity: -
If you are in programming background then you can easily understand the PHP syntax. And you can write PHP script because of most of PHP syntax inherited from other languages like C or Pascal.

Simplicity: -
PHP provides a lot of pre-define functions to secure your data. It is also compatible with many third-party applications, and PHP can easily integrate with other.
In PHP script there is no need to include libraries like c, special compilation directives like Java, PHP engine starts execution from (<?) escape sequence and end with a closing escape sequence (<?). In PHP script, there is no need to write main function. And also you can work with PHP without creating a class.

Efficiency: -
PHP 4.0 introduced resource allocation mechanisms and more pronounced support for object-oriented programming, in addition to session management features. Eliminating unnecessary memory allocation.

Security: -
Several trusted data encryption options are supported in PHP’s predefined function set. You can use a lot of third-party applications to secure our data, allowing for securing our application.

Flexibility: -
You can say that PHP is a very flexible language because of PHP is an embedded language you can embed PHP scripts with HTML, JAVA SCRIPT, WML, XML, and many others. You can run your PHP script any device like mobile Phone, tabs, laptops, PC and other because of PHP script execute on the server then after sending to the browser of your device.

Free: -
PHP is an open source programming language so you can download freely there is no need to buy a licence or anything.

Object Oriented: -
PHP has added some object-oriented programming features, and Object Oriented programming became possible with PHP 4. With the introduction of PHP 5, the PHP developers have really beefed up the object-oriented features of PHP, resulting in both more speed and added features.

PHP lexical structure

Computer languages, like human languages, have a lexical structure. A source code of a PHP script consists of tokens. Tokens are atomic code elements. In PHP language, we have comments, variables, literals, operators, delimiters, and keywords.

PHP comments
Comments are used by humans to clarify the source code. All comments in PHP follow the #character.
<?php
# ZetCode 2016
echo "This is comments.php script\n";
 ?>

Single line comment
// comments.php
// author Jan Bodnar
// ZetCode 2016

Multiline comment
/*
 comments.php
 author Jan Bodnar
 ZetCode 2016
*/

PHP semicolon
A semicolon is used to mark the end of a statement in PHP. It is mandatory.
$a = 34;
$b = $a * 34 - 34;
echo $a;

The variables are case sensitive. This means that $Price, $price, and $PRICE are three different identifiers.
<?php
$number = 10;
$Number = 11;
$NUMBER = 12;
echo $number, $Number, $NUMBER;
echo "\n";
?>

PHP constants
A constant is an identifier for a value which cannot change during the execution of the script. By convention, constant identifiers are always uppercase.

<?php
define("SIZE", 300);
define("EDGE", 100);
 #SIZE = 100;
echo SIZE;
echo EDGE;
echo "\n";
?>

PHP Data Types
Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

PHP String

A string is a sequence of characters, like "Hello world!".
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
•An integer must have at least one digit
•An integer must not have a decimal point
•An integer can be either positive or negative
•Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
<html>
<body>
<?php 
$x = 5985;
var_dump($x);
?> 
</body>
</html>

int(5985)

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential form.
<html>
<body>
<?php 
$x = 10.365;
var_dump($x);
?> 
</body>
</html>

Float(10.365)

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;

PHP Array

An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:

<html>
<body>
<?php 
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?> 
</body>
</html>

array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }


PHP Variables

A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is used to store data temporarily.
In PHP, a variable is declared using $ sign followed by variable name.
PHP Variable: Declaring string, integer and float

<?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:
string is: hello string
integer is: 200
float is: 44.6

Sum of two variables

<?php 
$x=5; 
$y=6; 
$z=$x+$y; 
echo $z; 
?>

case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc.
<?php 
$color="red"; 
echo "My car is " . $color . "<br>"; 
echo "My house is " . $COLOR . "<br>"; 
echo "My boat is " . $coLOR . "<br>"; 
?> 

PHP Variable: Rules

PHP variables must start with letter or underscore only.
PHP variable can't be start with numbers and special symbols.
<?php 
$a="hello";//letter (valid) 
$_b="hello";//underscore (valid) 
echo "$a <br/> $_b"; 
?> 

PHP $ and $$ Variables

The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc.
The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

<?php 
$x = "abc"; 
$$x = 200; 
echo $x."<br/>"; 
echo $$x."<br/>"; 
echo $abc; 
?> 

abc
200
200


Typecasting IN PHP:

The meaning of type casting is to use the value of a variable with different data type. In other word typecasting is a way to utilize one data type variable into the different data type.
We can cast following data type variable in PHP
•(int), (integer) - cast to integer
•(bool), (boolean) - cast to boolean
•(float), (double), (real) - cast to float
•(string) - cast to string
•(array) - cast to array
•(object) - cast to object

Example
(int) operator   changes type to Integer
(float) operator   changes type to Float

Example:-
$a=”5”;
$b=(int)$a;
$a=(int)$a;


Type juggling

Php variables can store integers,floating point,strings and more.
The conversion of a value from one type to another is called  casting.This kind of implicit casting is called type juggling in php.

Type of first operand is Integer and Type of second operator Floating point
Result is The integer is converted to a floating point.

Type of first operand is Integer and Type of second operator  String
Result is  String  is converted to a integer

Type of first operand is Floating point   and Type of second operator String
Result is The string is converted to a floating point.

<?php
$x=”3.14 pies”*2;
echo”$x=$x”;
?>

$x=6.28


Control structure

PHP If Statement

PHP if statement is executed if condition is true.
Syntax
if(condition){ 
//code to be executed 
} 

<?php 
$num=12; 
if($num<100){ 
echo "$num is less than 100"; 
} 
?> 
Output:
12 is less than 100

PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
Syntax
if(condition){ 
//code to be executed if true 
}else{ 
//code to be executed if false 
} 
<?php 
$num=12; 
if($num%2==0)
{ 
echo "$num is even number"; 
}else{ 
echo "$num is odd number"; 
} 
?> 
Output:
12 is even number

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.
Syntax
switch(expression){     
case value1:     
 //code to be executed 
 break; 
case value2:     
 //code to be executed 
 break; 
......     
default:      
 code to be executed if all cases are not matched;   
} 

<?php   
$num=20;   
switch($num)
{   
case 10:   
echo("number is equals to 10");   
break;   
case 20:   
echo("number is equal to 20");   
break;   
case 30:   
echo("number is equal to 30");   
break;   
default:   
echo("number is not equal to 10, 20 or 30");   
}  
?>   
Output:
number is equal to 20

PHP For Loop
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if number of iteration is known otherwise use while loop.
for(initialization; condition; increment/decrement){ 
//code to be executed 
} 

<?php 
for($n=1;$n<=10;$n++)
{ 
echo "$n<br/>"; 
} 
?> 

1 2 3 4 5 6 7 8 9 10

PHP While Loop
PHP while loop can be used to traverse set of code like for loop.
It should be used if number of iteration is not known.
while(condition)
{ 
//code to be executed 
} 

<?php 
$n=1; 
while($n<=10)
{ 
echo "$n<br/>"; 
$n++; 
} 
?> 

1 2 3 4 5 6 7 8 9 10

PHP do while loop
PHP do while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.
It executes the code at least one time always because condition is checked after executing the code.
do
{ 
//code to be executed 
}while(condition); 

<?php 
$n=1; 
do
{ 
echo "$n<br/>"; 
$n++; 
}while($n<=10); 
?> 

1 2 3 4 5 6 7 8 9 10


GET vs. POST

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
<html> 
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

welcome_get.php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

<html> 
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

PHP: $_REQUEST
$_REQUEST is a super global variable which is widely used to collect data after submitting html forms
The PHP built-in $_REQUEST function can be used with both the GET and POST methods
<html>
<body>
<form action="test.php" method="post">
Your name: <input type="text" name="yourname" />
<input type="submit" />
</form>
</body>
</html>

test.php
Welcome <?php echo $_REQUEST ["yourname"]; ?>

PHP Echo
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 "Hello by PHP echo"; 
?> 

echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
<html>
<body>
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
</body>
</html>

PHP is Fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters

<html>
<body>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
</body>
</html>

PHP is Fun!
Hello world!
I'm about to learn PHP!