Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 1 - Server Side Scripting

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Chapter One

Server Side Scripting Basics


1.1. Introduction to server side scripting

What is scripting?

 is writing programs to automate manual works (solving problems)


 Integration of existing tools
 Automating a new software from the scratch
 Mentioning an existing software
 Enhance the feature of an existing software and so on
 Mostly used in graphs, animations, web pages, video

Main components of dynamic website

 Dialog between the client (web browser) and server (web host)
 Client request and server responds

 Simple module consists of server, document and client


 Client request a page from server; server response a customized page to a client
 Dynamic pages are generated by server side scripts like PHP (to deliver from server to
client) in HTML form

For example: - retrieving student information from student database (server side DB store
student information) and a custom HTML page is return to a client. The custom return
document may contain text content, image, Java script, CSS and so on.

1.2. Types of Scripting Language


I. Client side script language

1
 Scripts which executes on the client side
 To pre-process the data on client side before send to server
 Making request files from serve, making read and write request of server side scripts
 Used for client side validation (i.e. simple validation: checking form elements are empty or
not)
 Example JavaScript = also used for server side script solution, not only client side solution
II. Server side script language
 Allows to custom HTML delivered to client
 Custom HTML is processed on web server with server side script before HTML sent to client
over internet
 Programming languages which uses server side scripting mechanism are called server side
programming languages such as ASP, PHP, JSP, Servlet and so on
 Server side language code remains on the web server. After it has been processed the server
send output of script to client in HTML format

Server side scripting brings life of web app

 Sending feedback
 Uploading a file through a web page
 Reading and writing to a files
 Displaying and updating information’s dynamically
 Use database to display and store information’s
 Making them searchable and so on

How server side scripting works in WWW

1. The browser sends a request to the web server.


2. The web server hands the request to the PHP engine, which is embedded in the server.
3. The PHP engine processes the code. In many cases, it might also query a database before
building the page.
4. The server sends the completed page back to the browser.

1.3. Server side scripting language with PHP

2
What is PHP?

 Hypertext pre-processor is an HTML embedded scripting language which allows developers


to write dynamically generated pages quickly
 PHP scripts are executed on the server

PHP will allow you to:


 Create a customized user experience for visitors based on information that you have gathered
from them.
 Open up thousands of possibilities for online tools.
 Allow creation of shopping carts for e-commerce websites.
Why PHP?
 PHP runs on various platforms (Windows, Linux, Mac OS, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
Use a Web Host with PHP Support
 If your server has activated support for PHP you do not need to do anything.
 Just create some .php files, place them in your web directory, and the server will
automatically parse them for you.
 You do not need to compile anything or install any extra tools.
 Because PHP is free, most web hosts offer PHP support.
Where to locate your PHP files
 Need to create PHP files in a location where the web server can process them
 Means that, the file should be in the server document root or a subfolder of the document root

The default location of the document root for the most common setups is as follows:
 XAMPP: C:\xampp\htdocs
 WampServer: C:\wamp\www
Set Up PHP on Your Own PC

 However, if your server does not support PHP, you must:


 install a web server
 install PHP
 install a database, such as MySQL
 The official PHP website (PHP.net) has installation instructions for
PHP: http://php.net/manual/en/install.php

3
1.4. Basic PHP Syntax

 A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.PHP script can be placed anywhere in the document. And it starts with <? php and
ends with?>:

<?php
// PHP code goes here
?>

 The default file extension for PHP files is “. php”. A PHP file normally contains HTML tags,
and some PHP scripting code.Below, we have an example of a simple PHP script which
sends the text "Hello World" to the browser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.There are two basic statements to output text
with PHP: echo and print. In the example above we have used the echo statement to output the
text "Hello World".

Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.

1.5. Comments in PHP


 A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
 PHP supports several ways of commenting:
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts

//of a code line


$x =  5 /* + 15 */  + 5;
echo $x;
?>
4
<! DOCTYPE html>
<html>
<body>
<?php
$color =  "red";
 Comments can be echo "My
used to: car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
 Let others understand what you are doing
echo "My boat is " . $coLOR . "<br>";
 Remind yourself?>of what you did - Most programmers have experienced coming back to
their own work a</body>
year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code
</html>

1.6. Syntax and Variables in PHP

PHP Case Sensitivity

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.

. DOCTYPE  html>
<!
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>

 However; all variable names are case-sensitive.

PHP Variables

 Variables are used for storing values, like text strings, numbers or arrays.
 When a variable is declared, it can be used over and over again in your script.
 All variables in PHP start with a $ sign symbol.
 The correct way of declaring a variable in PHP:

$var_name = value;

 New PHP programmers often forget the $ sign at the beginning of the variable. In that case it
will not work.

Let's try creating a variable containing a string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
5
 Note: Unlike other programming languages, PHP has no command for declaring a variable.
It is created the moment you first assign a value to it.
 A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
 Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable

 A variable name must start with a letter or the underscore character

 A variable name cannot start with a number

 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)

 Variable names are case-sensitive ($age and $AGE are two different variables)

PHP is a Loosely Typed Language

 In PHP, a variable does not need to be declared before adding a value to it.
 In the example above, you see that you do not have to tell PHP which data type the variable
is.
 PHP automatically converts the variable to the correct data type, depending on its value.
 In a strongly typed programming language, you have to declare (define) the type and name of
the variable before using it such as variable declaration in C++ , Java and so on.
 In PHP, the variable is declared automatically when you use it.

PHP Variables Scope

 In PHP, variables can be declared anywhere in the script.


 The scope of a variable is the part of the script where the variable can be referenced/used.
 PHP has three different variable scopes:

 Local

 Global

Global and Local Scope

 A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:

<?php
$x = 5;  // global scope

6
function myTest() {
     // using x inside this function will generate an error
     echo "<p>Variable x inside function is: $x</p>";

myTest();
echo "<p>Variable x outside function is: $x</p>";
?>

 A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:

<?php
function myTest() {
     $x = 5; // local scope
     echo "<p>Variable x inside function is: $x</p>";

myTest();
// using x outside the function will generate an error

echo "<p>Variable x outside function is: $x</p>";


?>

You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.

PHP The global Keyword

 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):

<?php
$x = 5;
$y = 10;
function myTest()  {
     global $x, $y;
     $y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>

 PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable.

7
 This array is also accessible from within functions and can be used to update global variables
directly.
 Example

<?php
$x = 5;
$y = 10;
function myTest()  {
     $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];

myTest();
echo $y; // outputs 15
?>

1.7. PHP Data Types


 Variables can store data of different types, and different data types can do different things.
 PHP supports the following data types:String , Integer ,Float (floating point numbers - also
called double) , Boolean , Array , Object and so on

 PHP String
 A string is a sequence of characters, like "Hello world!".
 A string can be any text inside quotes. You can use single or double quotes:
<?php 
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>"; 
echo $y;
?>
 PHP Integer
 An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
 Rules for integers:

 An integer must not have a decimal point

 An integer can be either positive or negative

 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -


prefixed with 0x) or octal (8-based - prefixed with 0)

 The PHP var_dump() function returns the data type and value:

8
<?php 
$x = 5985;
var_dump($x);
?>

 PHP Float
• A float (floating point number) is a number with a decimal point or a number in exponential
form.

<?php 
$x = 10.365;
var_dump($x);
?>

 PHP Boolean
 A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
 Booleans are often used in conditional testing.

 PHP Array
 An array stores multiple values in one single variable.
<?php 
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
1.8. PHP Operators
 Operators are used to perform operations on variables and values.
 PHP divides the operators in the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Increment/Decrement operators

 Logical operators

 String operators

 Array operators

9
 PHP Arithmetic Operators
 The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

Example
<?php
$x = 20;  
$x += 100;
echo $x;
?>   

PHP Comparison Operators

 Used to compare two values (number or string):

10
Example:
<?php
$x = 100;  
$y = "100";
var_dump($x == $y);  // returns true because values are equal
?>   
On the other hand, when we apply triple assignment comparison operator
<?php
$x = 100;  
$y = "100";
var_dump($x === $y);  // returns false because types are not equal
?>   
 PHP 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.

Example:-
<?php
$x = 10;  
echo ++$x; echo "<br>";
echo $x++;echo "<br>";
echo $x++;echo "<br>";
echo ++$x;echo "<br>";
echo ++$x;echo "<br>";
?>

this the of output for the above code

11
 PHP Logical Operators
 The PHP logical operators are used to combine conditional statements.

Example:-
<?php
$x = 100;  
$y = 50;
if ($x == 100  and $y == 50) {
     echo  "Hello world!";
}
?>   

 PHP String Operators


 PHP has two operators that are specially designed for strings.

Example: - (2). <?php


$txt1 = "Hello";
(1). <?php
$txt2 = " world!";
$txt1 =  "Hello"; $txt1 .= $txt2;
$txt2 =  " world!"; echo $txt1;
echo $txt1 . $txt2; ?>  
?>   

12
1.9. PHP Statements

1.9.1. Conditional Statements

Conditional statements are used to perform different actions based on different conditions. In
PHP we have the following conditional statements:

 if statement - use this statement to execute some code only if a specified condition is true
 if...else statement - use this statement to execute some code if a condition is true and another
code if the condition is false
 if...elseif....else statement - use this statement to select one of several blocks of code to be
executed
 switch statement - use this statement to select one of many blocks of code to be executed

 Use the if statement to execute some code only if a specified condition is true.

If Statement

Use if statement to execute some code only if a specified condition is true.

Syntax
if (condition) code to be executed if condition is true;

The following example will output "The day today is Thursday!" if the current day is Thursday:

<?php
$d=date("D");
if ($d=="Thu") echo "The day today is Thursday!";
?>

Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition
is true.

If...else Statement

Use if....else statement to execute some code if a condition is true and another code if a condition
is false.

13
Syntax
if (condition)
   code to be executed if condition is true;
else
   code to be executed if condition is false;

Example

The following example will output "The day today is Thursday!" if the current day is Thursday,
otherwise it will output "Have a nice day!":

<?php
$d=date("D");
if ($d=="Thu")
   echo "The day today is Thursday!";
else
   echo "Have a nice day!";
?>

If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces:

<?php
$d=date("D");
if ($d=="Thu")
   {
   echo "Hello!<br />";
   echo "Have a nice weekend!";
   echo "See you on Monday!";
   }
?>

If...elseif....else Statement

Use if....elseif...else statement to select one of several blocks of code to be executed.

Syntax
if (condition)
   code to be executed if condition is true;
elseif (condition)
   code to be executed if condition is true;

14
else
   code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Thursday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

<?php
$d=date("D");
if ($d=="Fri")
   echo "Have a nice weekend!";
elseif ($d=="Sun")
   echo "Have a nice Sunday!";
else
   echo "Have a nice day!";
?>

Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n)
{
case label1:
   code to be executed if n=label1;
   break;
case label2:
   code to be executed if n=label2;
   break;
default:
   code to be executed if n is different from both label1 and label2;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use
breakto prevent the code from running into the next case automatically. The default statement is
used if no match is found.

15
Example
<?php
switch ($x=4)
{
case 1:
  echo "Number 1";
  break;
case 2:
  echo "Number 2";
  break;
case 3:
  echo "Number 3";
  break;
default:
  echo "No number between 1 and 3";
}
?>
1.9.2. PHP Loop Statements

Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like 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 the
specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

while Loop

The while loop executes a block of code while a condition is true.

Syntax
while (condition)
 {
  code to be executed;

16
 }

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i
is less than, or equal to 5. i will increase by 1 each time the loop runs:

<?php
$i=1;
while($i<=5)
  {
  echo "The number is " . $i . "<br />";
  $i++;
  }
?>

It will display the following output

do...while Statement

The do...while statement will always execute the block of code once, it will then check the
condition, and repeat the loop while the condition is true.

Syntax
do
 {
  code to be executed;
  }while (condition);

Example

The example below defines a loop that starts with i=1. It will then increment i with 1, and write
some output. Then the condition is checked, and the loop will continue to run as long as i is less
than, or equal to 5:

17
<?php
$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "<br />";
  }
while ($i<=5);?>

It will display the following output

for loop statement

The for loop is used when you know in advance how many times the script should run.

Syntax
for (init; condition; increment)
 {
   code to be executed;
 }

Parameters:

 init: Mostly used to set a counter (but can be any code to be executed once at the beginning
of the loop)
 condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
 increment: Mostly used to increment a counter (but can be any code to be executed at the end
of the loop)

Note: Each of the parameters above can be empty, or have multiple expressions (separated by
commas).

18
Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i
is less than, or equal to 5. i will increase by 1 each time the loop runs:

<?php
for ($i=1; $i<=5; $i++)
 {
  echo "The number is " . $i . "<br />";
 }
?>

It will display the following output

foreach Loop

The foreach loop is used to loop through arrays.

Syntax
foreach ($array as$value)
 {
   code to be executed;  }

For every loop iteration, the value of the current array element is assigned to $value (and the
array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array
value.

Example

The following example demonstrates a loop that will print the values of the given array:

<?php
$x=array("one","two","three");
foreach ($x as $value)

19
 {
  echo $value . "<br />";
 }
?>
It will display the following output

20

You might also like