Download presentation
Presentation is loading. Please wait.
Published byBenedict Howard Modified over 9 years ago
2
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)
3
Warm up Which of this is a correct way to start a PHP code block 1. 2. <!—PHP 3. <% 4. <?PHP 5. <!PHP
4
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”]]; ?>
5
Warm up What is the output for this code ? <?php function confuse($b,$a) { $b=$a; $a=$b; return $b; } $a=1; $b=2; confuse($b,$a); $b=confuse($a,$b); echo($a+$b); ?>
6
Lesson Objectives Session 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)
7
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
8
Lists HTML supports two types of Lists: Ordered Lists (OL): e.g. 1,2,3 UnOrdered Lists (UL): e.g. bullets. Basic Syntax: Item 1 Item 2
9
Unordered list: Unordered list: Bulleted list (most popular), lists items with no particular order Fruit Banana Grape Fruit Banana Grape
10
Ordered list: Numbered list: Fruit Banana Grape Fruit 1. Banana 2.Grape
11
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. highlighted text
12
Hyperlinks: Absolute Link: These are links to another page outside of your web site. These links specify the entire URL of the page: NYU Web Site
13
Hyperlinks: Relative Link: These are links to another page in your site so you do not have to specify the entire URL. Go back to main page
14
Targeted Links A tag includes a target attribute. If you specify target= “ _blank ”, a new browser window will be opened. NYU More on this when we get to frames...
15
Email Link: You can someone at: Send email to J.J.
16
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.
17
Backgrounds Use for a background color with a hex version of a web-safe color: For a tiled background using an image file:
18
Tables tags starts with 1. tag, then 1. defines table rows. Each represents one row in the table. The number of rows is determined by the number of 2. Table data or Table Header can follow the tag The number of cells in each row is determined by the number of (Table Header) and/or (Table data) tags contained within that row. text will be in bold, and centered 2. HTML - Tables cell 1 cell 2 cell 3 cell 4 cell 5 cell 6 cell 7 cell 8 cell 9
19
Basic Tag Structure Ticker Price MSFT 71 1/16 KO 46 15/16 TR: Table Row TH: Table Heading TD: Table Data Every must have a matching. Every must have a matching.
20
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
21
Scrolling text using the tag scrolling text Welcome to my website! Be sure to visit again!
22
Images 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
Images Image Attributes src: URL or filename for the image width/height: not required border: not required. alt: recommended for users running a text browser.
24
23 What are forms? 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 elements... 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
25
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
26
25 The tag The... 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
27
26 The 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
28
27 Text input A text field: A multi-line text field Hello A password field: Note that two of these use the input tag, but one uses textarea
29
28 Buttons A submit button: A reset button: A plain button: 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”
30
29 Checkboxes A checkbox: 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
31
30 Radio buttons Radio buttons: male 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
32
31 Drop-down menu or list A menu or list: red green blue 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" )
33
32 Hidden fields <-- 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
34
33 A complete example Get Identity Who are you? Name: Gender: Male Female
35
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 the Form data is sent to this page either in URL or as a separate piece of data. XHTML Response
36
XHTML Form The form is enclosed in form tags.. <form action=“path/to/submit/page” method=“get”>
37
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.
38
Form fields: text input Use a text input within form tags for a single line freeform text input. First Name <input type="text" name="firstname" id=“fn" size="20"/>
39
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 tag. size=“…” is the length of the displayed text box (number of characters).
40
Form fields: password input Use a starred text input for passwords. Password <input type=“password" name=“passwd" id=“pw" size="20"/>
41
Form fields: text input If you need more than 1 line to enter data, use a textarea. Description <textarea name=“description” id=“desc“ rows=“10” cols=“30”> Default text goes here…
42
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 tag. rows=“…” cols=“..” is the size of the displayed text box.
43
Form fields: drop down Where do you live? Swindon <option value="london” selected="selected">London Bristol
44
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. … is the value displayed to the user. selected=“selected” this option is selected by default.
45
Form fields: radio buttons <input type="radio" name="age" id="u30“ checked=“checked” value="Under30" /> Under 30 <input type="radio" name="age" id="thirty40" value="30to40" /> 30 to 40
46
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.
47
Form fields: check boxes What colours do you like? <input type="checkbox" name="colour[]" id="r" checked="checked" value="red" /> Red <input type="checkbox" name="colour[]" id="b" value="blue" /> Blue
48
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.
49
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.
50
Submit button.. A submit button for the form can be created with the code: <input type="submit" name="submit" value="Submit" />
51
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.
52
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.
53
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”> $email = $_GET[‘email’];
54
A warning.. NEVER TRUST USER INPUT Always check what has been input. Validation can be undertaken using Regular expressions or in-built PHP functions.
55
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.
56
Example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
57
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
58
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.
59
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.
60
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 }
61
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.
62
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)......
63
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.
64
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.
65
How to Create a Cookie The setcookie() function is used to create cookies. Note: The setcookie() function must appear BEFORE the tag. setcookie(name, [value], [expire], [path], [domain], [secure]); This sets a cookie named "uname" - that expires after ten hours. …
66
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. <?php if (isset($uname)) echo "Welcome ". $uname. "! "; else echo "You are not logged in! "; ?>
67
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.
68
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.
69
How to Create a Session The session_start () function is used to create cookies. <?php session_start(); ?>
70
How to Retrieve a Session Value Register 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']++; ?>
71
How to Delete a Session Value session_unregister(´varname´); How to destroy a session: session_destroy()
72
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.
73
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);
74
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.
75
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.
76
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.
77
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 }
78
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.
79
GeshanManandhar.com PHP Strings A 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; ?>
80
GeshanManandhar.com PHP Strings Another Example <?php $beer = 'Heineken'; echo " $beer's taste is great."; // works, "'" is an invalid character for varnames echo " He drank some $beers."; // won't work, 's' is a valid character for varnames echo " He drank some ${beer}s."; // works echo " He drank some {$beer}s."; // works ?>
81
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 )
82
Lets practice Solvith PHP Course- James Song (81273798) Simple chat room
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.