Unit III Scripting Essentials Unit III Scripting Essentials
Unit III Scripting Essentials Unit III Scripting Essentials
While static content like typical HTML elements and images can easily be transferred and
displayed, dynamic content such as a Wiki, a drop-down menu, or a web application, will only
function with scripts. These must be executed and interpreted with the appropriate scripting
language, which can either occur server-side or client-side. For this reason, a distinction must be
made between server-side scripting and client-side scripting.
ActiveVFP.
ASP.
C.
DC.
Java.
JavaScript (using Server-side JavaScript (SSJS) e.g., node.js)
Perl.
PHP.
Server-side scripting is a technique that is used to develop websites and implement dynamic
elements and web applications. It’s based on the use of scripts that are carried out by the web
server using the appropriate scripting languages when a client requests the corresponding
content. The script’s task is often to retrieve the appropriate data from a database and integrate it
into the web project. The user accesses these via HTML pages, while the script source codes
remain completely hidden. The use of server-side scripts requires the client to send multiple
requests to the web server to provide the user with new information. This means, on the one
hand, high utilization of the server's capacity, which has an impact on the response time of the
web server, and on the other hand, that an existing connection to the server is indispensable for
making use of the web offer.
In the early days of the World Wide Web, server-side scripting was almost exclusively
implemented by writing developer programs in C, as well as Perl and command line scripts.
These applications were carried out and interpreted by server operating systems, at which time
the result could be passed from the web server to the browser via the common gateway interface
(CGI). Many modern web servers can now also run scripts directly, i.e. using corresponding
modules. Launched in 1995 and based on C and Perl, PHP is the most widely used server-side
scripting language today. The following table shows a selection of the programming languages
used for server-side scripts:
JavaScript.
VBScript.
HTML (Structure)
CSS (Designing)
AJAX.
jQuery etc.
Client-side scripting is another technique used by web developers to create projects with
dynamic content. Unlike the server-side variant, however, the client executes and processes the
programmed scripts, not the server. For this purpose, the scripts are either embedded into the
HTML or XHTML document, or written into a separate file linked to the document. If the user
now tries to access a webpage or application with such a client-side script, the web server sends
the HTML document and the script to the browser, which performs the same execution,
presenting the final result. Client-side scripts can also contain concrete instructions for the web
browser, determining how it should react to users’ actions, e.g. clicking on a button. Often, the
client doesn’t need to re-establish a connection to the web server.
As the scripts are executed in the user’s browser, the user has the option to view the source code
– unlike with server-side scripts. In turn, the interpretation of the scripts requires the
corresponding script language to be understood by the web browser. There are also various
browser extensions available, which can block scripts, as client-side scripting applications, such
as pop-ups and web-tracking tools, can have a negative impact on the loading times.
The most significant client-side script language is JavaScript. Developed by the Mozilla
predecessor, Netscape, and launched in 1995 with the previous version of the browser, Navigator
2.0 – then known as LiveScript. The script language caught on quickly, eventually becoming the
universal scripting language of all relevant web browsers. Shockwave Flash (SWF) is also
worth a mention, despite its considerable drawbacks. The object-oriented language is an
important component of Adobe’s Flash Player, which for a long time was the measure of all
things for videos on the internet. However, with all its security gaps and the introduction of new
technology, such as HTML5, the once popular Flash video has now faded into the background.
In the early days of the internet, Microsoft Silverlight and Java Applets also enjoyed a great deal
of popularity.
In theory, it’s also possible to use other scripting languages for client-side scripting, but the
developers of the relevant browsers must choose to support them. There are, however, alternative
solutions that allow client-side scripts with other languages. For this purpose, the respective code
can be interpreted and executed as JavaScript using a transpiler like CoffeeScript or TypeScript.
What is PHP
PHP is a open source, interpreted and object-oriented scripting language i.e. executed at server
side. It is used to develop web applications (an application i.e. executed at server side and
generates dynamic page).
What is PHP
Note: An interpreted language is a type of programming language for which most of its
implementations execute instructions directly and freely, without previously compiling a program into
machine-language instructions. The interpreter executes the program directly, translating each statement
into a sequence of one or more subroutines already compiled into machine code.
PHP Features
Performance: Script written in PHP executes much faster then those scripts written in other
languages such as JSP & ASP.
Open Source Software: PHP source code is free available on the web, you can developed all the
version of PHP according to your requirement without paying any cost.
Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application developed in one OS can be easily executed in other OS also.
Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.
Embedded: PHP code can be easily embedded within HTML tags and script.
Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that are
given below:
If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
PHP Example
It is very easy to create a simple PHP example. To do so, create a file and write HTML tags +
PHP code and save this file with .php extension.
All PHP code goes between php tag. A syntax of PHP tag is given below:
1. <?php
2. //your code here
3. ?>
File: first.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello First PHP</h2>";
6. ?>
7. </body>
8. </html>
Save in c:\htdocs\first.php
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 statement can be used to print string, multi line strings, escaping characters, variable,
array etc.
1. <?php
2. echo "Hello by PHP echo";
3. ?>
Output:
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the
argument list. Unlike echo, it always returns 1.
PHP print statement can be used to print string, multi line strings, escaping characters, variable,
array etc.
1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>
Output:
They are:
print only takes one parameter, while echo can have multiple parameters.
print returns a value (1), so can be used as an expression.
echo is slightly faster.
To add to the answers above, while print can only take one parameter, it will allow for concatenation of
multiple values, ie:
$count = 5;
print "This is " . $count . " values in " . $count/5 . " parameter";
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.
1. $variablename=value;
Let's see the example to store string, integer and float values in PHP variables.
File: variable1.php
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.
File: variable3.php
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
File: variablevalid.php
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello
hello
PHP is a loosely typed language, it means PHP automatically converts the variable to its correct
data type.
The scope of a variable is the part of the script where the variable can be referenced/used.
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
Output:
The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.
Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>
Output:
Abc
200
200
In the above example, we have assigned a value to the variable x as abc. Value of reference
variable $$x is assigned as 200.
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script.
PHP constants can be defined by 2 ways:
PHP constants follow the same PHP variable rules. For example, it can be started with letter or
underscore only.
File: constant1.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>
Output:
File: constant2.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
File: constant3.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
The const keyword defines constants at compile time. It is a language construct not a function.
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of their use.
They start with double underscore (__) and ends with double underscore.
They are similar to other predefined constants but as they change their values with the context,
they are called magic constants.
There are eight magical constants defined in the below table. They are case-insensitive.
Name Description
__LINE__ Represents current line number where it is used.
Represents full path and file name of the file. If it is used inside an include,
__FILE__
name of included file is returned.
Represents full directory path of the file. Equivalent to dirname(__file__). It
__DIR__ does not have a trailing slash unless it is a root directory. It also resolves
symbolic link.
Represents the function name where it is used. If it is used outside of any
__FUNCTION__
function, then it will return blank.
Represents the function name where it is used. If it is used outside of any
__CLASS__
function, then it will return blank.
Represents the trait name where it is used. If it is used outside of any
__TRAIT__
function, then it will return blank. It includes namespace it was declared in.
Represents the name of the class method where it is used. The method name
__METHOD__
is returned as it was declared.
__NAMESPACE__ Represents the name of the current namespace.
Example
1. <?php
2. echo "<h3>Example for __LINE__</h3>";
3. echo "You are at line number " . __LINE__ . "<br><br>";// print Your current line number i.e;3
4. echo "<h3>Example for __FILE__</h3>";
5. echo __FILE__ . "<br><br>";//print full path of file with .php extension
6. echo "<h3>Example for __DIR__</h3>";
7. echo __DIR__ . "<br><br>";//print full path of directory where script will be placed
1. Scalar Types
2. Compound Types
3. Special Types
PHP Data Types: Scalar Types(as they can hold only a single data item they are
known as scalar data types)
1. boolean
2. integer
3. float
4. string
PHP Data Types: Compound Types(can hold more than one data item)
1. array
2. object
1. resource
2. NULL
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. For example:
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
Arithmetic Operators
Comparison Operators
Bitwise Operators
Logical Operators
String Operators
Incrementing/Decrementing Operators
Array Operators
Type Operators
Execution Operators
Error Control Operators
Assignment Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right
| bitwise OR left
|| logical OR left
?: ternary left
Or logical left
PHP Comments
PHP comments can be used to describe any line of code so that other developer can understand
the code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++ and
Perl style (Unix shell style) comments.
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>
Output:
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
Output:
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
if
if-else
if-else-if
nested if
PHP If Statement
Example
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
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:
1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>
Output:
number is equal to 20
Syntax
Output:
1
2
3
4
5
6
7
8
9
10
Syntax
1. while(condition){
2. //code to be executed
3. }
1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
It executes the code at least one time always because condition is checked after executing the
code.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
$i = 10;
while (--$i)
{
if ($i == 8)
{
continue;
}
if ($i == 5)
{
break;
}
echo $i . "\n";
}
?>
Sample Programs:
1) Sum of Digits
3) Prime number
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.
Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.
We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.
Syntax
1. function functionname(){
2. //code to be executed
3. }
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and
Variable-length argument list.
File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>
Output:
Hello Sonoo
Hello Vimal
Hello John
File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
Value passed to the function doesn't modify the actual value by default (call by value). But we
can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need
to use ampersand (&) symbol before the argument name.
File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
Passing an argument like so: myFunc(&$var); means that the variable is passed
by reference (and not by value). So any modifications made to the variable in
the function modify the variable where the call is made.
We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.
File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>
Output:
Cube of 3 is: 27
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.
In this example, we have passed two parameters $x and $y inside two functions add() and sub().
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Parameter Addition and Subtraction Example</title>
5. </head>
6. <body>
7. <?php
8. //Adding two numbers
9. function add($x, $y) {
10. $sum = $x + $y;
11. echo "Sum of two numbers is = $sum <br><br>";
12. }
13. add(467, 943);
14.
15. //Subtracting two numbers
16. function sub($x, $y) {
17. $diff = $x - $y;
18. echo "Difference between two numbers is = $diff";
19. }
20. sub(943, 467);
21. ?>
22. </body>
23. </html>
24. Factorial.php:
<?php
function fac($n)
$fact=1;
$i=1;
for($i=1;$i<=$n;$i++)
$fact=$fact*$i;
echo "result=$fact";
if(isset($_POST['factorial']))
fac($_POST['val1']);
} ?>
<form method="post">
</form>
In the above code in process.php the $POST is a array which contains user information
submitted by the form. Form send user input values with its control names to process.php. where
val1 is key and whatever user type in input field will be the value in $POST array and we can
access that information like this $_POST['val1'].
Now come to isset. isset function check that the variable is set or not in other words the variable
has a value or not. In this case isset($POST['factorial']) checks that the $_POST['factorial'] is set
or not. it will be set if the user click on the login button. if the $_POST['fcatorial'] is set then the
code will echo computed factorial value else it will show that visit again message. For the
purpose we you isset is that suppose if user visit process.php without submitting the form then
the page will show an error that your $POST['val1'] is not set as we are trying to echo its value.
But now we are checking the form submission and if the user visit the process.php page without
submitting the form. This time user will get the visit again message instead of error.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
1. <?php
2. function add(...$numbers) {
3. $sum = 0;
4. foreach ($numbers as $n) {
5. $sum += $n;
6. }
7. return $sum;
8. }
9.
10. echo add(1, 2, 3, 4);
11. ?>
Output:
10
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
1. <?php
2. function display($number) {
3. if($number<=5){
Output:
1
2
3
4
5
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
1. <?php
2. $size=array("Big","Medium","Short");
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>
Output:
File: array2.php
1. <?php
2. $size[0]="Big";
3. $size[1]="Medium";
4. $size[2]="Short";
5. echo "Size: $size[0], $size[1] and $size[2]";
6. ?>
Output:
foreach
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays
and objects, and will issue an error when you try to use it on a variable with a different data type
or an uninitialized variable. There are two syntaxes:
The first form loops over the array given by array_expression. On each iteration, the value of the
current element is assigned to $value and the internal array pointer is advanced by one (so on the
next iteration, you'll be looking at the next element).
The second form will additionally assign the current element's key to the $key variable on each
iteration.
We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all
the elements of PHP array.
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Output:
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:
We can associate name with each array elements in PHP using => symbol.
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
Output:
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:
<?php
function fac($n)
$fact=1;
$i=1;
for($i=1;$i<=$n;$i++)
$fact=$fact*$i;
echo "result=$fact";
if(isset($_POST['factorial']))
fac($_POST['val1']);
?>
<form method="post">
</form>
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
Let's see a simple example of PHP multidimensional array to display following tabular data. In
this example, we are displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 John 500000
3 Rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP array() function creates and returns an array. It allows you to create indexed, associative
and multidimensional arrays.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can
divide array into many parts.
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer
PHP array_search() function searches the specified value in an array. It returns key if search is
successful.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
PHP array_intersect() function returns the intersection of two array. In other words, it returns the
matching elements of two array.
Syntax
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith
In this chapter, we will go through the following PHP array sort functions:
The following example sorts the elements of the $cars array in ascending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Output:
BMW
Toyota
Volvo
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
Output:
Volvo
Toyota
BMW
The following example sorts an associative array in ascending order, according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
The following example sorts an associative array in ascending order, according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Output:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
The following example sorts an associative array in descending order, according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
The following example sorts an associative array in descending order, according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
Output:
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4 ways
to specify string in PHP.
single quoted
double quoted
We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify
string in PHP.
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Output:
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>
Output:
my name is khan
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>
Output:
MY NAME IS KHAN
The ucfirst() function returns string converting first character into uppercase. It doesn't change
the case of other characters.
Syntax
Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>
Output:
My name is KHAN
The lcfirst() function returns string converting first character into lowercase. It doesn't change the
Syntax
Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:
mY name IS KHAN
The ucwords() function returns string converting first character of each word into uppercase.
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>
Output:
24
in_array()
Note: If the search parameter is a string and the type parameter is set to TRUE, the search is
case-sensitive.
Syntax
in_array(search,array,type)
Parameter Description
Optional. If this parameter is set to TRUE, the in_array() function searches for the
Type
search-string and specific type in the array.
<?php
$number_list = array('16.10', '22.0', '33.45', '45.45');
if (in_array(22.0, $number_list))
{
echo "'22.0' found in the array";
}
?>
Copy
Output:
Syntax
str_ireplace(find,replace,string,count)
Parameter Description
In this example we will demonstrate str_ireplace() with an array and a count variable:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_ireplace("RED","pink",$arr,$i));
echo "Replacements: $i";
?>
Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)
Replacements: 1
Syntax
str_pad(string,length,pad_string,pad_type)
Parameter Description
length Required. Specifies the new string length. If this value is less than the original
length of the string, nothing will be done
pad_string Optional. Specifies the string to use for padding. Default is whitespace
Possible values:
Example 1
<?php
$str = "Hello World";
echo str_pad($str,20,".");
?>
Hello World.........
Syntax
str_repeat(string,repeat)
Parameter Description
repeat Required. Specifies the number of times the string will be repeated. Must be
greater or equal to 0
Example
<?php
echo str_repeat(".",13);
?>
.............
The str_replace() function replaces some characters with some other characters in a string.
Syntax
str_replace(find,replace,string,count)
Parameter Description
In this example we will demonstrate str_replace() with an array and a count variable:
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)
Replacements: 1
The ROT13 encoding shifts every letter 13 places in the alphabet. Numeric and non-alphabetical
characters remains untouched.
Syntax
str_rot13(string)
Parameter Description
Example
In this example we will encode and decode a string using the str_rot13() function:
<?php
echo str_rot13("Hello World");
echo "<br />";
echo str_rot13("Uryyb Jbeyq");
?>
Uryyb Jbeyq
Hello World
Syntax
str_shuffle(string)
Example
<?php
echo str_shuffle("Hello World");
?>
H leooWlrld
Syntax
str_split(string,length)
Parameter Description
Example 1
<?php
print_r(str_split("Hello"));
?>
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)
Example 2
<?php
print_r(str_split("Hello",3));
?>
Array
(
[0] => Hel
[1] => lo
)
Syntax
str_word_count(string,return,char)
Example 1
<?php
echo str_word_count("Hello world!");
?>
Syntax
strcasecmp(string1,string2)
Example
<?php
echo strcasecmp("Hello world!","HELLO WORLD!");
?>
Classwork programs:
1)Write a PHP program to count number of
vowels in a string.
PHP File Handling
PHP File System allows us to create file, read file line by line, read file character by character,
write file, append file, delete file and close file.
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $c
ontext ]] )
Example
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Syntax
Example
1. <?php
2. fclose($handle);
3. ?>
The PHP fread() function is used to read the content of the file. It accepts two arguments:
resource and file size.
Syntax
Example
1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>
Output
The PHP fwrite() function is used to write content of the string into file.
Syntax
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
Output
Syntax
Example
1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $c
ontext ]] )
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.
Opens file in write-only mode. It places the file pointer to the beginning of the file and truncates
w
the file to zero length. If file is not found, it creates a new file.
Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates
w+
the file to zero length. If file is not found, it creates a new file.
Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it
a
creates a new file.
Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it
a+
creates a new file.
Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. If
x
file is found, fopen() function returns FALSE.
Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither
c truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file
pointer is positioned on the beginning of the file
fread()
fgets()
fgetc()
The PHP fread() function is used to read data of the file. It requires two arguments: file resource
and file size.
Syntax
Example
1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>
Output
The PHP fgets() function is used to read single line from the file.
Syntax
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>
Output
The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.
Syntax
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>
Output
data.txt
The PHP fwrite() function is used to write and append data into file.
Example
1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>
Output: data.txt
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.
Syntax
1. <?php
2. $status=unlink('data.txt');
3. if($status){
4. echo "File deleted successfully";
5. }else{
6. echo "Sorry!";
7. }
8. ?>
Output
The readfile() function reads a file and writes it to the output buffer.
<?php
echo readfile("webdictionary.txt");
?>
-rewind();
-fseek();
-ftell();
The rewind () function "rewinds" the position of the file pointer to the beginning of the file.
Syntax
rewind(file)
<?php
$handle = fopen('output.txt', 'w');
fclose($handle);
?>
This function moves the file pointer from its current position to a new position, forward or
backward, specified by the number of bytes.
This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an error.
Syntax
fseek(file,offset,whence) ;
Second is the int Record size, the value, it is expected to hop in one jump. Notice, it can be a
negative value as well.
Third parameter is the offset value from where this hopping is to be done. There are three
possible values for it 0,1 and 2. 0 represents beginning of the file 1 represents current location
And, 2 represents the end of file.
The SEEK_END, SEEK_CUR or,the SEEK_SET are merely the Macro Expansions with values
of 2,1 and 0 respectively. So when a user uses these macro Expansions rather that using the real
values underneath, the pre-processors replaces every such usage with its respective value and
compilation goes on as usual.
Example
<?php
$file = fopen("test.txt","r");
// read first line
fgets($file);
// move back to beginning of file
fseek($file,0);
?>
Syntax
ftell(file)
Example
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
0
15
Classwork programs:
1)Write a PHP program to count number of
lines in a file.
2)Write a PHP program to copy from 20th
line of a file to another file.
PHP and MYSQL:
MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
The data in MySQL is stored in tables. A table is a collection of related data, and it consists of
columns and rows.
Databases are useful when storing information categorically. A company may have a database
with the following tables:
Employees
Products
Customers
Orders
PHP + MySQL
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)
Queries
We can query a database for specific information and have a recordset returned.
The query above selects all the data in the "LastName" column from the "Employees" table.
Before we can access data in a database, we must open a connection to the MySQL server.
Syntax
mysqli_connect(host,username,password,dbname);
Note: Mysqli--here “i” stands for improved version of Mysql.Mysqli supports Object-oriented
interface , Support for Prepared Statements etc.
Parameter Description
Optional. Either a host name or an
host
IP address
username Optional. The MySQL user name
Optional. The password to log in
password
with
Optional. The default database to
dbname
be used when performing queries
Note: There are more available parameters, but the ones listed above are the most important.
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Host-If this parameter takes localhost" refers to the local computer that a program is running on.
For example, if you are running a Web browser on your computer, your computer is considered
to be the "localhost."
The connection will be closed automatically when the script ends. To close the connection
before, use the mysqli_close() function:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
Syntax
mysqli_query(connection,query,resultmode);
Parameter Description
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
Syntax
mysqli_num_rows(result);
Parameter Description
Technical Details
Return Value: Returns the number of rows in the result set
Syntax
mysqli_fetch_assoc(result);
Parameter Description
Technical Details
Returns an associative array of strings representing the fetched row. NULL if there
Return Value:
are no more rows in result-set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo $row[0]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
The mysqli_multi_query() function performs one or more queries against the database. The
queries are separated with a semicolon.
Syntax
mysqli_multi_query(connection,query);
Parameter Description
//Update:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//delete
?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Cookie
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.
Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying
return users.
A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer.
Once a cookie has been set, all page requests that follow return the cookie name and value. A
cookie can only be read from the domain that it has been issued from. For example, a cookie set
using the domain www.guru99.com can not be read from the domain career.guru99.com.
Most of the websites on the internet display elements from other domains such as advertising.
The domains serving these elements can also set their own cookies. These are known as third
party cookies.
A cookie created by a user can only be visible to them. Other users cannot see its value.
Most web browsers have options for disabling cookies, third party cookies or both.
If this is the case then PHP responds by passing the cookie token in the URL. Why
and when to use Cookies?
Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer.
The path were the cookies are stored depends on the browser.
Personalizing the user experience – this is achieved by allowing users to select their
preferences.
The page requested that follow are personalized based on the set preferences in the
cookies.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
The setcookie() function must appear BEFORE the <html> tag. The value of the cookie is automatically
URLencoded when sending the cookie, and automatically decoded when received. setcookie() must be
called before any output is sent to the browser.
To delete a cookie, use the setcookie() function with an expiration date in the past:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
What is a Session?
A session is a global variable stored on the server.
Each session is assigned a unique id which is used to retrieve stored values.
Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser does
not support cookies, the unique php session id is displayed in the URL
Sessions have the capacity to store relatively large data compared to cookies.
The session values are automatically deleted when the browser is closed. If you want to
store the values permanently, then you should store them in the database.
Just like the $_COOKIE array variable, session variables are stored in the $_SESSION
array variable. Just like cookies, the session must be started before any HTML tags.
You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to
passing them in the URL
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
Creating a Session
In order to create a session, you must first call the PHP session_start function and then store
your values in the $_SESSION array variable.
Let’s suppose we want to know the number of times that a page has been loaded, we can use a
session to do that.
The code below shows how to create and retrieve values from sessions
<?php
if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];
?>
Output:
<?php
?>
<?php
?>
Session_destroy removes all the session data including cookies associated with the session.