Upload
gervase-higgins
View
221
Download
0
Embed Size (px)
Citation preview
Mohammad Al-Samarah
Chapter - 4
Web Programming
Outline• Overview about Web Page
• HTML Form Creation
• FORM
• Input
• INPUT control types
• GET & POST
• PHP File Upload
• PHP Include Files
• Headers
• Cookie
• Sessions
Overview about Web Page• Most people think of a web page as nothing more than a
collection of HTML code . This is fine if you happen to be a web
designer .
• But as a PHP developer we talk about web server that generation
of a document starts with an HTTP request ,in which the client
requests access to a resource using on method from short list
methods.
• The client can also send data payload (called request),once
request is received , the sever decoded the data that it has
received and passes it on to the PHP interpreter.
Overview about Web Page
• A web application receives input from the
user via form input
• Handling form input is the cornerstone of a
successful web application – everything
else builds on it
Overview about Web Page
• The browser interprets the HTML source for a
particular page
– Result is a combination of text, images, and
entry fields
– Each entry field has a specific name
• User fills in these fields, (with potentially some
client-side input checking via JavaScript) and then
selects a submission button
Overview about Web Page
• The browser reads the input fields, and
creates a message that is sent to the
server
– A series of name, value pairs
HTML Form Creation• FORM
– Encloses all input fields
– Defines where and how to submit the form data
• INPUT
– Defines a specific input field
• TEXTAREA
– Creates a free-form text fill-in box
• SELECT
– Creates a menu
– OPTION defines options within the menu
FORM• FORM attributes
– action
• URL of the resource that receives the filled-in form
• This is the URL of your PHP code that receives the input
– method
• Choices are “get” or “post” – you should choose “post”
– enctype
• MIME type used to send results. By default is application/xww-
form-urlencoded
• Would use multipart/form-data if submitting a file
(INPUT,type=file)<FORM action=“MyHandler.php” method=“post”>
INPUT• INPUT attributes
– type: the kind of user input control
– name: the name of the control
• This gets passed through to the handling code
• In PHP: $_POST[‘name’]
– value: initial value of the control
– size: initial width of the control
• in pixels, except for text and password controls
INPUT
– maxlength: for text/password, maximum number of
characters allowed
– checked: for radio/checkbox, specifies that button is on
– src: for image types, specifies location of image used to
decorate input button
INPUT Control Types
• text: single input line
• password: single input line, with input
characters obfuscated
• checkbox: creates a check list
• radio: creates a radio button list (checkbox,
where inputs are mutually exclusive – only one
input at a time)
• button: push button
• hidden: a hidden control. No input field is
visible, but value is submitted as part of the form
INPUT Control Types
• Special buttons
– submit: the submit button. Causes input to be sent to the server
for processing
– reset: the reset button. Causes all input fields to be reset to their
initial values
• File upload
– file: creates a file upload control
Example<FORM action=“mypage.php" method="post">
First name: <INPUT type="text“ name="firstname"><BR>
Last name: <INPUT type="text“ name="lastname"><BR>
email: <INPUT type="text“ name="email"><BR>
<INPUT type="radio" name="sex“ value="Male"> Male<BR>
<INPUT type="radio" name="sex“ value="Female">
Female<BR>
<INPUT type="submit" value="Send">
<INPUT type="reset">
</FORM>
Example
Receiving form input in PHP
• Upon receiving a form submission, PHP
automatically creates and populates two arrays
with the form input data
– Either : _POST[] or _GET[], depending on the
FORM method type (post or get)
– Additionally, _REQUEST[] is also created
• The array indicies are the names of the form
variables (INPUT name=…)
• The array value is the user entry data
Receiving form input in PHP
• The two method allows you to send data
as part of the query string , The
predefined variable is used to collect
values in a form ( $_GET , $_POST ).
GET
• Information sent from a form with the GET method is visible
to everyone (it will be displayed in the browser's address
bar) and has limits on the amount of information to send.
http://localhost/send.php?Var1=value1&Var2=value2&Var3=value3
GET - Example <html><body>
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body></html>
<?php
echo “Welcome”. $_GET["fname"] .” <br />”;
echo “You are “.$_GET["age"].” years old!”;
?>.
welcome.php
GET - Example
<html> <body>
<h4> Order Form</h4>
<form action="process.php" method=“get"> <select
name="item"> <option>Paint</option>
<option>Brushes</option> <option>Erasers</option>
</select> Quantity: <input name="quantity"
type="text" /> <input type="submit" />
</form>
</body></html>
GET - Example
<html><body>
<?php
$quantity = $_GET['quantity'];
$item = $_GET['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?>
</body></html>
process.php
GET - Example
POST
• Information sent from a form with the POST method is
invisible to others and has no limits on the amount of
information to send.http://www.example.com/send.php
POST - Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
<?php
echo “Welcome”. $_POST["fname"] .” <br />”;
echo “You are “.$_POST["age"].” years old!”;
?>.
welcome.php
POST - Example
REQUEST
• The predefined $_REQUEST variable contains the contents
of both $_GET, $_POST, and $_COOKIE.
• The $_REQUEST variable can be used to collect form data
sent with both the GET and POST methods.
http://www.example.com/send.php
http://localhost/send.php?Var1=value1&Var2=value2&Var3=value3
REQUEST - Example
<?php
echo “Welcome”. $_REQUEST["fname"] .” <br
/>”;
echo “You are “. $_REQUEST["age"].” years
old!”;
?>.
welcome.php
Array Notation
• We can create arrays by using array notation..
<?php
forech($_GET[‘arra’] as $x)
{
echo $x
}
?>
http://localhost/send.php?user=data&arra[]=data1&arra1[]=data2
Array Notation
• We can create arrays by using array notation..
<?php
echo $_GET[‘arra’][‘x’];
echo $_GET[‘arra’][‘s’];
?>
http://www.example.com/send.php?user=data&arra[‘x’]=data1&arra[‘s’]=datax
PHP File Upload
• To allow users to upload a file to the server, you first need
to provide a form for them to specify which file they want to
upload. Once they click the submit button of the form, the
action page is called. This is the page that needs to contain
the PHP code to process the uploaded file.
PHP File Upload• Before a user can upload a file, you need to provide them with an
interface that allows them to select a file and initiate the upload.
• The following code is an example of an input form. There are a
couple of important things to note about this code:
• The action attribute points to a .php file. This is the file that will
process the uploaded file.
• There is an attribute called enctype, and its value is
multipart/form-data.
• One of the input fields has type="file".
PHP File Upload
<html> <head> <title>PHP File Upload Example</title>
</head><body>
<form enctype="multipart/form-data" method="post"
action="uploadFile.php">
<input type="file" name="fileToUpload" /><br />
<input type="submit" value="Upload File" />
</form>
</body> </html>
The Action Page
• Once the user uploads a file, the file is uploaded into a
temporary directory on the server. If you don't move the file it
will disappear. Therefore, your action page needs to move the
file to another location where it can stay as long as you want it
to.
• Whenever a file is uploaded, you can find out certain
information about the file including its name, type, size, as well
as the name of the temporary file on the server. These details
are made available to you via a PHP array called $_FILES.
Displaying Details of the Uploaded File
• This code simply displays the details of the uploaded file. It
doesn't move the file to another location - we'll get to that next.
For now, you can use this code in conjunction with the above
input form to demonstrate what happens when you upload a
file to the server.
• Notice the PHP $_FILES array which contains info about the file.
Note that we also divide the file size by 1024 in order to
convert it into kb.
-(Ignore any carriage returns in this example - each table
row should be on one line).
Displaying Details of the Uploaded File
<?php
echo "<table border=\"1\">";
echo "<tr><td>Client Filename: </td>
<td>" . $_FILES["fileToUpload"]["name"] . "</td></tr>";
echo "<tr><td>File Type: </td>
<td>" . $_FILES["fileToUpload"]["type"] . "</td></tr>";
echo "<tr><td>File Size: </td>
<td>" . ($_FILES["fileToUpload"]["size"] / 1024) . " Kb</td></tr>";
echo "<tr><td>Name of Temp File: </td>
<td>" . $_FILES["fileToUpload"]["tmp_name"] . "</td></tr>";
echo "</table>";
?>
Displaying Details of the Uploaded File
• The above code results in something like this:
Client Filename: Water lilies.jpg
File Type: image/jpeg
File Size: 81.830078125 Kb
Name of Temp File: C:\WINDOWS\TEMP\php48B2.tmp
Moving the Temp File
• As mentioned, if we want to keep the file on the server,
we need to move it to another location (of our choice).
The following code demonstrates how to move the file
from the temporary location.
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "C:/upload/" . $_FILES["fileToUpload"]["name"]);
Checking for Errors
• The $_FILES array includes an item for any errors that
may result from the upload. This contains an error code.
If there are no errors, the value is zero ( 0 ).
• You check this value within an "If" statement. If the value
is greater than zero, you know an error has occurred and
you can present a user friendly message to the user.
Otherwise you can processing the file.
Checking for Errors<?php
if ($_FILES["fileToUpload"]["error"] > 0)
{
echo "Apologies, an error has occurred.";
echo "Error Code: " . $_FILES["fileToUpload"]["error"];
}
else
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"C:/upload/" . $_FILES["fileToUpload"]["name"]);
}
?>
Restricting File Type/Size
• Letting your users upload files to your server can be very risky.
If you're not careful, you could get users uploading all sorts of
files - perhaps including harmful executables etc. You could also
find one day that you've run out of disk space because some
users have been uploading enormous files.
• You can restrict the file types and file sizes by using an "if"
statement. If the file type and size are acceptable, processing
can continue, otherwise, display a message to the user.
Restricting File Type/Size
• Important Note: This doesn't prevent the temp file from being
created. The file needs uploaded to the server before PHP can
find out the file size and type. This simply prevents the file from
being moved to your "permanent" location - hence the file
should disappear and (hopefully) not become a problem. In any
case, I recommend that you install good anti-virus software
before allowing users to upload files to your server.
Restricting File Type/Size<?php
if (($_FILES["fileToUpload"]["type"] == "image/gif")
|| ($_FILES["fileToUpload"]["type"] == "image/jpeg")
|| ($_FILES["fileToUpload"]["type"] == "image/png" )
&& ($_FILES["fileToUpload"]["size"] < 10000))
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "C:/upload/" .
$_FILES["fileToUpload"]["name"]);
}
else
{
echo "Files must be either JPEG, GIF, or PNG and less than 10,000 kb";
}
?>
PHP Include Files
• In PHP, you can insert the content of one PHP file into
another PHP file before the server executes it.
• The include and require statements are used to insert
useful codes written in other files, in the flow of execution.
• Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR)
and stop the script
include will only produce a warning (E_WARNING) and
the script will continue
PHP Include Files
• Including files saves a lot of work. This means that you can
create a standard header, footer, or menu file for all your
web pages. Then, when the header needs to be updated,
you can only update the header include file.include 'filename';
or
require 'filename';
PHP Include Files
<html>
<body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
PHP Include Files
• Assume we have a standard menu file that should be used
on all pages. "menu.php":
<?phpecho '<a href="/default.php">Home</a><a href="/tutorials.php">Tutorials</a><a href="/references.php">References</a><a href="/examples.php">Examples</a> <a href="/about.php">About Us</a> <a href="/contact.php">Contact Us</a>';?>
PHP Include Files
• All pages in the Web site should include this menu file. Here is how
it can be done:<html><body>
<div class="leftmenu"><?php include 'menu.php'; ?></div>
<h1>Welcome to my home page.</h1><p>Some text.</p>
</body></html>
Header
• The header() function sends a raw HTTP
header to a client.
• It is important to notice that header() must
be called before any actual output is sent
(In PHP 4 and later, you can use output
buffering to solve this problem):
Header
• The header() function sends a raw HTTP
header to a client.
• It is important to notice that header() must
be called before any actual output is sent
(In PHP 4 and later, you can use output
buffering to solve this problem):
Header
header(string,replace,http_response_code)
Parameter Description
string Required. Specifies the header string to send
replace Optional. Indicates whether the header should replace previous or add a second header. Default is TRUE (will replace). FALSE (allows multiple headers of the same type)
http_response_code
Optional. Forces the HTTP response code to the specified value (available in PHP 4.3 and higher)
Header
<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
//this is redirect to this website.
?>
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.
How to Create a Cookie?
How to Create a Cookie?
• The setcookie() function is used to set a cookie.
• Note: The setcookie() function must appear
BEFORE the <html> tag.
setcookie(name, value, expire, path, domain);
How to Create a Cookie?
• We will create a cookie named "user" and assign
the value "Ali" to it. We also specify that the
cookie should expire after one hour:
<?php
setcookie("user", "Ali", time()+3600);
?>
Cookie
• Note: The value of the cookie is
automatically URLencoded when sending
the cookie, and automatically decoded
when received (to prevent URLencoding,
use setrawcookie() instead).
How to Create a Cookie?
• You can also set the expiration time of the cookie
in another way. It may be easier than using
seconds.<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
How to Retrieve a Cookie Value?
• The PHP $_COOKIE variable is used to retrieve a cookie
value.
In the example below, we retrieve the value of the cookie
named "user" and display it on a page:<?php
echo $_COOKIE["user"]; // Print a cookie
print_r($_COOKIE); // A way to view all cookies
?>
How to Delete a Cookie?
• When deleting a cookie you should assure that the
expiration date is in the past.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
Session
• 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.
• Before you can store user information in your PHP
session, you must first start up the session.
Starting a PHP Session
• <?php session_start(); ?>
• The code above will register the user's session
with the server, allow you to start saving user
information.
• The correct way to store and retrieve session
variables is to use the PHP $_SESSION variable:
Storing a Session Variable
<?php
session_start();
// store session data
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];
?>
Destroying a Session
• if you wish to delete some session data,
you can use the unset() or the
session_destroy() function.
• The unset() function is used to free the
specified session variable:
Session
<?php
unset($_SESSION['views']); // delete single
session
?>
Or
<?php
session_destroy(); // delete all sessions
?>