0% found this document useful (0 votes)
41 views

Java Script and PHP

Client-side scripting enhances functionality and appearance of web pages. JavaScript is a scripting language that adds interactivity to HTML pages and is usually embedded directly into HTML. JavaScript can put dynamic text into pages, react to events, read and write HTML elements, validate data, detect the browser, and create cookies. It is defined using the <script> tag and can be placed in the <head> or <body> sections.

Uploaded by

Robel Asfaw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Java Script and PHP

Client-side scripting enhances functionality and appearance of web pages. JavaScript is a scripting language that adds interactivity to HTML pages and is usually embedded directly into HTML. JavaScript can put dynamic text into pages, react to events, read and write HTML elements, validate data, detect the browser, and create cookies. It is defined using the <script> tag and can be placed in the <head> or <body> sections.

Uploaded by

Robel Asfaw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Introduction

• Client-side scripting enhances functionality and


appearance
• Makes pages more dynamic and interactive
• Pages can produce immediate response without
contacting a server
• Browser has to have a built-in (JavaScript) interpreter
• Foundation for complex server-side scripting

Prepared By Mebiratu B. 22-Feb-10 1


• What is JavaScript?
• It is designed to add interactivity to HTML pages

• It is a scripting language (a lightweight programming language)

• Usually embedded directly into HTML pages

Prepared By Mebiratu B. 22-Feb-102


What can a JavaScript Do?
• put dynamic text into an HTML page

• can react to events

• can read and write HTML elements

• can be used to validate data

• can be used to detect the visitor’s browser

• can be used to create cookies

• Store and retrieve information on the visitor’s computer

Prepared By Mebiratu B. 22-Feb-103


How To
• The HTML <script> tag is used to insert a JavaScript into an HTML
page

<script type=“text/javascript”>

document.write(“Hello World!”)

</script>

• Ending statements with a semicolon?

• Optional; required when you want to put multiple statements on a


single line

Prepared By Mebiratu B. 22-Feb-104


Scripting
• <script> tag
• Indicate that the text is part of a script
• type attribute
• Specifies the type of file and the scripting language use:
• Value: “text/javascript”
• writeln method of the document object
• Write a line in the document and position the cursor in the
next line
• Does not affect the actual rendering of the HTML document
• What is being written by JavaScript is the set of html
instructions that in turn determine the rendering of the html
document

Prepared By Mebiratu B. 22-Feb-10 5


JavaScript Where To
• There are a flexible given to include JavaScript code anywhere in an HTML
document.

• But there are following most preferred ways to include JavaScript in your
HTML file.

• Script in <head>…</head> section


• Script in <body>…</body> section
• Script in <body>…</body> and <head>…</head> section>
• Script in and external file and then include in <head>…</head> section

Prepared By Mebiratu B. 22-Feb-106


• <html>
<head>
<title> First JavaScript page </title></head>
<body>
<h1> First JavaScript Page</h1>
<script type=”text/javascript”>
document.write(“<HR>”);
document.write(“Hello World Wide Web”); //comments goes here
document.write(“<HR>”);
</script>
</body>
• </html>

Prepared By Mebiratu B. 22-Feb-10 7


• The word document.write is a standard JavaScript command
for writing output to a page.

• write command between the <script> and </script> tags, the


browser will recognize it as a JavaScript command and
execute the code line.

• // is used for single line comment whereas /* comment …*/ is


used for multiple line comment in JavaScript coding

Prepared By Mebiratu B. 22-Feb-10 8


• Variables and operators
• Variables in JavaScript should be declared before using them with the
var keword.

• The scope of the variable is the region of the program in which it is


defined .

• Javascript variable will have only two scopes.


• Global variable –has global scope which is defined everywhere in the
JavaScript code.

• Local variable – visible only within a function where it is defined.


Function parameters are always local to that function.

Prepared By Mebiratu B. 22-Feb-10 9


• JavaScript allows working with three primitive data type:
• Numbers e.g. 123, 120.50 etc
• String of text e.g. “ javascript is my interest” etc
• Boolean e.g. true or false. The arithmetic operators (+, - , *, / and %)
are supported in JavaScript language

Prepared By Mebiratu B. 22-Feb-10 10


• <html>
<head><title>Arithmetic Operator Example</title></head>
<body>
<script type="text/javascript">
var num1=15;
var num2=5;
sum=var1+var2;
document.write("Sum="+sum);
</script>
• </body>
• <html>

Prepared By Mebiratu B. 22-Feb-10 11


• To compare the value of two variables, comparison operators are used.
These are == for equal, != not equal, > greater than, < less than, >=
greater or equal and <= less than or equal.

• The logical operators supported by javascript language are && called


logical AND operator, | | called logical OR operator and ! called logical
NOT operator

Prepared By Mebiratu B. 22-Feb-10 12


• Conditional Statement
If statement
if (expression){
Statement(s) to be executed if expression is true
}
if...else statement:
Syntax:
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
} Prepared By Mebiratu B. 22-Feb-10 13
• if...else if... statement:
• The if...else if... statement is the one level advance form of
control statement that allows JavaScript to make correct
decision out of several conditions.
Syntax:
if (expression 1){
Statement(s
}
• else if (expression 2){
Statement(s)
}else if (expression 3){
Statement(s)
}else{ Statement(s)
}

Prepared By Mebiratu B. 22-Feb-10 14


• <html><head><title>conditional
</title></head>
<body>
<script type="text/javascript">
var d=new Date();
theday=d.getDay();
if(theday==1)
{document.write("First Monday");}
else if(theday==2)
{document.write("Second Teusday");}
else if(theday==3)
{document.write("Sleepy Sunday");}
else
{document.write("I'm looking forward to this weekend");}
</script>
</body><html>

Prepared By Mebiratu B. 22-Feb-10 15


• switch statement:
The basic syntax of the switch statement is to give an expression to
evaluate and several different statements to execute based on the value of
the expression.

• The interpreter checks each case against the value of the expression until
a match is found.

• If nothing matches, a default condition will be used

Prepared By Mebiratu B. 22-Feb-10 16


• Syntax:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;

case condition n: statement(s)
break;
default: statement(s)
}

Prepared By Mebiratu B. 22-Feb-10 17


• The for loop
• The for loop is the most compact form of looping and
includes the following three important parts:
• The loop initialization –counter starting value which is
executed before the loop begins
• The test statement- the given condition is true or not is tested
• The iteration statement – increasing or decreasing the counter
Syntax:
for (initialization; test condition; iteration statement){
Statement (s)
}

Prepared By Mebiratu B. 22-Feb-10 18


• The while Loop
• The most basic loop in JavaScript is the while loop which
loops through a block of code as long as a specified
condition is true
Syntax:
while (expression){
Statement(s) to be executed if expression is true
}

Prepared By Mebiratu B. 22-Feb-10 19


• The do …while loop
• The do…while loop is similar to the while loop except that
the condition check happens at the end of the loop. This
means that the loop will always be executed at least once,
even if the condition is false.
Syntax:
do { Statement (s) to be executed;
• } while (expression);

Prepared By Mebiratu B. 22-Feb-10 20


• The break Statement:
is used to exit a loop early, breaking out of the enclosing
curly braces

The continue Statement: The continue statement tells the


interpreter to immediately start the next iteration of the loop
and skip remaining code block.

Prepared By Mebiratu B. 22-Feb-10 21


<html>
<head><title>conditional statement example</title></head>
<body><script type="text/javascript">
var x = 1;
while (x < 20)
{
if (x == 10){
break; }
x = x + 1;
document.write( x + "<br />");
}
</script>
</body></html>
Prepared By Mebiratu B. 22-Feb-10 22
Function definition:

• The most common way to define a function in JavaScript is by using the


function keyword, followed by a unique function name, a list of
parameters may be empty, and a statement block surrounded by curly
braces.
Syntax:
<script type=”text/javascript”>
function functionname(parameter-list)
{
Statements
}
</script>

Prepared By Mebiratu B. 22-Feb-10 23


• Example: A simple function that takes no parameters called
sayHello is defined here:
<script type=”text/javascript”>
function sayHello() //function definition
{
Alert(“Hello there”);
}
</script>

Prepared By Mebiratu B. 22-Feb-10 24


• Function Calling: to invoke a function somewhere later in
the script, we should simple need to write the name of that
function as follows:
<script type=”text/javascript”>
sayHello(); //function calling
</script>

Prepared By Mebiratu B. 22-Feb-10 25


• <html>
<head>
<script type="text/javascript">
function sayHello() //function definition
{ alert("Hello there!");}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()“>
</form>
</body>
</html>

Prepared By Mebiratu B. 22-Feb-10 26


• Alert Dialog Box: an alert dialog box is mostly used to
give a warning message to the users
Confirmation Dialog Box: A confirmation dialog box is
mostly used to take user’s consent on any option. It
displays a dialog box with two buttons: Ok and Cancel.

• Prompt Dialog: Take input from user

Prepared By Mebiratu B. 22-Feb-10 27


• <html>
<head><title>hhhh</title>
</head>
<body>
<form name=myform>
<input type=button value="Try it now"
onClick="if(confirm('Format the hard disk?'))
alert('You are very brave!');
else alert('A wise decision!')">
</form>
</body>
</html>

Prepared By Mebiratu B. 22-Feb-10 28


• <html>
<head>
<script type="text/javascript">
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
</script>
</head>
</html>

Prepared By Mebiratu B. 22-Feb-10 29


Form Validation
• Form validation used to occur at the server, after the client had entered
all necessary data and then pressed the Submit button.

• If some of the data that had been entered by the client had been in the
wrong form or was simply missing, the server would have to send all
the data back to the client and request that the form be resubmitted with
correct information.

• JavaScript provides a way to validate form's data on the client's


computer before sending it to the web server. Form validation generally
performs two functions

Prepared By Mebiratu B. 22-Feb-10 30


• Basic Validation - First of all, the form must be checked to
make sure data was entered into each form field that required
it. This would need just loop through each field in the form
and check for data.

• Data Format Validation - Secondly, the data that is entered


must be checked for correct form and value. This would need
to put more logic to test correctness of data.

Prepared By Mebiratu B. 22-Feb-10 31


• Basic Form Validation:
• First we will show how to do a basic form validation. In the below
form we are calling validate() function to validate data when
onsubmit event is occurring.
<script type="text/javascript">
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
return( true );
}
</script>

Prepared By Mebiratu B. 22-Feb-10 32


• <html><head><title> User Account</title>
<script type ="text/JavaScript">
function CheckPassword()
{
var Password, ConfPassword, Result;
Password = document.frmRegistration.txtPassword.value;
ConfPassword = document.frmRegistration.txtConfirmPass.value;
if(Password != ConfPassword)
alert( “Not match" );
}
</script></head><body>
<h1>User password Registration</h1>
<form name="frmRegistration">
Username<input type="text“ name="txtUsername“/>
Password<input type="password“ name="txtPassword" />
Confirm:<input type="password“ name="txtConfirmPass“/>
<input type="button" value="Send It" onClick="CheckPassword()">
</form></body></html>
Prepared By Mebiratu B. 22-Feb-10 33
• Data Format Validation:
• Now we will see how we can validate our entered form data before
submitting it to the web server.
• This example shows how to validate an entered email address which
means email address must contain at least an @ sign and a dot (.).

<script type="text/javascript">
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
return( true );
}
</script>

Prepared By Mebiratu B. 22-Feb-10 34


Server side script
• Contents
• Introduction
• PHP Comments, Variables and Strings .
• PHP Expressions, Operators, control structures
• PHP Arrays
• PHP Functions
• FORM validation with PHP
• Manipulating MySQL Database with PHP
• Designing Online Databases with phpMyAdmin
• Cookies and Sessions in PHP

Prepared By Mebiratu B. 22-Feb-10 35


Introduction
• PHP is a scripting language that allows you to create

dynamic Web pages

• You can embed PHP scripting within normal html coding

• PHP includes a comprehensive set of database access

functions

• Platform independent
Prepared By Mebiratu B. 22-Feb-10 36
Basics of PHP
• PHP files end with .php
• PHP code is contained within tags
<?php ?> or
• HTML script tags: (This syntax is removed after PHP 7.0.0)
<script language="php"> </script>
• Comments
// for single line
/* */ for multiline

Prepared By Mebiratu B. 22-Feb-10 37


7 <?php Scripting delimiters
8 $name = "Arjun Bala"; // declaration
9
10
?>
PHP Basic Example
Declare variable $name
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12 <head>
Single-line comment
13 <title>Untitled document</title>
14 </head>
15
16 <body style = "font-size: 2em">
17 <p>
18 <strong>
19
20 <!-- print variable name’s value -->
21 Welcome to PHP, <?php print( "$name" ); ?>!
22 </strong>
23 </p>
Function print outputs the value of
24 </body>
variable $name
25 </html>
Prepared By Mebiratu B. 22-Feb-10 38
Variables
• All variables begin with $ and can contain letters, digits and underscore
(variable name can not begin with digit)

• PHP variables are Case-sensitive


• Don’t need to declare variables
• The value of a variable is the value of its most recent assignment
• Variables have no specific type other than the type of their current value
• Can have variable variables $$variable (not recommended)
Example :

$a = “Arjun Bala”;

echo($a);
Prepared By Mebiratu B. 22-Feb-10 39
Variables (Cont.)
• Variable names inside strings replaced by their value
Example : $name = “Arjun Bala”;
$str = “My name is $name”;
• Type conversions
• settype function
• Type casting
• Concatenation operator
• . (period)

Prepared By Mebiratu B. 22-Feb-10 40


Variable types
Data Type Description
int, integer Whole numbers (i.e., numbers without a decimal point).
float, double Real numbers (i.e., numbers containing a decimal point).
string Text enclosed in either single ('') or double ("") quotes.
bool, boolean True or false.
array Group of elements.
object Group of associated data and methods.
resource An external data source.
NULL No value.

Prepared By Mebiratu B. 22-Feb-10 41


Variables Scope
• Scope refers to where within a script or program a variable has meaning or a
value

• Mostly script variables are available to you anywhere within your script.

• Note that variables inside functions are local to that function and a function
cannot access script variables which are outside the function even if they are

in the same file.

• The modifiers global and static allow function variables to be accessed


outside the function or to hold their value between function calls

respectively
Prepared By Mebiratu B. 22-Feb-10 42
Example (Variables)
5 <!-- Demonstration of PHP data types -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>PHP data types</title>
10 </head>
11
12 <body>
13 Assign a string to variable
14 <?php
$testString
15
16 // declare a string, double and integer
17 $testString = "3.5 seconds";
18 $testDouble = 79.2; Assign a double to variable
19 $testInteger = 12; Assign an integer to variable
$testDouble
20 ?> $testInteger
21

Prepared By Mebiratu B. 22-Feb-10 43


22 <!-- print each variable’s value -->
23
24
25
Example (Variables) (Cont.)
<?php print( $testString ); ?> is a string.<br />
<?php print( $testDouble ); ?> is a double.<br />
<?php print( $testInteger ); ?> is an integer.<br />
26
27 <br /> Print each variable’s value
28 Now, converting to other types:<br />
29 <?php
30
31 // call function settype to convert variable
32 // testString to different data types
33 print( "$testString" );
34 settype( $testString, "double" );
35 print( " as a double is $testString <br />" );
36 print( "$testString" );
37 settype( $testString, "integer" );
38 print( " as an integer is $testString <br />" );
39 settype( $testString, "string" );
40 Call function
settype
print( "Converting back to a string results in to
41 $testString <br /><br />" );
convert the data type
Call function settype to of
42
variable
convert $testString
the data type of to a
43 Prepared By Mebiratu B. 22-Feb-10 44
double.
variable $testString to an
Convert variable
integer.
$testString back to a string
44 $data = "98.6 degrees";
45
46
Example (Variables) (Cont.)
// use type casting to cast variables to a
// different type
47 print( "Now using type casting instead: <br />
48 As a string - " . (string) $data .
49 "<br />As a double - " . (double) $data .
50 "<br />As an integer - " . (integer) $data );
51 ?>
52 </body> Use type casting to cast variable
53 </html> $data to different types

Prepared By Mebiratu B. 22-Feb-10 45


PHP Arrays
• Array is a group of variable that can store multiple values under a single name.
• In PHP, there are three types of array.
• Numeric Array
These arrays can store numbers, strings and any object but their
index will be represented by numbers. By default array index starts
from zero.
• Associative Array
The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
Associative array will have their index as string so that you can
establish a strong association between key and values.
• Multidimensional Array
A multi-dimensional array each element in the main array can also
be an array. And each element in the sub-array can be an array, and
so on. Values in the multi-dimensional array are accessed using
Prepared By Mebiratu B. 22-Feb-10 46
multiple index.
PHP Arrays (Example)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Array manipulation</title>
10 </head>
11
12 <body>
13 <?php Create the array $first by assigning a
14
value to an array element.
15 // create array first
16 print( "<strong>Creating the first array</strong>
17 <br />" );
18 $first[ 0 ] = "zero";
19 $first[ 1 ] = "one";
Assign a value to the array, omitting the
20 $first[ 2 ] = "two";
21 $first[] = "three";
index. Appends a new element to the end
22
of the array.
23 // print each element’s index and value
Use a for loop to print out each element’s index
24 for ( $i = 0; $i < count( $first ); $i++ )
25 print( "Element $i is $first[$i]
value. Function count returns the total number o
<br />" );
elements in the array.
Prepared By Mebiratu B. 22-Feb-10 47
27 print( "<br /><strong>Creating the second array

PHP Arrays (Example) (Cont.)


28 </strong><br />" );
29 Call function to create an array that array
30 contains the arguments passed to it. Store the
// call function array to create array second
31 array in variable $second.
$second = array( "zero", "one", "two", "three" );
32 for ( $i = 0; $i < count( $second ); $i++ )
33 print( "Element $i is $second[$i] <br />" );
34
35 print( "<br /><strong>Creating the third array
36 </strong><br />" );
37
38 // assign values to non-numerical indices
39 $third[ "ArtTic" ] = 21;
40 $third[ "LunaTic" ] = 18;
Assign values to non-numerical
41 $third[ "GalAnt" ] = 23;
indices in array $third.
42
43
Function reset sets the internal pointer to
// iterate through the array elements and print each
44 // element’s name and value the first element of the array.
45 for ( reset( $third ); $element = key( $third );
46 next( $third ) )
47 print( "$element is $third[$element] <br />" );
Prepared By Mebiratu B.
Function key returns the index of the22-Feb-10
element48
Function
which thenext moves
internal the internal
pointer pointer to the next
references.
element.
PHP Arrays (Example) (Cont.)
49 print( "<br /><strong>Creating the fourth array
50 </strong><br />" );
51
52 // call function array to create array fourth using
53 // string indices
54 $fourth = array(
55 "January" => "first", "February" => "second",
56 "March" => "third", "April" => "fourth",
57 "May" => "fifth", "June" => "sixth",
58 "July" => "seventh", "August" => "eighth",
59 "September" => "ninth", "October" => "tenth",
60 "November" Operator => is used in function array to assign
=> "eleventh","December" => "twelfth"
61 ); each element a string index. The value to the left
62
of the operator is the array index, and the value t
63 // print each element’s name and value
64 foreach ( $fourth as $element =>
the right is the element’s value.
$value )
65 print( "$element is the $value month <br />" );
66 ?>
67 </body>
68 </html>

Prepared By Mebiratu B. 22-Feb-10 49


PHP Array Functions
• count($array) / sizeof($array)
Count all elements in an array, or something in an object
• array_shift($array)
Remove an item from the start of an array and shift all the numeric
indexes
• array_pop($array)
Remove an item from the end of an array and return the value of
that element
• array_unshift($array,”New Item”)
Adds item at the beginning of an array
• array_push($array,”New Item”)
Adds item at the end of an array

Prepared By Mebiratu B. 22-Feb-10 50


PHP Array Functions (Cont.)
• sort($array [, $sort_flags])

• Array can be sorted using this command, which will order them from the lowest to
highest

• If there is a set of string stored in the array they will be sorted alphabetically.

• The type of sort applied can be chosen with the second optional parameter $sort_flags
which can be

• SORT_REGULAR compare items normally (don’t change type)

• SORT_NUMERIC compare items numerically

• SORT_STRING compare items as string

• SORT_LOCALE_STRING compare items as string, based on the current


locale

• rsort($array [, $sort_flags])

•Prepared
It will sort array
By Mebiratu B. in reverse order (i.e. from highest to lowest) 22-Feb-10 51
PHP Array Functions (Cont.)
• shuffle($array)
It will mix items in an array randomly.
• array_merge($array1,$array2)
It will merge two arrays.
• array_slice($array,$offset,$length)
returns the sequence of elements from the array $array as specified by
the $offset and $length parameters.

Prepared By Mebiratu B. 22-Feb-10 52


PHP Functions
• A function is a piece of code which takes one more input in
the form of parameter and does some processing and returns a
value.
• Creating PHP function
Begins with keyword function and then the space and then
the name of the function then parentheses”()” and then code
block “{}”

<?php
function functionName()
{
//code to be executed;
}
?>
Note: function name can start with a letter or underscore "_", but not a number!

Prepared By Mebiratu B. 22-Feb-10 53


PHP Functions (Cont.)
<?php
<?php
function functionName()
functionName();
{
//code to be executed;
function functionName()
}
{
//code to be executed;
functionName();
}
?>
Here function call is before ?>
implementation, which is also valid

Here function call is aft


• Where to put the function implementation? implementation, which
In PHP a function could be defined before or after it is called.

Prepared By Mebiratu B. 22-Feb-10 54


Browser Control
• PHP can control various features of a browser.

• This is important as often there is a need to reload the same page or


redirecting the user to another page.

• Some of these features are accessed by controlling the information sent


out in the HTTP header to the browser, this uses the header() command
such as :

header(“Location: index.php”);

Or can specify the content type like,

header(“Content-Type: application/pdf”);

Prepared By Mebiratu B. 22-Feb-10 55


Browser Detection
• The range of devices with browsers is increasing so it is becoming
more important to know which browser and other details you are
dealing with.

• The browser that the server is dealing can be identified using:


$browser_ID = $_SERVER[‘HTTP_USER_AGENT’];

• Typical response of the above code is follows:


Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/56.0.2924.87

• which specifies that user is using Chrome browser and windows


10 OS with 64 bit architecture
Prepared By Mebiratu B. 22-Feb-10 56
Form Processing
• We can access form data using there inbuilt PHP associative array.
• $_GET => in case we have used get method in the form
• $_POST => in case we have used post method in the form
• $_REQUEST => in both the cases
• $_PUT
• For example,
html recive.php
<form action=“recive.php” <?php
method=“get”> $u = $_GET[‘UserName’];
<input type=“text” echo($u);
name=“UserName”> ?>
<input type=“submit”>
</form>

Prepared By Mebiratu B. 22-Feb-10 57


File Handling in PHP
• PHP has several functions for creating, reading, uploading, and editing files.
• fopen($filename, $mode) will return the handle to access file.
• "r" (Read only. Starts at the beginning of the file)
• "r+" (Read/Write. Starts at the beginning of the file)
• "w" (Write only. Opens and clears the contents of file; or creates a new file if
it doesn't exist)

• "w+" (Read/Write. Opens and clears the contents of file; or creates a new file
if it doesn't exist)

• "a" (Write only. Opens and writes to the end of the file or creates a new file if
it doesn't exist)

• "a+" (Read/Write. Preserves file content by writing to the end of the file)
Prepared By Mebiratu B. 22-Feb-10 58
File Handling Example
text.txt
Hello World

Read File
<?php
$file = fopen("text.txt","a+");
$text = fread($file,filesize("text.txt"));
echo($text);
?>
Write File
<?php
fwrite($file," New Content");
$text = fread($file,filesize("text.txt"));
echo($text);
?>
Prepared By Mebiratu B. 22-Feb-10 59
Cookies in PHP
• HTTP cookies are data which a server-side script sends to a web client to
keep for a period of time.
• On every subsequent HTTP request, the web client automatically sends the
cookies back to server (unless the cookie support is turned off).
• The cookies are embedded in the HTTP header (and therefore not visible to
the users).
• Shortcomings/disadvantages of using cookies to keep data
• User may turn off cookies support.
• Users using the same browser share the cookies.
• Limited number of cookies (20) per server/domain and limited size (4k bytes)
per cookie
• Client can temper with cookies

Prepared By Mebiratu B. 22-Feb-10 60


Cookies in PHP (Cont.)
• To set a cookie, call setcookie()
• e.g., setcookie('username', ‘AVB');
• To delete a cookie (use setcookie() without a value)
• e.g., setcookie('username');
• To retrieve a cookie, refer to $COOKIE
• e.g. $username = $_COOKIE['username‘];
• Note :
• Cookies can only be set before any output is sent.
• You cannot set and access a cookie in the same page. Cookies set in a
page are available only in the future requests.

Prepared By Mebiratu B. 22-Feb-10 61


Cookies in PHP (Cont.)
setcookie(name, value, expiration, path, domain, secure, httponly)
• Expiration
• Cookie expiration time in seconds
• 0 ➔ The cookie is not to be stored persistently and will be deleted when the web
client closes.
• Negative value ➔ Request the web client to delete the cookie
• e.g.: setcookie('username', 'Joe', time() + 1800); // Expire in 30 minutes
• Path
• Sets the path to which the cookie applies. (Default is ‘/’)
• Domain
• The domain that the cookie is available.
• Secure
• This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by
regular HTTP.

Prepared By Mebiratu B. 22-Feb-10 62


Session in PHP
• Session is a way to make data accessible across the various pages of an entire website
is to use a PHP Session.
• A session creates a file in a temporary directory on the server where registered session
variables and their values are stored.
• The location of the temporary file is determined by a setting in the php.ini file called
session.save_path.
• When a session is started following things happen
• PHP first creates a unique identifier for that particular session which is a random
string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
• A cookie called PHPSESSID is automatically sent to the user's computer to
store unique session identification string.
• A file is automatically created on the server in the designated temporary
directory and bears the name of the unique identifier prefixed by sess_,
sess_3c7foj34c3jj973hjkop2fc937e3443.

Prepared By Mebiratu B. 22-Feb-10 63


Starting a PHP Session
• A PHP session is easily started by making a call to the <?php
sessio
session_start() function.This function first checks if a
session is already started and if none is started then it
starts one.
• It is recommended to put the call to session_start() at the
beginning of the page.
$_SE
• The following example starts a session then register a
?>
variable called counter that is incremented each time the <htm
page is visited during the session. <
</h
<
</b

Prepared By Mebiratu B. 22-Feb-10 64


Destroying a PHP Session
Logout.php
<?php
session_destroy();
?>

• A PHP session can be destroyed by session_destroy()


function.
• This function does not need any argument and a single
call can destroy all the session variables.
Logout.php
<?php
unset(S_SESSION[‘counter’]);
?>

• If you want to destroy a single session variable then you


can use unset() function to unset a session variable.
Prepared By Mebiratu B. 22-Feb-10 65
Database

Prepared By Mebiratu B. 22-Feb-10 66


Outline
1. Connection to the Server
2. Creating a Database
3. Selecting a Database
4. Listing Database
5. Listing Table Names
6. Creating a Database Table
7. Inserting Data
8. Altering Tables
9. Deleting Databases
10. Select Queries
11. Accessing the Result
Prepared By Mebiratu B. 22-Feb-10 67
Connection to the Server
<?php
mysql_connect(server,username,password);
?>
• To connect with PHP the mysql_connect command
can be used

<?php
$connect = mysql_connect(“localhost”,”root”,””);
?>

• You may use the code fragment :

Prepared By Mebiratu B. 22-Feb-10 68


Creating a Database
SQL Query
CREATE DATABASE databasename

• To create a database, use the SQL command :


<?php
mysql_connect(“localhost”,”root”,””);
$sql = “CREATE DATABASE DemoDatabase”;
mysql_query($sql);
?>
• You may use the code fragment :

Prepared By Mebiratu B. 22-Feb-10 69


Selecting a Database
<?php
mysql_select_db(“DemoDB”) or die (“Can not Select Database”);
?>
• Before actually use a database we need to select it as
below

• The die command stops further script processing


with an error message if the database cannot be
selected.
Prepared By Mebiratu B. 22-Feb-10 70
Listing Database
SQL Query
SHOW DATABASES

• In SQL show databases will display all the current databases.

• One way to do the same in PHP is :


<?php
$result = mysql_list_dbs($connect);
for($row=0;$row<mysql_num_rows($result);$row++)
{
$dbases .= mysql_tablename($result,$row) . “<br/>”;
}
echo($dbases);
?>
• Note: mysql_tablename is generalized function for table/dastabase name
• Note: mysql_tablename is depricated function and should not be used
Prepared By Mebiratu B. 22-Feb-10 71
Listing Table Names
SQL Query
SHOW TABLES

• In SQL show tables will display all the current tables.


• One way to do the same in PHP is :
<?php
$result = mysql_list_tables($db);
for($row=0;$row<mysql_num_rows($result);$row++)
{
$tables .= mysql_tablename($result,$row) . “<br/>”;
}
echo($tables);
?>• Note: mysql_tablename is generalized function for table/dastabase name
• Note: mysql_tablename is depricated function and should not be used

Prepared By Mebiratu B. 22-Feb-10 72


Creating a Database Table
SQL Query
CREATE TABLE tablename (fileds);

• A database table is made in both the PHP and directly


with the same monitor using basically the same
command, which is
<?php
$sql = “CREATE TABLE demo (” .
“id INT NOT NULL AUTO_INCREMENT, “ .
“name VARCHAR(50) NOT NULL, “ .
“PRIMARY KEY(id))”;
mysql_query($sql);
?>
• In case of PHP the command is actually made up as a
string and then submitted using the mysql_query
command :
Prepared By Mebiratu B. 22-Feb-10 73
Inserting Data
SQL Query
INSERT INTO demo (id,name) values (NULL,’avb’)

• Data is inserted into a database table in the MySQL


monitor using insert query:
<?php
$sql = “INSERT INTO demo (id,name) values (NULL,’$name’)”;
mysql_query($sql);
?>
• In case of PHP the command is actually made up as
a string and then submitted using the mysql_query
command :

Prepared By Mebiratu B. 22-Feb-10 74


Altering Tables
SQL Query
ALTER TABLE demo modify name varchar(30);

• To alter table using database monitor we can use


following SQL query :
<?php
$sql = “ALTER TABLE demo modify name varchar(30)”;
mysql_query($sql);
?>
• In case of PHP the command is actually made up as
a string and then submitted using the mysql_query
command :

Prepared By Mebiratu B. 22-Feb-10 75


Deleting Databases
SQL Query
DROP DATABASE dbname

• To delete the database we can use following SQL


Query
<?php
$sql = “DROP DATABASE dbname”;
mysql_query($sql);
?>
• In case of PHP the command is actually made up as
a string and then submitted using the mysql_query
command :

Prepared By Mebiratu B. 22-Feb-10 76


Select Queries
SQL Query
SELECT * FROM demo where ………………….

• Once we have set up a database with information, queries can


be applided to actually find information
<?php
$sql = “select * from demo”;
$result = mysql_query($sql);
?>
• In case of PHP the command is actually made up as a string
and then submitted using the mysql_query command, it will
return an result which can then be manipulated to get desired
output:
Prepared By Mebiratu B. 22-Feb-10 77
Accessing the Result
• We have 3 methods to access the result generated from the
select query :
• $row = mysql_fetch_row($result)
Result can be accessed using numeric index starting from 0.
Ex : echo($row[1]); // in our demo table it will return name as it is in 1
index.
• $row = mysql_fetch_assoc($result)
Result can be accessed using string index where index is the column name.
Ex : echo($row[‘name’]);
• $row = mysql_fetch_array($result)
Result can be accessed using numeric as well as string index
Ex : echo($row[1]); // in our demo table it will return name as it is in 1 index
Or
Prepared By Mebiratu B. 22-Feb-10 78
Ex: echo($row[‘name’]); // both will be valid and will return same
Accessing the Result (Cont.)
<?php
$sql = “select * from demo”;
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{
echo($row[1] . “<br/>”);
}
OR
while($row = mysql_fetch_assoc($result))
{
echo($row[‘name’] . “<br/>”);
}
OR
while($row = mysql_fetch_array($result))
{
echo($row[0] . “ ”. $row[‘name’] . “<br/>”);
}
?> Prepared By Mebiratu B. 22-Feb-10 79
Thank You!!!!

Prepared By Mebiratu B. 22-Feb-10 80

You might also like