DOC-20241209-WA0009.
DOC-20241209-WA0009.
DOC-20241209-WA0009.
INTRODUCTION TO PHP
INTRODUCTION TO PHP AND A BRIEF HISTORY OF PHP
PHP started out as a small open source project that evolved as more and more people
found out how usefull it was.
Rasmus Lerdorf unleashed the first version of php way back in 1994.
● PHP is a recursive acronym for “PHP Hypertext Preprossesor”.
● PHP is a server side scripting language that is embedded in HTML . It is used to
manage dynamic content , database ,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 architechture (COM
and COBRA) making their devlopement a posibilty for the first time.
● PHP is forgiving : PHP language tries to be as forgiving as possible
● PHP syntax is C – like.
Before you continue you should have a basic understanding of the following :
● HTML
● CSS
● Javascript
INSTALLING PHP
After installing the webserver , we need to install PHP it self. It will work together with
the apache webserver we just installed, to allow the webserver to process PHP
documents and return the content to the client . To read more about how this works
,have a look at the introduction chapters . in ase you started Apache before , close it
down now – otherwise the PHP installer might not able to modify the required files!
Start the installation , and proced through it . You will be asked for a location to install
to the default is fine , although you may select another path if you wish too. The first
interesting screen will look like this:
What is PHP ?
● PHP is an actronynmfor “PHP. Hypertext Preprocessor”
● PHP is widely used ,open source scripting language.
● PHP scripts are executed on the server.
● PHP is free to download and use
What is a PHP file ?
● PHP files can contain text, HTML ,CSS ,JavaScript and PHP code
● PHP code are executed on the server, and the result to the browser as plain
HTML.
● PHP files have extension “.php”.
What does PHP Do ?
● PHP can generate dynamic , page content
● PHP can create , open ,read , write,delete, and close files on the server.+
● PHP can collect from data
● PHP can send and recive cookies.
● PHP can add, delete,modify data in your database.
● PHP can be used to control user-access.
● PHP can encrypt data.
Walk through PHP language Basics:LexicalStuructures
The lexical structure of programming languages is the set of basic rules that governs
how you you write programs in that language . It is the lowest level syntax of the
language and specifies such things as what variable names look like, what characters
are used for commentsband how programs statements are separated from each other.
Case sensitivity
In PHP , all keywords(e.g if , else, while, echo,etc),classes , functions, and
user-defined functions are NOT case-sensitive.
For example , you can write echo construct ways like Echo , ECHO, echo oryou can
write date function like Date,DaTe,date.
// Program to check case sensitivity
<?php
echo “Welcome to PHP”. “<br>”;
ECHO “welcome”. “<br>”;
Echo “php”. “<br>”;
echo Date(“Y/m/d”). “<br>”;
echo DATE(“Y.m.d”). “<br>”;
echo Date(“Y-m-d”);
?>
Output :
Welcome to PHP
welcome
php
2022/10/05
2022.10.05
2022-10-05
You can write pre-defined function in any case let’s take the example of
rand() function
<?php
$random _number=rand();
Echo “<br>Random number = “.
$random_number;
$random_number1=RAND();
Echo “<br>Random number = “.
$random_number1;
$random_number2=Rand();
Echo “<br>Random number = “.
$random_number2;
?>
Output :
Random number = 21438
Random number = 15391
Random number = 15212
There are three variables in this example first is “variable1” second is “variable2” and
the third one is “sum” . The value of variables displayed , perform an operation and
store the value of an another named $sum and print.
Example of case sensitive variables
<?php
$a = 7;
$A = 38;
echo $a. “<br>”;
echo $A;
?>
Output
7
38
$a and $A are not same as shown in the above example. Beacause PHP variable name
are case sensitive.
Rules For Variable Decleration
There are some simple rules for creating PHP variable.
● A PHP variable must start with ($) doller sign.
● A valid PHP variable name start with underscore(_) or alphabet.
● The rest of variable name consists of alphanumeric character like acb1.
● PHP variable can any length.
● Uppercase letter is not equal to the lowercase letter.
● Not contain spaces.
PHP Variable Decleration
A variable is a named memory location that contains data that may be manipulated
throughout the execution of the script.
//PHP FOR VARIABLE DECLERATION
<?php
$name = “welcome to php”;
Echo $name;
Echo “<br>”;
$first_value=12.30;
$d1=450;
Echo “The first value :”.$first_value;
Echo “<br>”;
Echo “The second value:”.$d1;?>
Output
Welcome to php
The first value : 12.30
The second value : 450
You can create PHP variable anywhere by using the doller sign in our PHP script.
In this example $name is a string variable , $first_value is the float value and $d1 is a
integer value.
Displaying Variables values
The fastest way to display the variable value , using print_r statement.
$name = “Usha”; $name = “Usha “;
Print_r($name); Echo ($name);
Data Types
Most of other language like C/C++ and java require specifying what kind of data it can
hold , but in PHP there is no need to specifying data type before using it . All the data
store in PHP variable . Data types are the backbone of any programminglanguage.
<?php
$test=15;
$test1=38;
$mul=$test*$test1;
Echo “First value = “.$test. “<br>”;
Echo “Second value = “.$test1. “<br>”;
Echo “Result =”.$mul;
?>
Output :
First value = 15
Second value = 38
Result = 570
In this example $test, $test1 are the integer type variable , after multiplying the $test
and $test1 stores the value into $mul variable. You can use gettype function tocheck
the data type of the variable.
Data types in PHP Under Various Categories Are Shown Below
● String
● Integer
● Floating point numbers
● Boolean
● Array
● Object
● Null
Hirarchy of Data Types
1. Scaler Data Type
2. Compound Data Type
3. Special Data Type
Integer
An integer is an integral whole number without a decimal point .Integer numbers
are used for counting purpose like 38, 8 etc.
<?php
$x = 5985;
var_dump($x);
?>
Output :int(5985)
Float
Float variables hold fractionalvalues ,like 38.02,7.652 etc it’s used for banking
and financial sector calculation
<?php
$x = 10.365;
var_dump($x);
?>
Output :float(10.365)
String
A string is defined as a character array , like john,caretc .
it’s used for storing array of character.
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output :Hello world!
Hello world!
Boolean
Boolean variables hold true or false.
$x = true;
$y = false;
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:
<?php
$cars
= array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output :
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Object :
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.
Let's assume we have a class named Car. A Car can have properties like model, color,
etc. We can define variables like $model, $color, and so on, to hold the values of these
properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for
the properties.
If you create a __construct() function, PHP will automatically call this function when
you create an object from a class.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . "" . $this->model . "!";
}
}
Output:
My car is a black Volvo!
My car is a red Toyota!
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output :
NULL
● Null is not a string it is a special data type that means does not have any value
you can check by using if-else.
**PHP Operators
Operators are used to perform operations on variables and values .PHP divides the
operators in following groups
● Arithmetic operator
● Assignment operator
● Comparison operator
● Increment /Decrement operator
● Logical operator
● String Operator
● Array operator
Addition
Example :
<?php
$x = 10;
$y = 6;
echo $x + $y;
?>
Output : 16
Substraction
Example :
<?php
$x = 10;
$y = 6;
echo $x - $y;
?>
Output : 4
Multiplication
Example :
<?php
$x = 10;
$y = 6;
echo $x * $y;
?>
Output : 60
Division
Example:
<?php
$x = 10;
$y = 6;
echo $x / $y;
?>
Output : 1.6666666666667
Modulus
Example :
<?php
$x = 10;
$y = 6;
echo $x % $y;
?>
Output : 4
Exponentiation
Example :
<?php
$x = 10;
$y = 3;
echo $x ** $y;
?>
Output : 1000
AssignmentOperator
The PHP assignmetoperaotor are usedwithnumeric values to write a value to a variable.
The basic assignmetoperator in PHP is = . It meansthat the leftoperandgets set to the
value of the assignment expression on the right.
Example :
<?php
$x = 10;
echo $x;
?>
Output :10
<?php
$x = 20;
$x += 100;
echo $x;
?>
Output :120
<?php
$x = 50;
$x -= 30;
echo $x;
?>
Output : 20
<?php
$x = 5;
$x *= 6;
echo $x;
?>
Output :30
<?php
$x = 10;
$x /= 5;
echo $x;
?>
Output :2
<?php
$x = 15;
$x %= 4;
echo $x;
?>
Output :3
Comparison Operators :
The PHP comparison operators are used to compare two values (number or string):
Example
<?php
$x = 100;
$y = "100";
var_dump($x == $y); // returns true because values are equal
?>
Output : bool(true)
<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
Output :bool(false)
<?php
$x = 100;
$y = "100";
var_dump($x != $y); // returns false because values are equal
?>
Output :bool(false)
<?php
$x = 100;
$y = "100";
var_dump($x <> $y); // returns false because values are equal
?>
Output : bool(false)
<?php
$x = 100;
$y = "100";
var_dump($x !== $y); // returns true because types are not equal
?>
Output : bool(true)
<?php
$x = 100;
$y = 50;
var_dump($x > $y); // returns true because $x is greater than $y
?>
Output : bool(true)
<?php
$x = 10;
$y = 50;
var_dump($x < $y); // returns true because $x is less than $y
?>
Output : bool(true)
<?php
$x = 50;
$y = 50;
var_dump($x >= $y); // returns true because $x is greater than or equal to $y
?>
Output : bool(true)
<?php
$x = 50;
$y = 50;
var_dump($x <= $y); // returns true because $x is less than or equal to $y
?>
Output : bool(true)
<?php
$x = 5;
$y = 10;
echo ($x <=> $y); // returns -1 because $x is less than $y
echo "<br>";
$x = 10;
$y = 10;
echo ($x <=> $y); // returns 0 because values are equal
echo "<br>";
$x = 15;
$y = 10;
echo ($x <=> $y); // returns +1 because $x is greater than $y
?>
Output : -1
0
1
Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Post-increment
<?php
$x = 10;
echo $x++;
?>
Output 10
Pre-decrement
<?php
$x = 10;
echo --$x;
?>
Output 9
Post-decrement
<?php
$x = 10;
echo $x--;
?>
Output 10
Logical operator
The PHP logical operator are used to combine conditional statements
Example
<?php
$x = 100;
$y = 50;
if ($x == 100 and $y == 50) {
echo "Hello world!";
}
Else{
Echo “ Not Equal”;
}
?>
Output : Hello world!
<?php
$x = 100;
$y = 50;
if ($x == 100 or $y == 80) {
echo "Hello world!";
}
?>
Output : Hello world!
<?php
$x = 100;
$y = 50;
if ($x == 100 xor $y == 80) {
echo "Hello world!";
}
?>
Output : Hello world!
<?php
$x = 100;
$y = 50;
if ($x == 100 && $y == 50) {
echo "Hello world!";
}
?>
Output : Hello world!
<?php
$x = 100;
$y = 50;
if ($x == 100 || $y == 80) {
echo "Hello world!";
}
?>
Output : Hello world!
<?php
$x = 100;
if ($x !== 90) {
echo "Hello world!";
}
?>
Output : Hello world!
String Operators
PHP has two operators that are specially designed for strings.
Example :
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
Output : Hello world!
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
Output : Hello world!
Array Operators
The PHP array operators are used to compare arrays.
operator Name Example Result
+ Union $x+$y Union of $x and $y
== Equality $x==$y Returns true if $x and $y have
the same key/value pairs
=== Identity $x===$y Returns true if $x and $y have
the same key/value pairs in
the same order and of the
same type
!= Inequality $x!=$y Return true if $x is not equal to
$y
<> Inequality $x<>$y Return true if $x is not equal to
$y
!== Non-identity $x!==$y Return true if $x is not
identical to $y
Example :
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
print_r($x + $y); // union of $x and $y
?>
Output : Array ( [a] => red [b] => green [c] => blue [d] => yellow )
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x == $y);
?>
Output :bool(false)
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x === $y);
?>
Output :bool(false)
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x != $y);
?>
Output :bool(true)
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x <> $y);
?>
Output :bool(true)
<?php
$x = array("a" =>"red", "b" =>"green");
$y = array("c" =>"blue", "d" =>"yellow");
var_dump($x !== $y);
?>
Output :bool(true)
● If……else statement - use this statement if you want to execute a set of code
when a condition is true and another if the condition is not true.
● Elseif statement – is used with the if…….else statement to execute a set of
code if one of the several condition is true
● Switch statement – is used if you want to select one of many blocks of code to
be executed . use the switch statement. The switch statement is used to avoid
● long blocks of if…..elseif…..else code
Very often wen you write code , you want to perform different actions for
different conditions in PHP we have the following conditional statements
● if statement - executes some code if one condition is true
● if….else statement – executes some code if a condition is true and another
code if that condition is false.
● if…..elseif….else statement – executes different codes for more than two
conditions.
● switch statements – selects one of many blocks of code to be executed.
If statement
If statement executes some code if one condition is true . this is primary decision
making statement in PHP.
Syntax
if (condition)
{
code to be executed if condition is true;
}
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
?>
Output :Have a good day!
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
Else
{
echo "Have a good evening!";
}
?>
Output :Have a good day!
In the above example the condition is not true so that it skips the one line just after
the “if statement” but “else statement” must be executed.
PHP – The if…..elseif….else Statement
The if…..elseif…else statement executes codes for more than two conditions
Syntax
if (condition)
{
code to be executed if this condition is true;
}
elseif (condition)
{
code to be executed if first condition is false and this condition is true;
}
else
{
code to be executed if all conditions are false;
}
Example :
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
}
elseif ($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Example
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favoritecolor is red!";
break;
case "blue":
echo "Your favoritecolor is blue!";
break;
case "green":
echo "Your favoritecolor is green!";
break;
default:
echo "Your favoritecolor is neither red, blue, nor green!";
}
?>
Output :Your favoritecolor is red!
PHP Loops
Often when you write
a code, you want the same block of code to run over and over again in a row. Instead
of adding sevral almost equal code_lines in a script , we can use loops to perform a
task line this.
In PHP , we have the following looping statements:
● 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 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.
The PHP while loop
The expression inside the parenthese is tested ; if it evaluates to true, the code block
inside the braces is executed. Then the expression is tested again if at any point the
expression return false, the loop exists.
● While loop will execute block of code until certain condition is met.
● Function of while loop do a task again and again (as your condition).
Flow Chart
Syntax
while (condition is true) {
code to be executed;
}
Example
<?php
$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>
Output :
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
In the above example, first assign the value of $i=0 and after that checks $i less than
7,if yes , it will be executed first time and check again if it finfd true then again it will
be executed, if any point of time the expression returns fails , the loop will be
terminated
Note :There must use the same expression (that are used in a while condition )in
while loop body otherwise loop will be never terminated. This type of the unterminated
loop is called infinite loop.
The PHP do….while Loop
● A do while loop code block executed at least one time before checking the
expression.
● A do while loop is a modified version of the while loop.
Syntax
do {
code to be executed;
} while (condition is true);
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output :
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
In above example , the condition is not true instead of data in between do block will be
executed and after that check the condition and loop terminated.
The PHP for loop
A for loop is usually used when the exact number of times a block of code must
execute is known in advance.
The for loop is the easiest way to understand of the PHP loops.
● The initialization state of a variable is setting a loop counter to an initial value.
● It’s involving the relational operator , test the loop counter to determine whether
its value has reached the number of repetations desired.
● Increment or decrement the value of the counter each time.
Syntax
for (init counter; test counter; increment
counter) {
code to be executed for each iteration;
}
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
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
The PHP foreach Loop
Foreach is a special kind of looping statement that works only on arrays. You can use it
in two wyas . You can either retrive just the value of each element or you can retrive
the element’s key and value.
syntax
foreach ($array as $value) {
code to be executed;
}
Example
1. The following example will output the values of the given array
($colors):
<?php
$colors = array()
?>
Output :
red
green
blue
yellow
2. The following example will output both the keys and the values of the
given array ($age):
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Install PHP
In this page we will install PHP5.
Step1. Again open up the terminal (Applications>Accessories>Terminal).
Step2. Copy /paste or type the following line into terminal and press enter: sudo
apt-get install php5 libapache2-mod-php5
Step3. In order for PHP to work and to be compatible with Apache we must restart
Apache. Sudo /etc/init.d/apache2 restart
Test PHP
To ensure there are no issues with PHP let’s give it a quick test run.
Step1. In the terminal copy/paste or type the following line:
Sudogedit /var/www/testphp.php
This will open up a file called testphp.php.
Step2. Copy/paste this line into the php test file:
<?phpphpinfo();?>
Step3. Save and close the file.
Step4. Now open you’re web browser and type the following into the web address:
http://localhost/testphp.php
(it will show you the page that has all information about your php. If you have prior
experience of installing php in some other OS , you must have seen this page .)
Congrates you have now installed both Apache and PHP.
Install MySQL
To finish this guide up we will install MySQL.
Step1. Once again open up the amazing terminal and then copy/paste or type this line:
sudo apt-get install mysql-server
Step2. (optional) In order for other computers on your network to view the server you
have created , you must first edit the “Bind Address”. Begin by opening up Terminal to
edit the my.cnf file.
Gksudogetdit/etc/mysql/my.cnf
Change the line
Bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.
(In Linux Mint 11, terminal itself asked to the set password , But if it doesn’t follow the
stemp3.)
Step3. This is where things may start to get tricky. Begin by typing the following into
terminal:
Mysql -u root
Following that copy/paste or type this line:
Mysql>SET PASSWORD FOR ‘root’@ ‘localhost’=PASSWORD(‘yourpassword’);
(Make sure to change yourpassword to a password of your choice.)
Step4. We are now going to install a program called phpMyAdmin which is an easy tool
to edit your databases. Copy/Paste or type the following line into terminal.
Sudo apt-get install libaapache-mod-auth-mysql php5-mysql phpMyAdmin
After that is installed our next task is to get PHP to work with MYSQL . To do this we
will need to open a file entitled php.ini. To open it type the following:
Gksudogedit / etc/php5/apache2/php.ini
Now we are going to have to uncomment the following line by taking out the
semicolon(;).
Change this line:
;extension=mysql.so
To look like this:
Extension=mysql.so
Now just restart Apache and you are all set!
Sudo /etc/init.d/apache2 restart.
UNIT II(FUNCTIONS)
Introduction
A function is a named block of code that performs a specific task, possibly acting upon
a set of values given to it, or parameters, and possibly returning a single value.
Functions save on compile time-no matter how many times you call them , functions
are compiled only once for the page. They also improve relieablity by allowing you to
fix any bugs in one place, rather than everywhere you perform a task, and they
improve readability by isolating code that performs specific tasks.
● A function name can be any string that brings with a letter or underscore(_)
followed byzero or one or more letters,underscores and numbers. Function
names are case-insentive . It means count(), Count() and COUNT() refer to the
same function . By convention , PHP built-in functionsare in lowercase.
Inside the brackets () after the function name, you specify one or more parameters. If
a function accepts more than one parameter, each parameter has to be separate by a
comma.
The code inside the curly brace {} is a function body. You can put PHP code, HTML
code or mixed PHP and HTML code inside its body. For Example , the following function
displays the header of web page:
<?php
//defining a function
FunctionToday(){
Echo “Today is Tuesday”;
}
//calling function
Today();
?>
familyName("Achal", "1998");
familyName("Mrunali", "1996");
familyName("Shivani", "1999");
?>
Output
Achal born in 1998
Mrunali born in 1996
Shivani born in 1999
<?php
FunctionsayHello($name = “Rekha”)
{
Echo “Hello $name<br>”;
}
sayHello(“Mukul”);
sayHello();//passing no value
sayHello(“Karishma”);
?>
Output :
Hello Mukul
Hello Rekha
Hello Karishma
Returning Value
Let’s see an example of PHP function that returns value
<?php
Function cube($n)
{
Return $n*$n*$n;
}
Echo “Cube of 3 is :”
cube(3);
?>
Output
Cube of 3 is : 27
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Output : 0 1 2
Then each time the function is called, that variablewill still have the information it
contained from the last time the function was called.
<?php
$str = addcslashes(“Hello World!” ,“W”):
Echo($str);
?>
Output :
Hello \ world!
The addcslashes() function returns a string with backslashes in front of the specified
characters.
Note :The addcslashes() function is case-sensitive.
<?php
$str = “Welcome to my humble Homepage!”;
Echo $str.”<br>”;
Echo addcslashes($str,’m’). “<br>”;
Echo addcslashes($str, ‘H’). “<br>”;
?>
Output
Welcome to my humble Homepage!
Welcome to \my hu\mble Ho\mepage!
Welcome to my humble \Homepage!
Addslashes() Function
Add a backslash in front of each double quote (“):
<?php
$str = addslashes(“What does “yolo”
mean?”);
Echo($str);
?>
Output
What does \”yolo \”mean?
Print() Function
<?php
Print “Hello World!”;
?>
Output : Hello World!
Example : write the value of the string variable ($str) to the output, including HTML
tags
<?php
$str = “Hello World!”;
Print $str;
Print “<br>What a nice
day!”;
?>
Output
Hello World!
What a nice day!
As you see the position of the string “ world” In our string is position 6. The reason
that it is 6, and not 7 , is that the first position in the string is 0,and not 1.
Accessing Individual Character
PHP substr() Function
Return “world” from the string
<!DOCTYPE html>
<html>
<body>
<?php
Echo substr(“Hello world”, 6);
?>
</body>
</html>
Output :world
Reverse a string
The PHP strrev() function reverse a string:
<?php
Echo strrev(“Hello world”);
?>
Output : !dlrowolleH
Comparing Strings
The strcmp() function compares two strings
Note :The strcmp() function is binary – safe and case sensitive.
Syntax
Strcmp(string1, string2)
Parameter Description
String1 Required , specifies the first string to compare
String2 Required , specifies the second string to compare
Return This function returns:
Value ● 0 -if two strings are equal
● <0-if string 1 is less than string2
● >0 -if string 1 is greater than string2
Compare two strings (case-sensitive = Hello and hELLO will not output
the same):
<?php
Echo strcmp(“Hello” , “Hello”);
Echo “<br>”;
Echo strcmp(“Hello” , “hELLO”);
?>
Output : 0
-1
Cleaning Strings
Often the strings we get from files or users need not to be cleaned up before we can
use them. Two common problems with raw data are the presence of extraneous
whitespace,and incorrect capitalization (uppercase verses lowercase)
Removing Whitespace
You can remove leading or trailing whitespace with the trim(), ltrim(),and rtrim()
functions
$trimmed = trim(string[,charlist]);
$trimmed = ltrim(string[,charlist]);
$trimmed = rtrim(string[,charlist]);
Trim() returns a copy of strings with whitespace removed from the beginning and the
end. ltrim() does the same , but removes whitespace only from the start of the string.
rtrim() removes whitespace only from the end of the string . The optionalcharlist
argument is a string that specifies all the characters to strip. The default characters to
strip are given in table
Table : Default characters removed by trim(), ltrim(), and rtrim()
Character ASCII value Meaning
““ 0x20 Space
“\t” 0x09 Tab
“\n” 0x0A Newline (line feed)
“\0” 0x00 Nul-byte
“\x0B” 0x0B Vertical tab
For Example
$title = “Programming in PHP \n”;
$str_1=ltrim($title);
$str_2=rtrim($title);
$str_3=trim($title);
Given a line of tab-seperated data, use the charset argument to remove leading or
trailing whitespace without deleting the tabs :
$record = “Fred\tFlintstone\t35\tWima \n”;
$record = trim($record, “\r\n\0\x0B”;
//$record is “Fred\tFlinstone\t35\tWilma”
Changing Case
PHP has sevral functions for changing the case of string :strtolower () and strtoupper
() operate on entire strings , ucfirst() operates only on the first character of the string ,
and ucwords() Operates on the first character of each word in the string . Each
function takes a string to operate on as an arguent and returns a copy of that string ,
appropriately changed
For example :
$string1 = “FRED flintstone”;
$string2 = “barney rubble”;
Print(strtolower($string1));
Print(strtoupper($string1));
Print(ucfirst($string2));
Print(ucwords($string2));
Output :
Fredflintstone
FRED FLINSTONE
Barney rubble
Barney Rubble
If you’ve got a mixed string that you want to convert to “title case” where the first
letter of each word is in uppercase and the rest of the letters are in lowercase , use a
combination of strtolower() and ucwords():
Print(ucwords(strtolower(string1)));
Fred Flintstone
PHP’s Regexp PERL Compatible Functions
PHP offers following functions for searching strings using perl-compatible regular
expressions?
Sr.No Function & Description
1 Preg_match()
The preg_match function searches string for pattern,
returning true if pattern exists and false otherwise.
2 Preg_match_all()
The preg_match_all() function matches all occurrences of
pattern in string.
3 Preg_replace()
The preg_replace() function operates just like preg_replace(),
except that regular expressions can be used in the pattern
and replacement input parameters.
Example :
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
Output : 1
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
Output :4
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>
Output :Visit W3Schools!
Modifiers
several modifiers are available that can make your work with regexps much easier ,
like case sensitivity , searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
o Evaluates the expression only once
s Allows use of to match a newline character
x Allows you to use white space in the expression for clarity
g Globallyfinds all matches
cg Allows a search to continue even after a global match fails
UNIT-III (ARRAYS)
Introduction
An array in PHP is actually an ordered map. A map is a type that associates values to
keys. This type is optimized for several different uses; It can be treated as an array.
List, hash table, dictionary, collection, stack, queue and probably more.
PHP array are more like hash maps in other languages. They have a set of “keys”
which can be strings or integers and each key has a value associated with it, if all keys
are integers and are consecutive numbers, PHP arrays behave similar to real arrays,
except that their size is not fixed. But if the keys are out of order, or some keys are
strings, PHP arrays behave more like hash maps.
What is an array?
An array is a special variable,which can hold more than one value at a time If you
have a list of items (a list of student names, for example), storing the student name in
single variables could look like this :
$names1 = “Ketki”;
$names2 = “Asha”;
$names3 = “Bhakti”;
Create an Array in PHP
In PHP, the array() function is used to create an array:
Array();
In PHP there are three types of arrays:
● Indexed arrays – Arrays with a numeric index
● Associative arrays – Arrays with named keys
● Multidimensional arrays - Arrays contained one or more arrays
**PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$names = array(“Ketki”, “Aasha”, “Bhakti”);
Or the index can be assigned manually:
$names[0] = “Ketki”;
$names[1] = “Aasha”;
$names[2] = “Bhakti”;
The following example creates an indexed array named $student, assigns three
elements to it and then prints a text containing the array values:
<html>
<body>
<?php
$names = array (“Ketki”, “Aasha”, “Bhakti”);
Echo “I like” . $names[0]. ”, “.$names[1]. “and” . $names[2]. “.”;
?>
</body>
</html>
Output : 3
Ketki
Aasha
Bhakti
Get The Length of an Array – The count() Function
The count() functions is used to return the length (the number of elements) of an
array:
<html>
<body>
<?php
$names = array(“Ketki” , “Aasha”, “Bhakti”);
Echo count($names);
?>
</body>
</html>
Output: 3
Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending
or ascending.
PHP – Sort functions for Arrays
The following PHP array sort function:
● sort() – sort arrays in ascending order
● rsort() – sort arrays in descending order
● asort() – sort associative arrays in ascending order, according to the value
● ksort() – sort associative arrays in ascending order , according to the value
● arsort() – sort associative arrays in descending order, according to the value
● krsort() – sort associative arrays in descending order, according to the key.
Sort Array in Ascending Order – sort()
The following example sorts the elements of the $names array in ascending
alphabetical order:
<html>
<body>
<?php
$names = array(“Ketki”, “Aasha”, “Bhakti”);
Sort($names);
$clength = count($names);
For($x=0; $x<$clength; $x++){
Echo $names[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output
Aasha
Bhakti
Ketki
The following example sorts the elements of the $numbers array in ascending
numerical order:
<html>
<body>
<?php
$numbers = array(4,6,2,22,11);
Sort($numbers);
$arrlength = count($numbers);
For($x=0; $x< $arrlength; $x++)
{
echo $numbers[$x];
echo “<br>”;
}
?>
</body>
</html>
Output
2
4
6
11
22
Sort Array in Descending Order – rsort()
The following example sorts the elements of the $names array in descending
alphabetical order:
<html>
<body>
<?php
$names = array(“Ketki”, “Aasha”, “Bhakti”);
rsort($names);
$clength = count($names);
For($x=0; $x < $clength; $x++)
{
Echo $names[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output
Ketki
Bhakti
Aasha
The following example sorts the elements of the $numbers array in descending
numerical order:
<html>
<body>
<?php
$numbers = array(4,6,2,22,11);
rsort($numbers);
$arrlength = count($numbers);
For($x=0 ; $x < $arrlength ; $x++)
{
Echo $numbers[$x];
Echo “<br>”;
}
?>
</body>
</html>
Output
22
11
6
4
2
Sort Array (Ascending Order),According to Value – asort()
The following example sorts an associative array in ascending to the value:
<html>
<body>
<?php
$age = array(“Peter”=> “35”, “Ben”=> “37”, “Joe”=> “43”);
asort($age);
Foreach($age as $x => $x_value)
{
Echo “Key=” . $x .“,Value=” . $x_value;
Echo “<br>”;
}
?>
</body>
</html>
Output
Key=Peter , Value=35
Key=Ben, Value=37
Key=Joe , Value=43
Sort Array (Ascending Order), According to Key – ksort()
The following example sorts an associative array in ascending order, according to the
key:
<html>
<body>
<?php
$age= array(“Peter”=> “35”, “Ben”=> “37” , “Joe”=> “43”);
Ksort($age);
Foreach($age as $x => $x_value)
{
Echo “Key=”. $x .”, Value=” .$x_value;
Echo “<br>”;
}
?>
</body>
</html>
Output
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
<?php
$cars = array (
array("Audi",22,18),
array("BMW",15,13),
array("Verna",5,2),
array("Rang 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
Audi: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Verna: In stock: 5, sold: 2.
Rang Rover: In stock: 17, sold: 15.
Extracting Multiple Values
To copy all of an array’s values into variables, use the list() construct:
List($variable,….)=$array;
The array’s values are copied into the listed variables, in the array’s internal order. By
default that’s the order in which they were inserted, but the sort functions described
later let you change that. Here’s an example:
$person = array(‘name’ => ‘Fred’ , ‘age’=> 35 , ‘wife’=> ‘Betty’);
List($n,$a,$w) = $person; //$n is ‘Fred’, $a is 35 , $w is ‘Betty’
If you have more values in the array than in the list(), the extra values are
ignored :
$person = array(‘name’=> ‘Fred’ , ‘age’=> 35 , ‘wife’=> ‘Betty’);
List($n, $a) =$person; //$n is ‘Fred’, $a is 35
If you have more values in the list() than in the array, the extra values are set
to NULL:
$values= array(‘hello’,’world’);
List($a, $b, $c) = $values // $a is ‘hello’,$b is ‘world’,$c is NULL
Two or more consecutive commas in the list() skip values in the array:
$values = range(‘a’, ‘e’);
List($m,,$n,,$o)=$values; //$m is ‘a’,$n is ‘c’, $o is ‘e’
Slicing an Array
To extract only a subset of the array, use the array_slice() function:
$subset = array_slice(array, offset, length);
The array _slice() function returns a new array consisting of a consecutive series of
values from the original array. The offset parameter identifies the initial element of
copy and the length para meter identifies the number of values to copy. The new array
consecutive numeric keys starting at 0.
For example
<?php
$a=array("red", "green", "blue", "yellow", "brown");
print_r(array_slice($a,2));
?>
OUTPUT
Array ( [0] => blue [1] => yellow [2] => brown )
Traversing Arrays
The most common task with arrays is to do something with every element-for
instance, sending mail to each element of an array of address, updating each file in an
array of filenames, or adding up each element of an array of prices. There are sevral
ways to traverse arrays in PHP, and the one you choose will depend on you data and
the task you’re performing.
The foreach Construct
The most common way to loop over elements of an array is to use the foreach
construct:
<?php
$address = array(“@raisoni.net”, “[email protected]”);
Foreach ($address as $value)
{
echo “Processing {$value}\n”;
}
?>
OUTPUT:
Processing { @raisoni.net}
Processing { [email protected]}
PHP executes the body of the loop (the echo statement) once for each element of
$addresses in turn, with $value set to the current element. Elements are processed by
their internal order.
In this case, the key foreach element is placed in $key and the corresponding value is
placed in $value.
The foreach construct does not operate on the array itself, but rather on a copy of it .
You can insert or delete elements in the body of a foreach loop, safe in the knowledge
that the loop won’t attempt to process the deleted or inserted elements.
Acting on entire arrays
Arrays is a kind of data type will almost certainly be used by the PHP programmers as
its flexibility to accommodate data. The array can also hold dozens or even hundreds of
data.
The topic about array is very very wide.
Writing Array in PHP
In PHP, we can define an array in two ways, by using the array function array() or
simply use a square bracket[].
<?php
$vehicle = [];//since PHP 5.4
$vehicle = array(); //All version of PHP
Indexed array
<?php
$vehicle = [‘car’, ‘Motorcycle’, ‘Bicycle’, ‘Truck’, ‘Bus’];
Unset($vehicle[0]);
Echo ‘<pre>’;
Print_r($vehicle);
?>
OUTPUT:
Array
(
[1] => Motorcycle
[2] => Bicycle
[3] => Truck
[4] => Bus
)
Reading data in web pages : setting Up web pages to communicate with PHP
Introduction
To connect to PHP on the server or any code on the server, to set up web pages a
particular way. To enclose all HTML controls in an HTML form, and have to indicate in
that form where the data in those controls will be sent.
For example, the user might enter their name in a text field, and have to let the
browser know where to send that name in a text field,and have to let the browser
know where to send that name when the user clicks the submit button
HTML forms might be
<form>
.
.
.
</form>
It’s compulsory to specify the method with which data will be sent- the two most
common methods are “get” and “post” and might choose the get method here:
<form method=”get”>
.
.
.
</form>
<form method= “post”>
.
.
.
</form>
To create a submit button- note it has to be inside the HTML <form> element – with
the caption send, and that are use an <input> element with the type attribute set to
“submit” To create submit button.
<html>
<head>
<title>connecting to PHP
</title>
</head>
<body>
<h1> Connecting to PHP </h1>
<?php
echo "your name is:";
echo $_REQUEST["name"];
echo "<br>";
echo "and email id is:";
echo $_REQUEST["email"];
?>
</body>
</html>
All this PHP script , does is to echo the name the user entered into the datatext field.
HANDELING TEXTAREAS
Text fields are fine if you want a single line of text, but if you want multiline text input,
you have to go with text areas.
Here’s an example, .html that presents the user with a text area, and asks what pizza
toppings they want. It starts like this:
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>entering data into text areas</h1>
<form method= "post">
<textarea name="data" cols="50" rows="5">
1.
2.
3.
4.
</textarea>
<br>
<input type="submit" value= "send">
</form>
<h1>You ordered pizza with</h1>
<?php
$text = $_REQUEST["data"];
echo $text;
?>
</body>
</html>
Check Boxes
The next steps up in controls are check boxes- those square controls that you can
select or de-select with the mouse
You create check boxes with the <input> element like this in a web page, where you’re
asking the user if they want fries in .htm
<html >
<head>
<title>Document</title>
</head>
<body>
<h1>Enter data into checkbox</h1>
<form method = "post">
Do you want fries?
<input name="check" type = "checkbox" value = "Yes">
Yes
<input name="check1" type = "checkbox" value = "No">
No
<br>
<br>
<input type="submit" value = "send">
</form>
selected:
<?php
if(isset($_REQUEST["check"]))
{
echo $_REQUEST["check"],"<br>";
}
if(isset($_REQUEST["check1"]))
{
echo $_REQUEST["check1"],"<br>";
}
?>
</body>
</html>
</body>
</html>
You can see the result in above fig, where you’re reading what check boxes the user
selected
Note that the user could click both check boxes here- which would mean that they both
wanted fries and didn’t want fries. A better choice for the controls here are radio
buttons, where only one can be selected at a time, and they’re coming up next.
?>
</body>
</html>
Password Controls
A common use of PHP is to check password on the server, giving the user access to a
resource if they have the right password, and you can use password controls for that
here’s an example that asks the user for their password.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h3>Enter data</h3>
<form method="post">
<input name="password" type="password">
Enter password
<br>
<input type="submit" value="send">
</form>
<?php
if($_REQUEST["password"]=="letmein")
{
echo "password accepted";
}
?>
</body>
</html>
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>Storing data with hidden controls</h1>
what kind of customer do we think you are?
<br>
click the button to find out.
<br>
<form method= "post">
<input name="customer_type" type="hidden" value="good">
<br>
<br>
<input type="submit" value="send">
</form>
<h1>Reading data from password controls</h1>
we think you are a
<?php
echo $_REQUEST["customer_type"];
?>
customer.
</body>
</html>
You can see the result in above figure the customer is a good customer.
Hidden controls like this are popular for storing information about the user for use with
PHP-another popular for storing information about the user is to use cookies.
Handling File Uploads
A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for
file uploads as upload_tmp_dir and the maximum permitted sixe of files that can be
uploaded is stated as upload_max_filesize . These parameters are set into PHP
configuration file php.ini
The process of uploading a file follows these steps?
● The user opens the page containing a HTML form featuring a text files, a browse
button and a submit button.
● The user clicks the browse button and selects a file to upload from the local PC.
● The full path to the selected file appears in the text filed then the user clicks the
submit button.
● The selected file is sent to the temporary directory on the server.
● The PHP script that was specified as the form handler in the form’s action
attribute checks that the file has arrived and then copies the file into an
intended directory.
● The PHP script confirms the successto the user.
As usual when writing files it is necessary for both temporary and final locations to
have permissions set that enable file writing’ if either is set to be read-only then
process will fail. An uploaded file could be a text file or image file or any document.
Creating an upload form
The following HTML code below creates an uploader form. This form is having method
atrribute set to post and enctype attribute is set to maultipart/form-data
Creating an upload script
There is one global PHP variables called $_FILES.This variable is an associated double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input’s name attribute in uploading form was file, then PHP would
create following five variables?
● $_FILES[‘file’][tmp_name’] – the uploaded file I the temporary directory on
the web server.
● $_FILES[‘file’][‘name’] – the actual name of the uploaded file.
● $_FILES[‘file’][‘size’] – the size in bytes of the uploaded file.
● $_FILES[‘file’][‘type’] – the MIME type of the uploaded file
● $_FILES[‘file’][‘error’] – the error code associated with this file upload.
Handling Buttons : Making Button Data Persist
Using Submit Buttons as HTML Buttons
There is still one popular HTML control that we haven’t covered-buttons. Often you
see buttons in web pages , they are more difficult to work with using server side
scripts for one reason – they pop back. That is there is no data that’s stored tat will be
sent to the server when a submit button is clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<script language= "JavaScript">
function setbutton1()
{
document.form1.button.value="button 1"
form1.submit()
}
function setbutton2()
{
document.form1.button.value="button 2"
form1.submit()
}
function setbutton3()
{
document.form1.button.value="button 3"
form1.submit()
}
</script>
</head>
<body>
<h1>handling buttons</h1>
<form name= "form1" method="post">
<input type="hidden" name="buttons">
<input type="button" value="button 1" onclick="setbutton1()">
<input type="button" value="button 2" onclick="setbutton2()">
<input type="button" value="button 3" onclick="setbutton3()">
</form>
<!-- You clicked -->
<?php
if(isset($_REQUEST["button"]))
{
echo $_REQUEST["button"],"<br>";
}
?>
</body>
</html>