0% found this document useful (0 votes)
4 views33 pages

Introduction to Server Side Scripting-1

The document provides an overview of server-side scripting, focusing on the request/response procedure, the role of web servers like Apache, and the PHP programming language. It covers essential PHP concepts such as variables, arrays, operators, functions, conditionals, and sessions, along with examples for clarity. Additionally, it outlines the requirements for setting up a server environment for PHP development.

Uploaded by

mnrmnajib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

Introduction to Server Side Scripting-1

The document provides an overview of server-side scripting, focusing on the request/response procedure, the role of web servers like Apache, and the PHP programming language. It covers essential PHP concepts such as variables, arrays, operators, functions, conditionals, and sessions, along with examples for clarity. Additionally, it outlines the requirements for setting up a server environment for PHP development.

Uploaded by

mnrmnajib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Basics server

side scripting
INTRODUCTION
HTTP is a communication standard governing the requests and responses that take place between
the browser running on the end user’s computer and the web server.

Between the client and the server there can be several other devices, such as routers, proxies,
gateways, dns and so on.

A web server can usually handle multiple simultaneous connections and—when not communicating
with a client—spends its time listening for an incoming connection.

When one arrives, the server sends back a response to confirm its receipt.
The Request/Response
Procedure
The Request/Response Procedure
1. You enter http://server.com into your browser’s address bar.
2. Your browser looks up the IP address for server.com.
3. Your browser issues a request to that address for the web server’s home page.
4. The request crosses the Internet and arrives at the server.com web server.
5. The web server, having received the request, fetches the home page from its hard disk.
6. With the home page now in memory, the web server notices that it is a file incorporating
PHP scripting and passes the page to the PHP interpreter.
The Request/Response Procedure
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements, which the PHP interpreter now
passes to the MySQL database engine.
9. The MySQL database returns the results of the statements to the PHP interpreter.
10. The PHP interpreter returns the results of the executed PHP code, along with the
results from the MySQL database, to the web server.
11. The web server returns the page to the requesting client, which displays it.
Apache Web Server
Apache doesn’t serve up just HTML files—it handles a wide
range of files from images and Flash files to MP3 audio files, RSS
(Really Simple Syndication) feeds, and so on.

PHP running on Apache can even create images and other files
for you, either on the fly or in advance to serve up later.

To do this, you normally have modules either precompiled into


Apache or PHP or called up at runtime.
Requirements for Server Side Scripting
• A computer running on Windows, Linux, Mac Os
• A web server preferably running on Apache
• PHP Interpreter – The PHP engine processes code.
• Database – Ideally MySQL
• You may install a package comprising of all the necessary application
to host your web application (WAMP, MAMP, LAMP, or XAMPP)
• Ideally, we can agree on XAMPP because it is probably the best there
is for development
Introduction to PHP
• PHP is the hypertext processor, which is the language that you use to make the
server generate dynamic output
• your web pages will be a combination of PHP, HTML, and JavaScript, and some
MySQL statements laid out using CSS, and possibly utilizing various HTML5 elements.
• By default, PHP documents end with the extension .php
• To trigger the PHP commands, you need a new tag <?php and close with another
tag ?>
Display on the browser

<!DOCTYPE html>
<html> The output:
<body>
Hello world!
I'm about to learn PHP!
<?php
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
?>

</body>
</html>
PHP Comments

<!DOCTYPE html>
<html>
<body>

<?php
// This is a comment
/* This is a section of multiline comments
which will not be interpreted */
?>

</body>
</html>
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, but cannot start with a number

Example : Three different types of variable assignment


array()
<?php
$mycounter = 1;
$team = array('Bill', 'Mary', 'Mike', 'Chris', 'Anne');
$mystring = "Hello";
echo $team[3]; // Displays the name Chris
$myarray = array("One", "Two", "Three");
?>

Two-dimensional array

Example : Defining a two-dimensional array

<?php
$oxo = array(array('x', ' ', 'o'),
array('o', 'o', 'x'),
array('x', 'o', ' '));
?>
PHP Array
Numerical indexed array – array contents are indexed numerically

Example : Adding items to an array and retrieving them


The output:

<?php
$paper[] = "Copier"; This example prints out the following:

$paper[] = "Inkjet";
0: Copier
$paper[] = "Laser"; 1: Inkjet
$paper[] = "Photo"; 2: Laser
3: Photo
for ($j = 0 ; $j < 4 ; ++$j)
echo "$j: $paper[$j]<br>";
?>
PHP Array
Associative array – reference the items in an array by name

Example : Walking through an associative array using foreach...as


<?php
$paper = array('copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer", 'photo' => "Photographic Paper");
foreach($paper as $item => $description)
echo "$item: $description<br>";
?>

The output:

copier: Copier & Multipurpose


inkjet: Inkjet Printer
laser: Laser Printer
photo: Photographic Paper
PHP Operators
PHP operators are symbols that perform operations on variables and values. They are essential for
performing calculations, comparisons, and logical operations in PHP scripts.
PHP Logical Operators
Logical Operators: Used for combining or negating boolean expressions
PHP Comparison Operators
Comparison Operators: Used for comparing two values
String Concatenation
• String concatenation is performed using the period (.) to append one string of characters to another

$name = "John"; The output:


$welcomeMessage = "Welcome, " . $name . "!";
Welcome John !
echo $welcomeMessage;

• PHP supports two types of strings, denoted by the type of quotation mark that you use.
i. A literal string preserves the exact contents; use the single quotation mark (apostrophe)

$name = 'John'; The output:


$welcomeMessage = 'Welcome $name !';
Welcome $name !
echo $welcomeMessage;

ii. To include the value of a variable inside a string; use double-quoted strings

$name = "John"; The output:


$welcomeMessage = "Welcome $name !";
echo $welcomeMessage; Welcome John !
String Concatenation
• PHP supports the concatenation assignment operator (.=), which appends a string to an existing string

variable
$text = "Hello"; The output:
$text .= " World!";
Hello World !
echo $text;

• String can concatenate with other data types. PHP will automatically converts non-string types to

strings during concatenation

$age = 20; The output:


$message = "Age: " . $age;
echo $message; Age:20
PHP Functions
Functions are used to separate out sections of code that perform a particular task. It help to organize
code, reduce repetition, and improve readability
Example : Returning multiple values in an array
<?php
$names = fix_names("WILLIAM", "henry", "gatES");
Example : A simple function declaration
echo $names[0] . " " . $names[1] . " " . $names[2];
<?php
function longdate($timestamp)
function fix_names($n1, $n2, $n3)
{
{
return date("l F jS Y", $timestamp);
$n1 = ucfirst(strtolower($n1));
}
$n2 = ucfirst(strtolower($n2));
echo longdate(time()); //function call
$n3 = ucfirst(strtolower($n3));
?>
return array($n1, $n2, $n3);
}
?>
The output:

Friday April 25th 2025 The output:

William Henry Gates


Variable Types
Local variables
Defined inside functions or methods, local
Example:.A function using a local variable
variables exist only during the function's <?php
function myTest()
execution {
$x = 5; // local scope
For example, a variable declared inside a function echo "<p> Variable x inside function is: $x </p>";
}
will be discarded once the function finishes myTest();
executing, making local variables ideal for ?>

temporary data storage during function calls


Variable Types
Global variables
Declared outside of all functions or explicitly Example:.A function using a global variable
<?php
using the global keyword inside functions, global $x = 5; // global scope
echo "<p>Variable x outside function is: $x</p>";
variables can be accessed from any part of the
?>
script
Variable Types
Static variables
A local variable inside a function that you don’t want any Example:.A function using a static variable
<?php
other parts of your code to have access to, but you would
function counter()
also like to keep its value for the next time the function is {
static $count = 0;
called $count++;
echo $count;
Example: Allowed and disallowed static variable declarations }
<?php counter(); // Outputs 1
static $int = 0; // Allowed counter(); // Outputs 2
static $int = 1+2; // Disallowed (will produce a Parse error) counter(); // Outputs 3
static $int = sqrt(144); // Disallowed ?>
?>
Variable Types
• Superglobal variables - provided by the PHP environment but are global within the program, accessible
absolutely everywhere

• Best to sanitize superglobals in the code

• It provide essential access points to various types of data, including user input, server environment details,
cookies, session data, and uploaded files, making them fundamental for web development tasks

• Using the htmlentities function for sanitization is an important practice in any circumstance where user or other
third-party data is being processed for output, not just with superglobals.

$came_from = htmlentities($_SERVER['HTTP_REFERER']);
Variable Types
Superglobal Name Contents
$GLOBALS All variables that are currently defined in the global scope of the
script. The variable names are the keys of the array.
$_SERVER Information such as headers, paths, and script locations. The entries
in this array are created by the web server, and there is no guarantee
that every web server will provide any or all of these.
$_GET Variables passed to the current script via the HTTP Get method. It
stores key-value pairs where keys represent parameter names, and
values are the corresponding user data
$_POST Variables passed to the current script via the HTTP Post method. It
used when submitting form data that should not be visible in the URL,
such as passwords or large data sets
Variable Types
Superglobal Name Contents
$_FILES Items uploaded to the current script via the HTTP Post method,
including file name, type, size, temporary storage location, and error
status
$_COOKIE Variables passed to the current script via HTTP cookies. They are often
used for remembering user preferences, login credentials, and
tracking user behavior
$_SESSION Session variables available to the current script. This is commonly
used for user authentication.
$_REQUEST Contents of information passed from the browser; by default, $_GET,
$_POST, and $_COOKIE.
$_ENV Variables passed to the current script via the environment method.
Conditionals
• The if condition can be any valid PHP expression

• The action is taken when an if condition is TRUE

• when a condition is not TRUE, but you want to continue, you need to use else

• With an if...else statement, the first conditional statement is executed if the condition is TRUE. But if it’s
FALSE, the second one is executed

• The else if statement in if...else if...else construct is used when you want a number of different possibilities
to occur
Conditionals
• The switch statement is useful in cases in which one variable
or the result of an expression can have multiple values

Example : A multiple-line if...elseif...statement


<?php
if ($page == "Home")
echo "You selected Home";
elseif ($page == "About")
echo "You selected About";
elseif ($page == "News")
echo "You selected News";
elseif ($page == "Login")
echo "You selected Login";
elseif ($page == "Links")
echo "You selected Links";
?>
Conditionals
Example : A switch statement

<?php
switch ($page)
{
case "Home":
echo "You selected Home"; break;
case "About":
echo "You selected About"; break;
case "News":
echo "You selected News"; break;
case "Login":
echo "You selected Login"; break;
case "Links":
echo "You selected Links"; break;
default:
echo "Unrecognized selection";break;
}
?>
Looping
Looping are fundamental in PHP to execute a block of code repeatedly based on given conditions. It allows PHP
programmers to handle repetitive tasks and process data collections smoothly.

• A while loop continuously executes and checks for the condition to stay TRUE

• Slight variation to the while loop is the do...while loop, used when you want a block of code to be executed at
least once and made conditional only after that

• The for loop, is also the most powerful, as it combines the abilities to set up variables as you enter the loop,
test for conditions while iterating loops, and modify variables after each iteration
Example : A while loop to print the 12 times table

Looping
<?php
$count = 0;
while (++$count <= 12)
echo "$count times 12 is " . $count * 12 . "<br>";
Example : The for loop with added curly braces ?>
<?php
for ($count = 1 ; $count <= 12 ; ++$count)
Example : A do...while loop for printing the times table for 12
{
<?php
echo "$count times 12 is " . $count * 12;
$count = 1;
echo "<br>";
do
}
{
?>
echo "$count times 12 is " . $count * 12;
echo "<br>";
}
while (++$count <= 12);
?>
PHP Session
• Sessions provide a solid way of keeping track of users

• Starting a session requires calling the PHP function session_start


before any HTML has been output

session_start();

• To save a session variable

$_SESSION['variable'] = $value;

• To read a session variable


$variable = $_SESSION['variable'];
PHP Session
• To remove a session variable, issue

session_destroy();

Example : A handy function to destroy a session and its data


<?php
function destroy_session_and_data()
{
session_start();
$_SESSION = array();
setcookie(session_name(), '', time() - 2592000, '/');
session_destroy();
}
?>
T H A N K YO U

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy