Hyper Text Markup Language HTML BASICS - PowerPoint PPT Presentation

1 / 72
About This Presentation
Title:

Hyper Text Markup Language HTML BASICS

Description:

where the tag indicates the beginning of a tag-pair, and the /tag is the end ... Line Breaks br Ending /br is not required. Lists ... – PowerPoint PPT presentation

Number of Views:580
Avg rating:3.0/5.0
Slides: 73
Provided by: people8
Category:

less

Transcript and Presenter's Notes

Title: Hyper Text Markup Language HTML BASICS


1
Hyper Text Markup Language (HTML) BASICS
2
HTML TAGS
  • HTML is composed of tags. The tags are always
    enclosed in angle-brackets ( lt gt )
  • Tags typically occur in begin-end pairs.
  • lttaggt ... lt/taggt
  • where the lttaggt indicates the beginning of a
    tag-pair, and the lt/taggt is the end tag
    (slash-tag).Multiple tags may appear on the same
    line and some tags may embody (contain) other
    tags.

3
Document Tags
  • HTML ltHTMLgt lt/HTML
  • HTML documents start with ltHTMLgt and end with
    lt/HTMLgt
  • HEAD ltHEADgt lt/HEADgt
  • Contains header information for the document such
    as title, script, and meta-tags.
  • TITLE ltTITLEgt lt/TITLEgt
  • Contains the text that displays in the title bar
    of the document when viewed by the browser.
    Normally the default value for bookmarks of the
    html document.

4
Document Tags Continued.
  • BODY ltBODYgt lt/BODYgt
  • Contains what is to be displayed by the browser.
  • Comment Tags lt!-- --gt
  • For commenting your document. Will not be
    displayed by the browser. Shouldnt incase other
    tags. If other tags are encased here, very likely
    they will be interpreted as comment. This
    reaction may vary by browser type.

5
Sample HTML scripts
  • Sample1.html
  • lt!-- My first html script. Does nothing - just a
    blank screen is displayed. --gt
  • lthtmlgt
  • lt/htmlgt

6
Sample2.htmllt!-- Does nothing - just a blank
screen is displayed. --gtlthtmlgtltheadgtlttitlegtlt/t
itlegtlt/headgtltbodygtlt/bodygtlt/htmlgt
7
Sample3.htmllt!-- Does something
--gtlthtmlgtltheadgtlttitlegtCOSC 681, eCommerce and
Web Databaselt/titlegtlt/headgtltbodygtThis is a
sample web page.lt/bodygtlt/htmlgt
8
Text outlay
  • Headers ltHngt .. lt/Hngt 1 ? n ? 6
  • Hi is more significant than Hi1 1?ilt6
  • Paragraphs ltPgt .. lt/Pgt
  • For segmenting the document into paragraphs. The
    effect is some vertical spacing between the
    information above and what follows.
  • Line Breaks ltbrgt Ending lt/brgt is not required

9
Lists
  • Unordered lists ltULgt (ltLIgt list-item) lt/ULgt e.g.
  • ltULgt
  • ltLIgtapple
  • ltLIgtorange
  • lt/ULgt
  • Displays
  • apple
  • orange

10
Listscontinued
  • Ordered lists ltOLgt (ltLIgt list-item) lt/OLgt e.g.
  • ltOLgt
  • ltLIgtapple
  • ltOLgt ltLIgt green ltLIgt red lt/OLgt
  • ltLIgtorange
  • lt/OLgt
  • Displays
  • 1. apple
  • i. green
  • ii. red
  • 2. orange

11
Lists Continued.
  • List styles may be indicated like the following
    example
  • ltol stylelist-style-type decimalgt
  • This indicates a decimal (1,2,) numbering
    sequence for the list items. Other styles are
    upper-alpha, lower-alpha, upper-roman and
    lower-roman.

12
Anchors ltA gtlt/Agtlinks from a document to
another part of the document or to an outside
document
  • Hypertext Reference anchor (HREF)
  • ltA hrefhttp//db1.acad.emich.edugt eCommerce
    lt/Agt
  • NAME anchor
  • ltA nameReqgt Requirements lt/Agt
  • tags this point in the document as Req
  • http//db1.acad.emich.edu/eCommerce.htmlReq
  • Goes to the Req point in eCommerce.html

13
Tables by Examples lttable border1gt lttrgt lttdgt
Row 1, col 1lt/tdgt lttdgt Row 1, col
2lt/tdgt lt/trgt lttrgt lttdgt Row 2, col 1
lt/tdgt lt/trgt lt/tablegt lttable border2gt ltcaptiongt
Grade Sheet lt/captiongt lttr aligncentergt ltthgtlt/
thgtltthgtNamelt/thgtltthgtScore1lt/thgtltthgtScore2lt/thgt lt/t
rgt lttr aligncentergt ltthgt1lt/thgtlttdgtJohn
Doelt/tdgtlttdgt95lt/tdgtlttdgt88lt/tdgt lt/trgt lttr
aligncentergt ltthgt2lt/thgtlttdgtJim
Doelt/tdgtlttdgt80lt/tdgtlttdgt97lt/tdgt lt/trgt lttrgt lttd
colspan3gt Occupy 3 columns lt/tdgt lttdgt row 3,
col 4 lt/tdgt lt/trgt lt/tablegt Javascript was
introduced by Netscape. Javascript 1.0 was part
of Navigator 2.0. Currently there is version 1.2
which is supported by Netscape 4.0 and
supposedly supported by MSIE 4.0. There are
minor differences in the behavior across
different browsers.
14
What you should know for 681 relating to
HTML. For the 681 (e-commerce), you are
responsible for basic html tags like the ones for
controlling fonts type, size and color images
including scaling paragraphs background
images color forms and widget (input) types
e.g. Text, textarea, file, button and submit
lists ordered and unordered anchors href and
named tables - including tr, td, th, colspan and
rowspan attributes frames including two
dimensional frames. Visit http//www.w3schools.co
m for some basic tutorials on these features.
15
Javascript Basics Background Javascript was
introduced by Netscape. Javascript 1.0 was part
of Navigator 2.0. Currently there is version 1.2
which is supported by Netscape 4.0 and
supposedly supported by MSIE 4.0. There are
minor differences in the behavior across
different browsers.
16
What is Javascript It provides programming
capabilities at both server and client ends of a
web connection. It can perform most of the
tasks a CGI program does. It is not as capable as
Java applets when it comes to generating and
manipulating graphical objects. It is an easier
language to learn in comparison to Java.
Nowadays, the primary purpose is the verification
of form-data on the clients side.
17
Programming in Javascript Code is typically
embedded into an HTML document using the SCRIPT
tag. Script tags may appear in the HEAD or BODY
tags. Multiple Script tags are allowed.
Normally, javascript functions are placed in the
HEAD tag and the BODY tag may contain javascript
statements referencing the functions in the HEAD
tag. ltscript language"JavaScript
srctest.jsgt lt!-- ... //--gt lt/scriptgt
18
Language specifies the version the code is
written in. Src may be a text file containing
javascript code. The src... is omitted if the
script is written within the script
tags. lt!-- //--gt is used to surround javascript
code for non-javascript aware browsers. With
this, non-javascript aware browsers will just
treat the code as comment and ignore it.
19
Variables Variables do not need to be declared
before use. To declare a variable, we may use var
x, y, z A variable is not fixed to any data type
and type conversion is done whenever unambiguous.
For example, we may use x 1 y 2 zxy z
xy is ambiguous and will give an error.
Variable names are case-sensitive. Scope
Declared variables are recognized during the
script load time. Undeclared variables are not
recognized until the first time a value is
assigned to it. Statements outside a function are
executed at script load time in the order of
occurrence. Variables declared inside a function
are local. All others are global.
20
Example function t1 () alert(x)
alert(y) // will give 1 and 2 although x and y
are after t1. z4 var x1 y2 function
t2()alert(x) alert(z) // z is
undefined t1() t2()
21
Operators Most of the operators available in
java are also available in javascript. Examples
x x y x y 2 if ((a lt b) (c lt d)
if (a b) checks for strictly equal i.e.
same type, same value. if (1 1 ) is true if
(1 1) is false, if (1 1) is true.
javascript statements are very similar to
statements in java. Semicolon is not required at
the end of every statement unless you have
multiple statements on one line, then they must
be separated by semicolon. Looping statements are
basically the same too.
22
Communicating with functions Arguments are
passed by value. To get call by reference, you
may send an object. For example function t1
(x, y) x 1 y2 function t2(x) x0
3 function t3 () a 10 b20 t1 (a, b)
// a, b will remain unchanged. L0 30
t2(L) // L0 is changed to 3
23
Basic String methods Example str
hello str.length is 5, str.charAt(0) is h,
str.indexOf(ell) is 1, str.substring(2,3) is
ll I/O - alert(str), xprompt(what,
default-value), yconfirm(are you sure?)
Confirm returns true for ok and false for cancel.
24
Statements and Control Structures if, switch,
for, while, do-while, comments (//, /) are
available in javascript. The syntax is the same
as in Java. With statement Similar to Pascals
with statement but used with objects in
javascript. For example, with (window.document.log
inform) alert(username)
alert(password)
25
Javascripts Document Object Model (DOM) An
object is a "package" of data a collection of
properties (variables) and methods (functions)
all classed under a single name In C or Java,
objects are usually represented with
classes. DOM is a hierarchy of all objects
"built in" to JavaScript. Most of these objects
are directly related to characteristics of the
Web page or browser. There are some differences
between Javascripts DOM in Netscape and
Explorer.
26
Javascripts Window DOM in Netscape (Explorer is
a superset of this) Window - frame, document,
location, history document - layer, link, image,
area, anchor, applet, plugin, form form -
textarea, text, password, hidden, submit,
reset, radio, checkbox, button, select select
- option note that objects can contain other
objects e.g. window contains the document object.
Also objects have methods. E.g window.close(),
document.write(abc)
27
Javascripts Events and Event handling Javascrip
t programs are typically event-driven. Events are
actions that occur on the web-page usually as a
result of something the client does e.g. clicking
on a link, closing a window, etc. An event
handler (or the execution of javascript code) may
be associated to any event. For example, ltbody
onLoadalert(welcome)gt lta hrefabc.html
onClickverifyFunction()gt abc.com
lt/agt lt/bodygt
28
Common Events Event Caused by Event Handler
click clicks on form element or
link onClick change changes to value of text,
textarea, or select element onChange focus Fo
rm element gets input focus onFocus blur Form
element looses focus onBlur mouseover mouse
pointer over a link or anchor onMouseOver
mouseout mouse pointer off of link or
anchor onMouseOut select form element's input
field onSelect submit User submits a
form onSubmit resize User resizes the browser
window onResize load User loads the page in the
Navigator onLoad
29
(No Transcript)
30
  • Meta tags provide a useful way to control your
    summary in some search engines.  

31
  • Meta tags can also help you provide keywords and
    descriptions on pages that for various reasons
    lack text. Examples are splash pages and frames
    pages. They might also boost your page's
    relevancy. However, simply including a meta tag
    is not a guarantee that your page should suddenly
    leap to the top of every search engine listing.
    They are a useful tool but, as said above, not a
    magic solution.
  • Two Important Meta Tags Keywords and Description
  • There are several meta tags, but the most
    important one for search engine indexing are the
    description and keywords tags. The description
    tag gives a summary of the page. The keywords tag
    provides keywords for the search engine to
    associate with your page.

32
  • One other meta tag worth mentioning is the robots
    tag. This lets you specify that a particular page
    should NOT be indexed by a search engine. To keep
    spiders out, simply add this text between your
    header tags on each page you don't want indexed.
  • You do NOT need to use variations of the meta
    robots tag to help your pages get indexed. They
    are unnecessary.
  • Be aware that not all search engines support the
    meta robots tag.

33
  • In Conclusion
  • Definitely add meta description and meta keyword
    tags to your web pages. Some search engines will
    give you a boost if you have them. But don't
    expect that to necessarily be enough to put you
    in the top ten. Meta tags are mainly a design
    element you can tap into, a crutch for helping
    information-poor pages better be acknowledged by
    the search engines.

34
  • PHP
  • Rescursive acronym for "PHP Hypertext
    Preprocessor".
  • It is an open source scripting language that can
    be embedded into HTML. Php Code is embedded
    inside HTML code, unlike other scripting
    languages like Perl or C which produce WHOLE html
    codes, PHP code is embeded anywhere inside and
    HTML code.
  • JavaScript is client-side processed while PHP is
    processed on the server side.
  • When an HTML code with embedded PHP is shown to a
    client, all the client can see is the final HTML
    version. They have no way of knowing that some of
    that code came from PHP.

35
PHP START AND OPEN TAGS lt? echo 'a' echo
'b' echo 'c' ?gt lt echo 'ASP -style
tags' echo "1 2 3" gt lt? expression ?gt
Short cut for lt? echo expression ?gt lt variable
gt Short cut for lt echo variable gt ltscript
language'php'gt echo "php code" lt/scriptgt The
preferred method that is enabled by default in
PHP 4 is lt?php ?gt Others may need further PHP
configuration after installing PHP.
36
  • PHP is case sensitive just like Java.
  • PHP Autoglobals
  • _SERVER is a special reserved PHP variable that
    contains all web server information. It's known
    as an Autoglobal.
  • To display this variable, we can simply do

37
  • Printing a variable (Array element)lt?php echo
    _SERVER"HTTP_USER_AGENT" ?gtA sample output of
    this script may be Mozilla/4.0 (compatible MSIE
    5.01 Windows NT
  • _SERVER is just one variable that's
    automatically made available to you by PHP. You
    can get a complete list of the auto variables by
    using lt?php phpinfo() ?gt

38
  • PHP interface to the DB
  • lthtmlgt
  • ltbody bgColor"33AACC" Text"000000"gt
  • ltcentergt
  • lt?php
  • echo "lth1gtheaderlt/h1gt"
  • db mysql_connect("localhost",
    "db_username", "db_password")
  • mysql_select_db("dbname",db)
  • result mysql_query("SELECT FROM
  • tablename",db)
  • if (result "")
  • echo "SORRY, THIS INFORMATION IS
  • CURRENTLY UNAVAILABLE.ltbrgt"

39
  • else if (myrow mysql_fetch_array(result))
  • echo "lttable width600 cellspacing0
    cellpadding0
  • border1gt\n lttr aligncentergt"
  • / make header with column names /
  • description mysql_query("DESCRIBE
  • tablename",db)
  • echo "ltthgt Num. lt/thgt"
  • ncols 0
  • while (colnames mysql_fetch_array(descript
    ion))
  • echo "ltthgt colnames0 lt/thgt"
  • ncols ncols 1

40
  • echo "lt/trgt\n"
  • count 0
  • do
  • count count 1
  • print "lttrgtlttdgtcountlt/tdgt"
  • for (i0 i lt ncols i)
  • print "lttdgtmyrowilt/tdgt"
  • print "lt/trgt\n"
  • while (myrow mysql_fetch_array(result)
    )
  • // mysql_fetch_array may also be indexed as an
    associative array
  • // e.g. myrowid works if id is one of the
    selected attributes.
  • lt/tablegt
  • lt/centergt
  • lt/bodygt
  • lt/htmlgt

41
  • FUNCTIONS IN PHP
  • Examples
  • lt?phpfunction foo(arg)   if (arg lt 10)    
     echo "arg is less than 10"   else     echo 
    "arg is not less than 0"  
  • foo(15) / Echoes 15 is not less than 10" /
  • ?gt

42
  • Use the return statement to have the function
    return a value e.g.
  • Function adder(first, second)
  • return firstsecond
  • a 5
  • sum adder(a,10) / Call adder /

43
  • Reference/value Parameters An before the
    parameter at the function header indicates a
    reference parameter, otherwise it is a value
    parameter e.g.
  • a1 c2
  • function test(bb)
  • global c
  • echo a a // displays nothing why?
  • bb c
  • c
  • test(b)
  • echo a b c // displays 1 2 3 why?

44
  • Default Values for Paramaters
  • Example
  • function divide (num, den2)
  • return num/den
  • / den defaults to 2 if not specified at call
    time /
  • echo divide(2) / echoes 1 /

45
  • Some useful pre-defined functions
  • gettype(var) - Get the type of a variable
  • settype(var, type) - Set a variable to a
    certain type e.g. settype(myvar, "integer")
  • isset(var) - Determine whether a variable is
    set
  • i.e. has a value
  • unset(var) - Unset a given variable, destroys
    the specified variable and returns true
  • isset example
  • lt?phpif (isset(var))   echo "Your variable is 
    set"
  • else    echo "Your variable was not set"
  • ?gt

46

Scope of variables Variables declared or used in
a function are local to that function. For a
function to access a variable outside of the
function block, it must use the global keyword
to import the variable. Example lt?php tax  1.0
6 state  'MI' weight  5 function total(
t, shipping  1.33)      global tax, state,
weight     //import global variables if (stat
e  'MI')          t  tax  t  (shippin
g  weight)      else           t  shi
pping  weight             t
1000    total(t) printf( Total with shipping
and tax (if applicable) is ltbgt.2flt/bgt", t)   
?gt static var0 within a function forces var
to remain static over calls to the function.

47
  • Functions may be placed in a file and included in
    the scripts that may need them. In PHP4, if you
    have a return statement at the end of the include
    file, the returned value may be assigned to a
    variable at the include statement
  • Example
  • lt?php/ foo.inc file.
  • Always remember that you must start with a lt?php 
    tag when you include files. The parser drops out 
    of php-mode when it includes a file, so you have 
    to get it back again /function f1()
  • echo hello world
  • x 20
  • return time()
  • ?gt
  • Then you could write the following in
    script.php
  • lt?phpy  include('foo.inc') // include
    foo.inc works too
  • ?gt

48
  • setcookie -- Send a cookie
  • boolean setcookie ( string name , string value
    , int expire , string path , string domain ,
    int secure)
  • setcookie() defines a cookie to be sent along
    with the rest of the header information. Cookies
    must be sent before any other headers are sent
    (this is a restriction of cookies, not PHP). This
    requires you to place calls to this function
    before any lthtmlgt or ltheadgt tags. If headers
    exist prior to calling this function, setcookie()
    will fail and return FALSE. If setcookie()
    successfully runs, it will return TRUE This does
    not mean the user accepted the cookie or not.
  • All the arguments except the name argument are
    optional. If only the name argument is present,
    the cookie by that name will be deleted from the
    remote client. You may also replace any argument
    with an empty string ("") in order to skip that
    argument. The expire and secure arguments are
    integers and cannot be skipped with an empty
    string. Use a zero (0) instead.

49
  • Expiredate value
  • The expire argument is a regular Unix
    time integer as returned by the time() or
    mktime() functions.
  • The date string is formatted as Wdy, DD-Mon-YYYY
    HHMMSS GMT. For example,
  • Sunday, 03-Nov-2002 000000 GMT

50
  • domainDOMAIN_NAME
  • When searching the cookie list for valid cookies,
    a comparison of the domain attributes of the
    cookie is made with the Internet domain name of
    the host from which the URL will be fetched. If
    there is a tail match, then the cookie will go
    through path matching to see if it should be
    sent. "Tail matching" means that domain attribute
    is matched against the tail of the fully
    qualified domain name of the host. A domain
    attribute of "acme.com" would match host names
    "anvil.acme.com" as well as "shipping.crate.acme.c
    om".
  • Only hosts within the specified domain can set a
    cookie for a domain and domains must have at
    least two (2) or three (3) periods in them to
    prevent domains of the form ".com", ".edu", and
    "va.us". Any domain that fails within one of the
    seven special top level domains listed below only
    require two periods. Any other domain requires at
    least three. The seven special top level domains
    are "COM", "EDU", "NET", "ORG", "GOV", "MIL",
    and "INT".
  • The default value of domain is the host name of
    the server which generated the cookie response.

51
  • pathPATH
  • The path attribute is used to specify the subset
    of URLs in a domain for which the cookie is
    valid. If a cookie has already passed domain
    matching, then the pathname component of the URL
    is compared with the path attribute, and if there
    is a match, the cookie is considered valid and is
    sent along with the URL request. The path "/foo"
    would match "/foobar" and "/foo/bar.html". The
    path "/" is the most general path.
  • If the path is not specified, it as assumed to be
    the same path as the document being described by
    the header which contains the cookie.
  • The secure indicates that the cookie should only
    be transmitted over a secure HTTPS connection.

52
  • Once the cookies have been set, they can be
    accessed on the next page load with the _COOKIE
    or HTTP_COOKIE_VARS arrays.
  • Common Pitfalls
  • Cookies will not become visible until the next
    loading of a page that the cookie should be
    visible for. To test if a cookie was successfully
    set, check for the cookie on a next loading page
    before the cookie expires. Expire time is set via
    the expire parameter.
  • Cookies must be deleted with the same parameters
    as they were set with.
  • Cookies names can be set as array names and will
    be available to your PHP scripts as arrays but
    seperate cookies are stored on the users system..

53
  • Example 1.
  • setcookie ("TestCookie", value)
  • setcookie ("TestCookie", value,time()3600) /
    expire in 1 hour / setcookie ("TestCookie",
    value,time()3600, "/ikeji/",
    db1.acad.emich.edu", 0)

54
  • DELETING COOKIE
  • When deleting a cookie you should assure that the
    expiration date is in the past, to trigger the
    removal mechanism in your browser. Examples
    follow how to delete cookies sent in previous
    example
  • setcookie ("TestCookie", "", time() - 3600)
  • setcookie ("TestCookie", "", time() - 3600,
    "/ikeji/", db1.acad.emich.edu", 1)
  • Note that the value portion of the cookie will
    automatically be urlencoded when you send the
    cookie, and when it is received, it is
    automatically decoded and assigned to a variable
    by the same name as the cookie name. To see the
    contents of our test cookie in a script, use
  • echo _COOKIE"TestCookie"

55
  • You may also set array cookies by using array
    notation in the cookie name. This has the effect
    of setting as many cookies as you have array
    elements, but when the cookie is received by your
    script, the values are all placed in an array
    with the cookie's name
  • setcookie ("cookiethree", "cookiethree")
  • setcookie ("cookietwo", "cookietwo")
  • setcookie ("cookieone", "cookieone")
  • if (isset (_COOKIEcookie))
  • arr _COOKIEcookie
  • while (list (name, value) each (arr))
  • echo "name valueltbrgt\n"

56
  • PHP/RADIO BOX EXAMPLE
  • ltform actionans.php" method"post"gtWhat is
    11?
  • ltinput type"radio" name"choice" value1"
    checkedgt1
  • ltinput type"radio" name"choice"
    value2"gt2ltinput type"radio" name"choice"
    value3"gt3ltinput type"submit" value"Submit"gt
  • lt/formgt

57
  • On the ans.php, you may access the ans by using
  • lt?php
  • if (_POSTchoice 2)
  • echo alert(correct)
  • else
  • echo alert(sorry, wrong answer)
  • ?gt

58
  • PHP/CHECK BOXES EXAMPLE
  • ltform actionans.php"gt // default is get
    methodltinput namechoices" type"checkbox"
    valueA"gtAltinput namechoices"
    type"checkbox" valueB"gtBltinput
    namechoices" type"checkbox"
    value"C"gtCltinput namechoices"
    type"checkbox" value"D"gtDltinput type"submit"
    name"submit" value"Submit"gt
  • lt/formgt
  • PHP Code to process it
  • lt?phpitems _GETchoicesfor (i0
    iltcount(items) i) echo "itemsi
  • ?gt

59
  • PHP/SELECT BOXES EXAMPLE
  • To pass multiple values, as in a "Multiple Select
    Box", put after the variable name, like
    choices.
  • ltSELECT NAMEchoices" MULTIPLE
    SIZE3"gt    ltOPTION VALUE"1"gtOnelt/OPTIONgt    lt
    OPTION VALUE"2"gtTwolt/OPTIONgt    ltOPTION
    VALUE3"gtThreelt/OPTIONgt    ltOPTION
    VALUE4"gtFourlt/OPTIONgt    ltOPTION
    VALUE5"gtFivelt/OPTIONgtlt/SELECTgt

60
  • On the receiving page, you simply do a count() on
    choices, and iterate through the list of values
    that was selected just like in the checkbox
    example.
  • lt?phpitems_GETchoices
  • for (i0 iltcount(items) i)     echo it
    emsi
  • ?gt

61
  • PHP/FILE UPLOAD EXAMPLE
  • ltform action"file-upload.php" method"post"
    enctype"multipart/form-data"gt
  • Send these filesltbrgt
  • ltinput name"userfile" type"file"gtltbrgt
  • ltinput name"userfile" type"file"gtltbrgt
  • ltinput type"submit" value"Send files"gt
  • lt/formgt

62
  • When the above form is submitted, the arrays
    _FILES'userfile', _FILES'userfile''name',
    and _FILES'userfile''size' will be
    initialized.
  • For instance, assume that the filenames
    /home/test/one.html and /home/test/two.out are
    submitted. In this case, _FILES'userfile''name
    '0 would contain the value one.html, and
    _FILES'userfile''name'1 would contain the
    value two.out.
  • _FILES'userfile'tmp_name'0,
    _FILESuserfiletmp_name1 will contain
    the temporary local names of the files on the
    server. Use these names to access the files on
    the local server.
  • Similarly, _FILES'userfile''size'0 and
    _FILES'userfile''type'0 are also set.

63
  • fgets
  • (PHP 3, PHP 4 )
  • fgets -- Gets line from file pointer
  • Description
  • string fgets ( int fp , int length)Returns a
    string of up to length - 1 bytes read from the
    file pointed to by fp. Reading ends when length -
    1 bytes have been read, on a newline (which is
    included in the return value), or on EOF
    (whichever comes first). If no length is
    specified, the length defaults to 1k, or 1024
    bytes.
  • If an error occurs, returns FALSE.

64
  • FILE I/O EXAMPLE
  • lt?php
  • FILE fopen(in.dat","r") // for reading only
  • NEWFILE open(out.dat","w")// open for
    writing only
  • // continously read in from data.txtwhile
    (BUFFER fgets(FILE,4096))
    fputs(NEWFILE,BUFFER) //write to out.dat
  • fclose(FILE) // close in.datfclose(NEWFILE)
    // close out.dat
  • ?gt

65
  • RELATED FILE UPLOAD FUNCTIONS
  • bool move_uploaded_file ( string filename, string
    destination)This function checks to ensure that
    the file designated by filename is a valid upload
    file (meaning that it was uploaded via PHP's HTTP
    POST upload mechanism). If the file is valid, it
    will be moved to the filename given by
    destination.
  • If filename is not a valid upload file, then no
    action will occur, and move_uploaded_file() will
    return FALSE.

66
Practical Extraction and Report Language (Perl)
By Example
  • Perl is widely used for textual pattern matching,
    extraction and substitution. It is because of
    this feature that it is widely used in CGI
    programming.
  • It is an interpreted language. It may also be
    compiled into an intermediate form to speed up
    the interpretation phase.
  • Number constants in Perl 1, 1.5, .1, 1., 1e5,
    1E-2, 1.5E-1, 0XFF, 0x2AE
  • String constants in Perl abc, abc, joe\s
    car, joes car, , , 8 hello\nworld,
  • qhello\nworld gives hello\nworld any char may
    b used as delimiter after q
  • qqchello\nworldc gives hello\nworld
  • Variables Dont have to be declared. Auto
    declared at first instance if need be. Value of a
    variable without a value is undef. Undef in
    integer context is 0, in string context is null.
  • Scalar variable names start with , followed by
    letter, and then any combination of
    letter,digit,underscore. No length limit although
    first 255 chars are recognized.
  • Variable names are case sensitive.
  • Examples x 50
  • Value of x is x
  • Predefined or implicit variables start with and
    usually followed by one special character like ,
    _, \
  • Numeric operators , --, unary -, , ,/,,
    binary ,-
  • Numeric relational ops , !, lt,gt,lt,gt
  • Expressions with number evaluate to
    double-precision e.g. 3/2 is 1.5
  • String operators . (concatenation), x
    (repetition) e.g.abc. def gives abcdef,
    abcx4 gives abcabcabcabc
  • String relational ops eq, ne, lt, gt, le, ge

67
Control Structuresif elsif else, unless, while,
for, statements must have , around them
e.g.if (a gt b) unless (a gt b) //
opposite condition to the if statementuntil
(cond) // opposite condition to the while
statementfor (inittestupdate)A group of
statements may be encased in a block statement.
For example, to simulate the switch statement in
Perl, usepoints 0SWITCH label for
block is called SWITCH if (score lt 60)
last SWITCH break from switch points
if (score lt 70) last SWITCH points
if (scorelt 80) last SWITCH points if
(score lt 90) last SWITCH points end
of SWITCH block Note last label will break
from the indicated label. If no label is given,
it breaks from the enclosing . In the above
example, if SWITCH is not specified last, it will
only break from the if block.IMPLICIT VARIABLE
__ is the default parameter in function calls
i.e. when a function is called without a
parameter, the default parameter is the current
value of _. For example,while (ltSTDINgt
chomp print if (_ eq mike)print welcome
mikeARRAYS Arrays can store lists. List
may contain only scalar types - numbers, strings
and references. Arrays may change in length or
type dynamically. Array names start with at _at_
sign. Only integer types may be used for array
indexing. First element is at index 0.
Examples_at_scores (80, 70, 40, 99)_at_names
qw(james mike jim)first scores0
80names10 jane auto increases size of
names to 11array represents the last
subscript of array and this can be changed to
dynamically increase or decrease the array size.
For example,names 100 len names
1len _at_names array names used in the
context of a scalar yields the array
length.Array values may processed using the
foreach statement e.g.foreach item (_at_scores)
add 10 to each score item
10shift/pop/unshift/pushfirstItem shift
_at_list removes and returns first item in list.
Remaining items are shifted forward.lastItem
pop _at_listpush _at_list, 3 pushes 3 to end of
listpush _at_list, (3, 20, 4) pushes items
3,20,4 to end of list in that orderunshift
_at_list, (5, 10) prepands 5, 10 to list.SPLIT
operator may be use to tokenize a string along
specified character(s). For example, s1
jim-mike-mary_at_tokens split /-m/, s1
yields tokens0jim, tokens1ike,
tokens2aryAssociation lists or hashes -
these are key,value pairs e.g.Hashes (because
the locator function uses hashing) must start
with sign. For example,name_score
(Jimgt80, Kinggt75) orname_score
(Jim, 80, King, 75)To retrieve a value,
specify the key e.g. jims_score
name_scoreJimTo insert a value, use
name_scoreJenny 50delete
name_scoreKing deletes King and his
scoreif (exists name_scoreKing) is now
falsevalues or keys hashvariable yields and
array of the values of keys e.g.foreach (i
(values name_score)) ...foreach (1 (keys
name_score)) ... FUNCTIONSFunctions may be
called before they are declaredFunctions may
return values with a return statement. If no
return statement is met in the course of
execution, the value of the last executed
statement is returnedTo make local variables,
use the local keyword or the my function.
Variables declared with the my function have
static scope while variables declared with the
local keyword have dynamic scope.All actual
arguments are sent in as formal arguments via the
special array variable _at__. Changes to _at__ would
result in pass by reference. Examplessub f1
my(a, b) _at__ extracts the first 2 args
into local varaibles _0
abx5 y10t f1(x, y) results
in t15, x6, y10 PATTERNS and REGULAR
EXPRESSIONSSpecial characters are
\()?.Use slashes to surround the string
to be matched e.g.if (/jan/) .. looks for
jan in _. Matches any one char .. matches
any one char inside a-z matches any
lowercase charUsing circumflex () as the first
char in a class negates the specified set e.g.
0123456789 matches any non digit/abc3d/ is
the same as abcccd means 0 or more reps.,
means 1 or more and ? is 0 or 1
e.g.abcxyz?/abc/ must match at the
beginning,/abc/ must match at the end of a
string PREDEFINED CHARACTER CLASSES\d 0-9 A
digit\D 0-9 Not a digit\s \r\t\n\f white
space\S \r\t\n\f not white spaceFor
example /\d\.\d/ represents a number that
starts with at least one digit, followed by a
period and then 0 or more digits after the
period.To match a pattern against a string
other than _, usestr /\d/ true if
there is a digit in strstr !- /\d/ true
if there is NO digit in strEXTRACTING THE
MATCHED SUBSTRINGS1, 2, 3 etc. contain the
substrings that match the patterns. The patterns
must be placed inside parenthesis to get the
results in 1, 2, etc.For example 1 January
2001 /(\w) (\d) (\d)/ yields 1 as
January, 2 as 2001 and nothing for 3. The match
is done from the end position of the last match.
After a match, , , may be used to get
the part of the string that preceed the match,
the part that matched, the part that followed the
match.s/pattern/new-string/ replaces pattern
in s with new-stringIf new-string is an
expression, place an e after the last slash to
get the expression evaluated and its result will
be used in the replacement.For example _
Jane is 10 years old s/(\d)/12/e
yields Jane is 12 years old. Without the e, you
will end up with Jane is 102 years old i.e. it
will not evaluate the 102.The g operator is
for global substitution i.e. dont stop at the
first one e.g._ James Jim Janes/Ja/ja/g
yields james Jim jane TRANSLITERATE
(tr) Operator Use to replace characters by other
characters. Examples,tr//gt/ replaces with
gttr/0-9/A-J/ replaces 0 with A, 1 with B
respectivelytr/0-9/A/ replaces each digit
with Atr/-/\\// replaces each , - with /
respectively
68
FILE I/Oopen (INFILE, ltin.dat) or die
Erroropen (OUTFILE, gtout.dat) or die Error
in openopen (OUTFILE, gtgtout.dat) or die
Error in open opens for append modeNOTE Do
not use die for CGI/perl programs because you may
get premature end of script.x
ltINFILEgtprint OUTFILE Sum of x and y is
sumncharsRead read(INPUT, buf, 3000)
returns 0 to 3000 chars read from INPUT into buf
array. nCharsRead is the actual of chars
read._at_lines split /\n/, buf splits but into
lines
69
CGI/PERL programmingUse !/usr/bin/perl -w as
the first line of the CGI program to specify that
the rest of the file is to be run under
perl.The ! Specifies that the program whose
location follows is to be executed on the rest of
the file.ENVenvironment-variable returns
the value of the environment variable.For
example,request_method ENVREQUEST_METHOD
if (request_method eq GET)
query_string ENVQUERY_STRINGelsif if
(request_method eq POST)
read(STDIN,query_string,ENVCONTENT_LENGTH)
else print Content-type
text/plain\n\nIllegal request method\n
split query string into name-value
pairs_at_name_value_list split(//,
query_string)foreach name_value
(_at_name_value_list) (name, value)
split(//, name_value) value tr// /
change s to spaces change hex strings of
the form dHH to decimal values value
s/(\dA-Fa-f\dA-Fa-f)/pack(C, hex(1))/eg

70
The CGI perl module (CGI.pm)This module
contains the common routines needed for CGI
programming in perl. Their use is enabled in a
CGI program via the use statement. For
exampleuse CGI qw(standard) enables the use
of the standard (most commonly needed) CGI/perl
functions in CGI.pm.Use CGI brings in
everything which may be unnecessary.The CGI.pm
shortcuts are named after their html tag
counterpart and may be given parameters too. They
normally use only the lowercase characters of the
html tag.Examplesprint header() or print
header gives Content-type text/html\n\nprin
t start_html(test) gives lthtmlgtltheadlttitlegttestlt
/titlegtlt/headgtltbodygtprint start_form() gives
ltform methodpostgtend_form gives lt/formgt
end_html gives lt/bodygtlt/htmlgtprint h1(hello
world) lth1gthello worldlt/h1gtprint b(Bold)
ltbgtBoldlt/bgtprinttextarea(-namegt
scores, -rowsgt4, -valuegt10\n20)gives
lttextarea namescores rows4gt10\n20lt/textareagt
To specify the content for a tag, place
attributes inside , and then follow with the
content. For example,a(-hrefgtmike.html,
mikes homepage)gives mikes
homepageol(li(jim, jane, james))
yieldsltolgtltligtjimltligtjaneltligtjameslt/olgtradio_gr
oup(-namegtstudents, -valuegtjim,jane,king
),br, radio_group(-namegtstudents,
-valuegtjames) yieldsltinput typeradio
namestudents valuejimgt ltinput typeradio
namestudents valuejanegt ltinput
typeradio namestudents valuekinggtltbrgt
ltinput typeradio namestudents
valuejamesgt table(-bordergt2,
caption(b(Test table)), Tr( th(,
col1, col2, col3, col4),
th(row1).td(1,1, 1,2, 1,3, 1,4),
th(row2).td(2,1, 2,2, 3,3, 3,4),
th(row3).td(3,1, 3,2, 3,3,
3,4) )) note that T in Tr must
be capitalized so as not to confuse it with perls
tr function. The above givesltTABLE
BORDER"2"gtltCAPTIONgtltBgtTest tablelt/Bgtlt/CAPTIONgt
ltTRgtltTHgtlt/THgt ltTHgtcol1lt/THgt ltTHgtcol2lt/THgt
ltTHgtcol3lt/THgt ltTHgtcol4lt/THgtlt/TRgt
ltTRgtltTHgtrow1lt/THgtltTDgt1,1lt/TDgt ltTDgt1,2lt/TDgt
ltTDgt1,3lt/TDgt ltTDgt1,4lt/TDgtlt/TRgt ltTRgtltTHgtrow2lt/THgtltT
Dgt2,1lt/TDgt ltTDgt2,2lt/TDgt ltTDgt2,3lt/TDgt
ltTDgt2,4lt/TDgtlt/TRgt ltTRgtltTHgtrow3lt/THgtltTDgt3,1lt/TDgt
ltTDgt3,2lt/TDgt ltTDgt3,3lt/TDgt ltTDgt3,4lt/TDgtlt/TRgtlt/TABL
Egt
71
LOCK AND UNLOCK FEATURESThe same CGI program
may be executed concurrently by different users.
If the program accesses files, care must be taken
not to corrupt the files. Concurrency control is
achieved via the flock function. An argument of 2
waits until a lock is achieved and an argument of
8 will unlock the file.For example,flock
(ltINFILEgt, 2) blocks until lock is gained on
INFILE read and process INFILE
dateflock(ltINFLEgt, 8) unlocks INFILE so one
of the blocked processes can go through.
72
Perl DBI example with MySQL!/usr/bin/perl
-w ch04/error/ex1 Small example using manual
error checking. use DBI Load the
DBI module Perform the connection using
the Oracle drivermy dbh DBI-gtconnect(
'DBImysqlcosc681db', "cosc681", "cosc681pwd",
PrintError gt 0, RaiseError gt 0
) or die "Can't connect to the database
DBIerrstr\n" Prepare a SQL statement
for executionmy sth dbh-gtprepare( "SELECT
FROM student" ) or die "Can't prepare SQL
statement DBIerrstr\n" Execute the
statement in the databasesth-gtexecute or
die "Can't execute SQL statement
DBIerrstr\n" Retrieve the returned
rows of data my _at_row while ( _at_row
sth-gtfetchrow_array( ) ) print "Row
_at_row\n" warn "Data fetching terminated
early by error DBIerrstr\n" if
DBIerr Disconnect from the database
dbh-gtdisconnect or warn "Error
disconnecting DBIerrstr\n" exit
Write a Comment
User Comments (0)
About PowerShow.com