Upload
benedict-howard
View
216
Download
2
Embed Size (px)
Citation preview
Programming Methodology and Web Rapid Prototyping (Session 3)
TC101 , 5 Sessions course, Conducted by Solvith
http://solvith.com/ACJC
Solvith PHP Course- James Song (81273798)
Warm up
Which of this is a correct way to start a PHP code block
1. <SCRIPT LANGUAGE="php">2. <!—PHP3. <%4. <?PHP5. <!PHP
Warm up
What is the output for this code ?
<?php$myarr=array(“b”=>2,2=>”b”);$myarrb=array(3,2,1,0);echo $myarrb[$myarr[“b”]]; ?>
Warm up What is the output for this code ?<?phpfunction confuse($b,$a){$b=$a;$a=$b;return $b;}
$a=1;$b=2;confuse($b,$a);$b=confuse($a,$b);echo($a+$b);?>
Lesson ObjectivesSession 4 [3 Aug] (Changed*)1. Consultation (20 mins)
2. HTML Basic (Part 2) (1 hour)
3. PHP AND HTML Interactivity (1 hour)4. Consultation (20 mins)5. String Functions In PHP (1 hour)6. Consultation (20 mins)
Solvith PHP Course- James Song (81273798)
Lists Lists are used to organize items in the browser
window: Unordered list: Bulleted list (most popular), list items with no
particular order Ordered list: Numbered list
Lists HTML supports two types of Lists:
Ordered Lists (OL): e.g. 1,2,3 UnOrdered Lists (UL): e.g. bullets.
Basic Syntax:<UL>
<LI>Item 1<LI>Item 2
</UL>
Unordered list: Unordered list: Bulleted list
(most popular), lists items with no particular order
Fruit <UL>
<LI> Banana
<LI>Grape</UL>
Fruit• Banana• Grape
Hyperlinks (Anchor Tag):
Hyperlinks are used for linking: within the same page (Named tags) To another page in your web site (Relative Link or local link) To another page outside your web site (Absolute or remote link) Email Link
Hyper Links: are highlighted and underlined text. When you click on it, it takes you to another page on the web.
<A command=“target”>highlighted text</A>
Hyperlinks:
Absolute Link: These are links to another page outside of your web site. These links specify the entire URL of the page:
<A HREF=“http://www.nyu.edu/”>NYU Web Site</A>
NYU Web Site
Hyperlinks:
Relative Link: These are links to another page in your site so you do not have to specify the entire URL.
<A HREF=“index.html”>Go back to main page</A>
Go back to main page
Targeted Links
A tag includes a target attribute. If you specify target=“_blank”, a new browser window will be opened.
<A HREF=“http://www.nyu.edu” target="_blank”> NYU</A>
More on this when we get to frames...
HTML Tables
Tables represent a simple mechanism for creating rows and columns of data.
This is a great tool for laying out the content of any web page, especially when you omit the border by using:
… border = “0” … Tables are very widely used and
supported by all common browsers. Tables use a very simple tag structure.
Backgrounds Use < body bgcolor = “ …” > for a
background color with a hex version of a web-safe color:
<body bgcolor = “ccffff”>
For a tiled background using an image file:
<BODY background="backgroundPicture.gif">
Tables tags starts with 1. <TABLE> tag, then
1. <TR> defines table rows. Each <TR> represents one row in the table. The number of rows is determined by the number of
<TR> 2. <TD> Table data or <TH> Table Header can follow the <TR> tag
The number of cells in each row is determined by the number of <TH> (Table Header) and/or <TD> (Table data) tags contained within that row.
<TH> text will be in bold, and centered
2. <table>
</table>
HTML - Tables
<tr> <td> cell 1 <th> cell 2 <th> cell 3 </tr>
<tr> <td> cell 4 <td> cell 5 <td> cell 6 </tr>
<tr> <td> cell 7 <td> cell 8 <td> cell 9 </tr>
Basic Tag Structure
<TABLE>
<TR >
<TH>Ticker</TH>
<TH>Price</TH>
</TR>
<TR>
<TD>MSFT</TD>
<TD>71 1/16</TD>
</TR>
<TR>
<TD>KO</TD>
<TD>46 15/16</TD>
</TR>
</TABLE>
TR: Table Row
TH: Table Heading
TD: Table Data
Every <TD> must have a matching</TD>. Every <TR> must havea matching </TR>.
<TABLE ALIGN=“left" BORDER=0 BGCOLOR=“cyan“ width=600 cellpadding=0 cellspacing=0>
Align: "left", "center" or "right“ - "left" is the default Border: thickness of the border in pixels - 0 for no borders Bgcolor: is background color in HEX or as a name color Background=url (works with IE only) Cellpading=n (n is number of pixels (space) between cell content and its
border Cellspacing=n (n is number of pixels (space) between cells) Height=n (height of table in pixels or percentages 100%) Width=n (Width of table in pixels or percentages 100%)
Table Attributes
Scrolling text using the <marquee> tag
<html><head><title> scrolling
text</title></head>
<marquee><font face=”sand">Welcome to my website! Be sure to visit again!</marquee>
</body></html>
Images
<img src= "logoblue.gif" width="153" height="31" border="0" alt="W I R E D">
Image Attributes src: URL or filename for the image width/height: not required border: not required. alt: recommended for users running a text browser.
Images
<img src= "logoblue.gif" width="153" height="31" border="0" alt="W I R E D">
Image Attributes src: URL or filename for the image width/height: not required border: not required. alt: recommended for users running a text browser.
23
What are forms? <form> is just another kind of HTML tag HTML forms are used to create (rather primitive) GUIs on
Web pages Usually the purpose is to ask the user for information The information is then sent back to the server
A form is an area that can contain form elements The syntax is: <form parameters> ...form elements... </form> Form elements include: buttons, checkboxes, text fields, radio
buttons, drop-down menus, etc Other kinds of HTML tags can be mixed in with the form elements
A form usually contains a Submit button to send the information in he form elements to the server
The form’s parameters tell JavaScript how to send the information to the server (there are two different ways it could be sent)
Forms can be used for other things, such as a GUI for simple programs
24
Forms and JavaScript The JavaScript language can be used to make
pages that “do something” You can use JavaScript to write complete programs, but... Usually you just use snippets of JavaScript here and there
throughout your Web page JavaScript code snippets can be attached to various form
elements For example, you might want to check that a zipcode field
contains a 5-digit integer before you send that information to the server
Microsoft sometimes calls JavaScript “active scripting”
HTML forms can be used without JavaScript, and JavaScript can be used without HTML forms, but they work well together
JavaScript for HTML is covered in a separate lecture
25
The <form> tag
The <form arguments> ... </form> tag encloses form elements (and probably other HTML as well)
The arguments to form tell what to do with the user input action="url" (required)
Specifies where to send the data when the Submit button is clicked
method="get" (default) Form data is sent as a URL with ?form_data info appended
to the end Can be used only if data is all ASCII and not more than 100
characters method="post"
Form data is sent in the body of the URL request Cannot be bookmarked by most browsers
target="target" Tells where to open the page sent as a result of the request target= _blank means open in a new window target= _top means use the same window
26
The <input> tag Most, but not all, form elements use the input tag,
with a type="..." argument to tell which kind of element it is type can be text, checkbox, radio, password, hidden,
submit, reset, button, file, or image Other common input tag arguments include:
name: the name of the element value: the “value” of the element; used in different ways
for different values of type readonly: the value cannot be changed disabled: the user can’t do anything with this element Other arguments are defined for the input tag but have
meaning only for certain values of type
27
Text input
A text field: <input type="text" name="textfield" value="with an initial value">
A multi-line text field <textarea name="textarea" cols="24" rows="2">Hello</textarea>
A password field: <input type="password" name="textfield3" value="secret">
• Note that two of these use the input tag, but one uses textarea
Buttons
A submit button: <input type="submit" name="Submit" value="Submit">
A reset button: <input type="reset" name="Submit2" value="Reset">
A plain button: <input type="button" name="Submit3" value="Push Me">
submit: send data
reset: restore all form elements to their initial state
button: take some action as specified by JavaScript
• Note that the type is input, not “button”
Checkboxes
A checkbox: <input type="checkbox" name="checkbox” value="checkbox" checked>
type: "checkbox" name: used to reference this form element from
JavaScript value: value to be returned when element is
checked Note that there is no text associated with the
checkbox—you have to supply text in the surrounding HTML
Radio buttons
Radio buttons:<br><input type="radio" name="radiobutton" value="myValue1">male<br><input type="radio" name="radiobutton" value="myValue2" checked>female
If two or more radio buttons have the same name, the user can only select one of them at a time This is how you make a radio button “group”
If you ask for the value of that name, you will get the value specified for the selected radio button
As with checkboxes, radio buttons do not contain any text
Drop-down menu or list
A menu or list:<select name="select"> <option value="red">red</option> <option value="green">green</option> <option value="BLUE">blue</option></select>
Additional arguments: size: the number of items visible in the list (default is
"1") multiple: if set to "true", any number of items may be
selected (default is "false")
Hidden fields
<input type="hidden" name="hiddenField" value="nyah"> <-- right there, don't you see it?
What good is this? All input fields are sent back to the server, including hidden
fields This is a way to include information that the user doesn’t
need to see (or that you don’t want her to see) The value of a hidden field can be set programmatically (by
JavaScript) before the form is submitted
33
A complete example
<html><head><title>Get Identity</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><p><b>Who are you?</b></p><form method="post" action=""> <p>Name: <input type="text" name="textfield"> </p> <p>Gender: <input type="radio" name="gender" value="m">Male <input type="radio" name="gender" value="f">Female</p> </form></body></html>
How forms work
Web Server
User
User requests a particular URL
XHTML Page supplied with Form
User fills in form and submits. Another URL is requested and theForm data is sent to this page either inURL or as a separate piece of data.
XHTML Response
XHTML Form The form is enclosed in form tags..
<form action=“path/to/submit/page”
method=“get”>
<!–- form contents -->
</form>
Form tags action=“…” is the page that the form should
submit its data to. method=“…” is the method by which the form
data is submitted. The option are either get or post. If the method is get the data is passed in the url string, if the method is post it is passed as a separate file.
Form fields: text input Use a text input within form tags for a single
line freeform text input.
<label for=“fn">First Name</label><input type="text" name="firstname" id=“fn" size="20"/>
Form tags name=“…” is the name of the field. You will use
this name in PHP to access the data. id=“…” is label reference string – this should
be the same as that referenced in the <label> tag.
size=“…” is the length of the displayed text box (number of characters).
Form fields: password input Use a starred text input for passwords.
<label for=“pw">Password</label><input type=“password" name=“passwd" id=“pw" size="20"/>
Form fields: text input If you need more than 1 line to enter data, use
a textarea.
<label for="desc">Description</label><textarea name=“description” id=“desc“ rows=“10” cols=“30”>Default text goes here…</textarea>
Form fields: text area name=“…” is the name of the field. You will use
this name in PHP to access the data. id=“…” is label reference string – this should
be the same as that referenced in the <label> tag.
rows=“…” cols=“..” is the size of the displayed text box.
Form fields: drop down
<label for="tn">Where do you live?</label>
<select name="town" id="tn">
<option value="swindon">Swindon</option>
<option value="london”
selected="selected">London</option>
<option value=“bristol">Bristol</option>
</select>
Form fields: drop down name=“…” is the name of the field. id=“…” is label reference string. <option value=“…” is the actual data sent
back to PHP if the option is selected. <option>…</option> is the value displayed
to the user. selected=“selected” this option is selected
by default.
Form fields: radio buttons
<input type="radio" name="age"
id="u30“checked=“checked”value="Under30" />
<label for="u30">Under 30</label><br /><input type="radio"
name="age"id="thirty40"value="30to40" />
<label for="thirty40">30 to 40</label>
Form fields: radio buttons name=“…” is the name of the field. All radio
boxes with the same name are grouped with only one selectable at a time.
id=“…” is label reference string. value=“…” is the actual data sent back to PHP
if the option is selected. checked=“checked” this option is selected by
default.
Form fields: check boxes
What colours do you like?<br /><input type="checkbox"
name="colour[]"id="r"checked="checked"value="red" />
<label for="r">Red</label><br /><input type="checkbox"
name="colour[]" id="b"
value="blue" /><label for="b">Blue</label>
Form fields: check boxes name=“…” is the name of the field. Multiple
checkboxes can be selected, so if the button are given the same name, they will overwrite previous values. The exception is if the name is given with square brackets – an array is returned to PHP.
id=“…” is label reference string. value=“…” is the actual data sent back to
PHP if the option is selected. checked=“checked” this option is selected
by default.
Hidden Fields<input type="hidden"
name="hidden_value"
value="My Hidden Value" />
name=“…” is the name of the field. value=“…” is the actual data sent back to
PHP.
Submit button.. A submit button for the form can be created
with the code:
<input type="submit"
name="submit"
value="Submit" />
Fieldset In XHTML 1.0, all inputs must be grouped within the form
into fieldsets. These represent logical divisions through larger forms. For short forms, all inputs are contained in a single fieldset.
<form><fieldset><input … /><input … /></fieldset><fieldset><input … /><input … /></fieldset></form>
In PHP… The form variables are available to PHP in the
page to which they have been submitted. The variables are available in two superglobal
arrays created by PHP called $_POST and $_GET.
Access data Access submitted data in the relevant
array for the submission type, using the input name as a key.
<form action=“path/to/submit/page”
method=“get”><input type=“text” name=“email”></form>
$email = $_GET[‘email’];
A warning..
NEVER TRUST USER INPUT
Always check what has been input. Validation can be undertaken using Regular
expressions or in-built PHP functions.
A useful tip.. I find that storing the validated data in a
different array to the original useful. I often name this array ‘clean’ or something
similarly intuitive. I then *only* work with the data in $clean, and
never refer to $_POST/$_GET again.
Example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean = array();
Initialise an array to store filtered data.
Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
if (ctype_alnum($_POST['username']))
Inspect username to make sure that it is alphanumeric.
Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean['username'] = $_POST['username'];
If it is, store it in the array.
Is it submitted? We also need to check before accessing data
to see if the data is submitted, use isset() function.
if (isset($_POST[‘username’])) {
// perform validation
}
Server Side Includes
You can insert the content of one file into another file before the server executes it, with the require() function. The require() function is used to create functions, headers, footers, or elements that will be reused on multiple pages.
<?php require("header.htm"); ?>
How to create variables storing values across php scripts’ calls?
Client-server connection is not permanent=> Cannot be saved in program memory
There are many clients connecting simultaneously => Cannot be saved in file (you cannot identify clients as well sometimes)
.
.
.
Different mechanisms of the same solution Cookies
Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.
Sessions Session support in PHP consists of a way to
preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.
What is a Cookie? A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for 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
The setcookie() function is used to create cookies.
Note: The setcookie() function must appear BEFORE the <html> tag.
setcookie(name, [value], [expire], [path],
[domain], [secure]);
This sets a cookie named "uname" - that expires after ten hours.
<?php setcookie("uname", $name, time()+36000); ?>
<html> <body> …
How to Retrieve a Cookie Value To access a cookie you just refer to the cookie
name as a variable or use $_COOKIE array Tip: Use the isset() function to find out if a
cookie has been set.
<html> <body><?php
if (isset($uname)) echo "Welcome " . $uname . "!<br />";
else echo "You are not logged in!<br />"; ?>
</body> </html>
How to Delete a Cookie It will expire
or Cookies must be deleted with the same
parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.
What is a Session? The session support allows you to register
arbitrary numbers of variables to be preserved across requests.
A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.
How to Create a SessionThe session_start() function is used to create
cookies.
<?php
session_start();
?>
How to Retrieve a Session ValueRegister Session variable
session_register('var1','var2',...); // will also create a session PS:Session variable will be created on using even if you will not register it!
Use it<?php session_start();
if (!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else $_SESSION['count']++;
?>
How to Delete a Session Value session_unregister(´varname´);
How to destroy a session: session_destroy()
Using Cookies Cookies are small pieces of data that a server
sends to a browser for storage. When a browser contacts a server, it sends along any cookies for that server under the variable $_COOKIES. Similarly, a server can set one or more cookies on the browser for retrieval at a later time.
The first part of program session-cookies.php illustrates the typical use of cookies, with these lines:
$today = date('l, F j, Y'); $timestamp = date('g:i A'); if (strcmp($_COOKIE[LAST_VISIT], "") == 0) { $lasttime = ""; } else { $lasttime = $_COOKIE[LAST_VISIT]; } $LAST_VISIT = $today . " at " . $timestamp; // set last_visit cookie with date/time, with expiration for 2 full weeks setcookie ("LAST_VISIT", $LAST_VISIT, time() + 3600*24*14); if ($_COOKIE[VISIT_NUMBER] == 0) { $visitcount = 0; } else { $visitcount = $_COOKIE[VISIT_NUMBER]; } // set visit_number cookie with count, with expiration for 2 full weeks setcookie ("VISIT_NUMBER",1 + $visitcount, time() + 3600*24*14);
additional notes: Here are a few additional notes: Cookies are sent with Web page headers, so
any setting of cookies must take place BEFORE the DOCTYPE line in an HTML/PHP script.
PHP function setcookie specifies a cookie ID, a value, and a length of time for which the cookie will be kept by the browser.
PHP variable $_COOKIE is an associative array that maintains the list of cookies set previously.
Check if your browser is usually set to accept cookies.
If you use the Mozilla browser, this information can be found by looking under "Preferences" in the "Edit" menu, and then going to "Privacy & Security" and "Cookies".
If you use the Iceweasel browser, this information can be found by looking under "Preferences" in the "Edit" menu, and then going to the "Privacy" tab.
If you use Internet Explorer under Windows, this information can be found by looking under select "Internet Options" from the "Tools" menu, then look under "General" and "Settings" in the "Temporary Internet Files" section.
If you use Internet Explorer on a Macintosh, this information can be found by looking under "Preferences" under the "Explorer" menu, and then looking under "Cookies" in the "Receiving Files" section.
Session Variables Effectively, session variables are cookies that
remain active only while the browser is actively interacting with the server. When time elapses, or when you close your browser, the session variables disappear. (If cookies are not allowed by a user, then information for sessions may be placed in a query string at the end of a URL.)
The following lines from session-cookies-2.php illustrate typically processing of session variables.
The following lines illustrate typically processing of session variables.
// check if person has logged in previously
session_start(); $processingOK = "not yet"; $firstLogin = "no"; if (isset ($_SESSION['authorized'])) { // user already logged in $processingOK = $_SESSION['authorized']; } else { // user not logged in, so check password $password = trim($_POST['password']); if ($password == 'Test') { // correct password given $processingOK = 'ok'; $_SESSION['authorized'] = 'ok'; $firstLogin="yes"; } else { // invalid password } }
Here are some notes regarding session variables:
A script uses session_start() to initialize and register any session variables.
As with cookies, session variables are sent with Web page headers, so any setting of session information must take place before the DOCTYPE tag.
PHP variable $_SESSION is an associative array that maintains the list of session variables set previously.
PHP function isset determines whether a specific $_SESSION field has a designated value.
PHP function unset removes a session value that was sent previously, and session_unset() removes all session values.
GeshanManandhar.com
PHP StringsA string is series of characters. In PHP, a character is the same as a byte, which is exactly 256 different characters possible.
<?php$s=“I am a string”;$s2=‘I am also a string”;print $s.”---”.$s2;?>
GeshanManandhar.com
PHP StringsAnother Example
<?php
$beer = 'Heineken';echo "<br>$beer's taste is great."; // works, "'" is an invalid character for varnamesecho "<br>He drank some $beers."; // won't work, 's' is a valid character for varnames
echo "<br>He drank some ${beer}s."; // worksecho "<br>He drank some {$beer}s."; // works?>
GeshanManandhar.com
Important String Functions• explode (string $delimiter, string $string)• nl2br ( string $string )• strcmp ( string $str1, string $str2 )• strlen ( string $string )• strtolower ( string $str )• substr ( string $string, int $start [, int
$length] )• trim ( string $str )