UG-OSS-U4
UG-OSS-U4
PHP Introduction
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used to
develop web applications (an application that executes on the server and generates the dynamic
page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0 is the latest version of PHP, which was released on 28 November.
http://localhost/php-examples/programName.php
The http://localhost refers to the path c:\xampp\htdocs
Example Program
Following is the first example of PHP script
<html>
<head>
<title> PHP Demo </title>
</head>
<body>
<?php
$i=10;
echo"<h3> Welcome to first PHP Document </h3>";
echo "The value of variable is = $i";
?>
</body>
</html>
PHP Scripting
PHP runs on different operating systems, like Windows, UNIX, Linux and supports
different databases like MySQL, Microsoft Access, and Oracle. PHP can not only collect form data,
but it can also create, read, write, delete, and close files on the server.
It can be easily embedded in HTML. PHP code is embedded in HTML with tags <?php ?>.
PHP is one of the easier programming languages to learn. PHP features a solid ecosystem of
resources for beginners and it encompasses a syntax that is forgiving to beginners.
One-line comments
The one-line comment is placed at the end of the line or at the current block.
A one-line comment starts with the pound (#) or double forward-slash (//). The rest of the text
after the (//) is ignored by the PHP interpreter.
Multi-line comments
A Multi-line comment start with /* and end with */. For example:
<?php
/*
This is an example of a multi-line comment,
which can span multiple lines.
*/Code language: HTML, XML (xml)
In practice, you use the multi-line comment when you need to span comments multiple lines.
For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
Name Example Explanation
Operator
The value of right operand is assigned to the left
= Assign $a = $b
operand.
+= Add then Assign $a += $b Addition same as $a = $a + $b
Subtract then
-= $a -= $b Subtraction same as $a = $a - $b
Assign
*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b
Divide then Assign
/= $a /= $b Find quotient same as $a = $a / $b
(quotient)
Divide then Assign
%= $a %= $b Find remainder same as $a = $a % $b
(remainder)
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
Operator Name Example Explanation
Bits that are 1 in both $a and $b are set to 1, otherwise
& And $a & $b
0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1
^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of
comparison operators are given:
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.
Operator Name Example Explanation
and And $a and $b Return TRUE if both $a and $b are true
Or Or $a or $b Return TRUE if either $a or $b is true
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
! Not ! $a Return TRUE if $a is not true
&& And $a && $b Return TRUE if either $a and $b are true
|| Or $a || $b Return TRUE if either $a or $b is true
String Operators
The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:
PHP Variables
Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric values,
memory addresses, and strings. PHP has its own way of declaring and storing variables.
There are a few rules, that need to be followed and facts that need to be kept in mind
while dealing with variables in PHP:
Any variables declared in PHP must begin with a dollar sign ($), followed by the variable
name.
A variable can have long descriptive names (like $factorial, $even_nos) or short names
(like $n or $f or $x)
A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-
Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number.
A constant is used as a variable for a simple value that cannot be changed. It is also case-
sensitive.
Assignment of variables is done with the assignment operator, “equal to (=)”. The variable
names are on the left of equal and the expression or values are to the right of the
assignment operator ‘=’.
One must keep in mind that variable names in PHP names must start with a letter or
underscore and no numbers.
PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values. The same happens
while conversion. No variables are declared before they are used. It automatically
converts types from one type to another whenever required.
PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
Output:
string is: hello string
integer is: 200
float is: 44.6
Variable Scopes
Scope of a variable is defined as its extent in a program within which it can be accessed, i.e. the
scope of a variable is the portion of the program within which it is visible or can be accessed.
Depending on the scopes, PHP has three variable scopes:
Local variables: The variables declared within a function are called local variables to that
function and have their scope only in that particular function. In simple words, it cannot be
accessed outside that function. Any declaration of a variable outside the function with the same
name as that of the one within the function is a completely different variable. We will learn about
functions in detail in later articles. For now, consider a function as a block of statements.
Global variables: The variables declared outside a function are called global variables. These
variables can be accessed directly outside a function. To get access within a function we need to
use the “global” keyword before the variable to refer to the global variable.
Static variable: It is the characteristic of PHP to delete the variable, once it completes its
execution and the memory is freed. But sometimes we need to store the variables even after the
completion of function execution. To do this we use the static keywords and the variables are
then called static variables. PHP associates a data type depending on the value for the variable.
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the specified
condition is true.
Syntax
if(condition){
//code to be executed
}
Example
<?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.
If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output:
12 is even number
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can
check multiple conditions using this statement.
Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
Output:
B Grade
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 Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops.
Loops are used to execute the same block of code again and again, as long as a certain condition
is true.
In PHP, we have the following loop types:
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
foreach - loops through a block of code for each element in an array
Example
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-
each loop. If you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the
current flow of the program at the specified condition and program control resumes at the next
statements outside the loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach loop,
and also with switch case.
Syntax
jump statement;
break;
Array
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.
Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
OUTPUT
Season are: summer, winter, spring and autumn
<?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:
Season are: summer, winter, spring and autumn
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:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
PHP Functions
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.
Output:
Hello Sonoo
Hello Vimal
Hello John
Let's see the example to pass two argument in PHP function.
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old
Note: GET should NEVER be used for sending passwords or other sensitive information!
File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if it
w
doesn't exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File pointer starts at
a
the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for read/write. Erases the contents of the file or creates a new file if it
w+
doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. The existing data in file is preserved. File pointer starts at
a+
the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "John Doe" and second contained "Jane Doe". After we finished
writing, we closed the file using the fclose() function.
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing
file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just
wrote is present:
Mickey Mouse
Minnie Mouse
PHP Cookies
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.
A cookie is often used to identify a user. A cookie 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, you can both create and retrieve cookie values.
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?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
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.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color, etc). By default, session variables last until the user closes
the browser.
So; Session variables hold information about one single user, and are available to all pages in one
application.
Tip: If you need a permanent storage, you may want to store the data in a database.
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
MySQLi Object-Oriented:
$conn->close();