Vous êtes sur la page 1sur 6

1

3. Server Side Scripting


PHP -Beginning with PHP-The PHP Language-Processing Web Forms-Object-Oriented Programming with PHP-
Database processing using PHP

PHP -Beginning with PHP-The PHP Language
PHP stands for PHP: Hypertext Preprocessor. PHP is a server-side scripting language.
When a browser calls a PHP document, the Server reads the PHP document, runs the PHP code and returns the
resulting HTML code to the browser
What is a PHP File?
PHP files can contain text, HTML tags and scripts
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ".php", ".php3", or ".phtml"
The PHP script is executed on the server, and the plain HTML result is sent back to the browser
Rules for PHP variable names:
Variables in PHP starts with a $ sign, followed by the name of the variable
The variable name must begin with a letter or the underscore character
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
A variable name should not contain spaces
Variable names are case sensitive (y and Y are two different variables)
In PHP, a variable does not need to be declared before adding a value to it.
PHP automatically converts the variable to the correct data type, depending on its value.
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>

<?php
$name = "Anand";
echo "Hello, $name";
?>

<?php
$name = 'Anand';
echo 'Hello, $name';
?>

<?php
$weight=100;
echo 'The total weight is ' . $weight . 'kg';
?>

<?php
if (mail("pranand3@yahoo.com",
"Hello", "This is a test email")) {
echo "Email was sent successfully";
}
else {
echo "Email could not be sent";
}
?>


2


In PHP, there are three kinds of arrays:
Numeric array - An array with a numeric index
Multidimensional array - An array containing one or more arrays
Associative array - An array where each ID key is associated with a value

<?php
//Numeric Array
$colors=array("Red","Blue","Green","Yellow");
$fruits[0]="Apple";
$fruits[1]="Mango";
$fruits[2]="Grape";
echo "<br>".$colors[1];
echo "<br>".$fruits[1];
?>

<?php
//Multidimensional Array
$items['books'][0]="book0";
$items['books'][1]="book1";
$items['bags'][0]="bag0";
$items['pens'][0]="pen0";
$items['pens'][1]="pen1";
$items['pens'][2]="pen2";
echo $items['pens'][1];
?>

<?php
//Associative Array
$ages = array('Peter'=>32, 'Anand'=>42, 'Ram'=>34);
echo "<br>".$ages['Anand'];
?>


In PHP, we have the following looping statements:
while - loops through a block of code while a specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as a 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
<?php
$a=array("Red","Blue","Green","Yellow");
$i=0;
while($i<count($a))
{echo "<br>".$a[$i];++$i;}
?>

<?php
$a=array("Red","Blue","Green","Yellow");
$i=0;
do {echo "<br>".$a[$i];++$i;} while($i<count($a));
?>

3

<?php
$a=array("Red","Blue","Green","Yellow");
for($i=0;$i<count($a);++$i)
echo "<br>".$a[$i];
?>

<?php
$a=array("Red","Blue","Green","Yellow");
foreach($a as $k=>$v)
echo "<br>".$v;
?>


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.
If your application deals with browsers that do not support cookies, you will have to use other methods to
pass information from one page to another in your application. One method is to pass the data through forms.
Other method is to use sessions.
sc.php
//set cookie
<?php
$expire=time()+60*60*24*30;
// One month =60 sec * 60 min * 24 hours * 30 days.
setcookie("user", "Anand", $expire);
// variable, value, expiration
echo "Cookie set successfully";
?>
rc.php
//retrieve cookie
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
dc.php
//delete cookie
// To delete cookie set the expiration date
//to one hour ago (past)
<?php
setcookie("user", "", time()-3600);
echo "Cookie deleted successfully";
?>

Run rc.php

Run sc.php

Run rc.php

Run dc.php

Run rc.php




A PHP session variable is used to store information about, or change settings for a user session. Session
variables hold information about one single user, and are available to all pages in one application.
When you are working with an application, you open it, do some changes and then you close it. This is much
like a Session. The computer knows who you are. It knows when you start the application and when you end. But on
the internet there is one problem: the web server does not know who you are and what you do because the HTTP
address doesn't maintain state.
4

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e.
username, shopping items, etc). However, session information is temporary and will be deleted after the user has
left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is
either stored in a cookie or is propagated in the URL.
1.php
<?php
session_start();
$_SESSION['a']=10;
echo '<a href="2.php">Click to goto page 2</a>';
?>
2.php
<?php
session_start();
$_SESSION['a']++;
echo $_SESSION['a'];
?>





Functions in php
// default parameter
<?php
function add_tax_rate($amount, $rate=10)
{
$total = $amount * (1 + ($rate / 100));
return($total);
}
echo add_tax_rate(10);
echo "<br>".add_tax_rate(10, 9);
?>

// call by value
<?php
function increment($value, $amount = 1) {
$value = $value +$amount;
}
$a = 10;
echo $a.'<br />';
increment($a);
echo $a.'<br />';
?>

// call by reference
<?php
function increment(&$value, $amount = 1) {
$value = $value +$amount;
}
$a = 10;
echo $a.'<br />';
increment($a);
echo $a.'<br />';
?>


5

Files in php

Welcome.txt
This is welcome.txt file
File.php
<?php
$file=fopen("welcome.txt","r") or
exit("Unable to open file!");
while (!feof($file))
echo fgetc($file);
fclose($file);
?>



Server Side Includes (SSI)
You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or
require() function.
The two functions are identical in every way, except how they handle errors:
include() generates a warning, but the script will continue execution
require() generates a fatal error, and the script will stop
These two functions are used to create functions, headers, footers, or elements that will be reused on multiple
pages.
Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for
all your web pages. When the header needs to be updated, you can only update the include file

Processing Web Forms
User input should be validated on the browser whenever possible (by client scripts). Browser validation is
faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to
validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then
get the error messages on the same page. This makes it easier to discover the error.
home.php
<form method="POST" action="home.php">
<input type="hidden" name= "posted" value="true">
Please enter your name:
<input type="text" name="fullname">
<input type="submit" value="Send">
</form>
<?php
if(isset($_POST['posted']))
echo "Hello ".$_POST['fullname'];
?>

1.php
<?php
echo '<a href="2.php?a=10&b=20">Click to goto page 2</a>';
?>
2.php
<?php
echo "a=$_GET[a]<br>";
echo "b=$_GET[b]";
?>


6

Object-Oriented Programming with PHP
A class is the template structure that defines an object. It can contain functions also known as class methods
and variables also known as class properties or attributes.
Each class consists of a set of PHP statements that define how to perform a task or set of tasks that you
want to repeat frequently. The class can contain private methods, which are only used internally to perform the
class's functions, and public methods, which you can use to interface with the class.
A good class hides its inner workings and includes only the public methods that are required to provide a
simple interface to its functionality. If you bundle complex blocks of programming into a class, any script that uses
that class does not need to worry about exactly how a particular operation is performed - All that is required is
knowledge of the class's public methods.
Because there are many freely available third-party classes for PHP, in many situations, you need not waste
time implementing a feature in PHP that is already freely available.
One of the advantages of OO programming is that it can allow your code to scale into very large projects
easily. In OO programming, a class can inherit the properties of another and extend it; this means that functionality
that has already been developed can be reused and adapted to fit a particular situation. This is called inheritance,
and it is a key feature of OO development.
The following example illustrates how to create and use php classes and objects.
<?php
class myClass {
var $myname = "Anand";

function myMethod() {
echo "My name is " . $this->myname . "<br>";
}
}
$myObject = new myClass;
$myObject->myMethod();
$myObject->myname = "Ram";
$myObject->myMethod();
?>
Output:



Database processing using PHP
What is MySQL?
MySQL is a database server
MySQL supports standard SQL

Connecting to Server
mysql_connect('localhost','root','');
Selecting the database
mysql_select_db('sdb');
Selecting records from a table
$q="select * from s order by rno";
$r=mysql_query($q);
Inserting records into a table
$q="insert into s values ('$rno','$name','$photo')";
mysql_query($q);
Deleting records from a table
$q="delete from s where rno=$rno";
mysql_query($q);
updating records
update s set rno = 5 where rno =10

Vous aimerez peut-être aussi