SlideShare a Scribd company logo
Including Multiple Files



   Pengaturcaraan PHP




Pengaturcaraan PHP
Every PHP script can consist of a single file that contains all of the
required HTML and PHP code. But as you develop more complex Web
sites, you'll see that this methodology has many limitations. PHP can
readily make use of external files, a capability that allows you to divide your
scripts into their distinct parts. Frequently you will use external files to extract
your HTML from your PHP or to separate out commonly used processes.




                                                                                       1
Pengaturcaraan PHP
PHP has four functions for using external files: include(), include_once(),
require(), and require_once(). To use them, your PHP script would have
a line like:




Pengaturcaraan PHP




                                                                              2
Pengaturcaraan PHP
 Both functions also have a *_once() version, which guarantees that the file
 in question is included only once regardless of how many times a script
 may (presumably inadvertently) attempt to include it.




In this first example, included files are used to separate HTML formatting
from PHP code. Then, the rest of the examples in this lesson will be able to have
the same appearance without the need to rewrite the HTML every time. The
concept results in a template system, an easy way to make large applications
consistent and manageable.

In our example, we've used a Cascading Style Sheet file to control the layout
of all pages. The style sheet code is referenced in each HTML file for consistent
styles and formatting throughout the Web site.




                                                                                    3
Pengaturcaraan PHP




    Using PHP Redux



Pengaturcaraan PHP




                      4
Pengaturcaraan PHP
In many instances, two separate scripts for handling HTML forms can be used:
one that displays the form and another that receives it. While there's certainly
nothing wrong with this method, you may find your scripts run more efficiently
when the entire process is in one script.

To have one page both display and handle a form, use a conditional.




 Pengaturcaraan PHP

To determine if the form has been submitted, set a $_POST variable
(assuming that the form uses the POST method, of course). For example, you
can check $_POST['submitted'], assuming that's the name of a hidden input
type in the form.




                                                                                   5
Pengaturcaraan PHP
   If you want a page to handle a form and then display it again (e.g., to add
   a record to a database and then give an option to add another), use




   Using the preceding code, a script will handle a form if it has been
   submitted and display the form every time the page is loaded.




  Pengaturcaraan PHP

Write the conditional for handling the form. As mentioned previously, if the
$_POST ['submitted'] variable is set, we know that the form has been
submitted and we can process it. This variable will be created by a hidden
input in the form that will act as a submission indicator.




                                                                                 6
Pengaturcaraan PHP




Pengaturcaraan PHP




                     7
Pengaturcaraan PHP




Pengaturcaraan PHP




                     8
Pengaturcaraan PHP




Pengaturcaraan PHP
You can also have a form submit back to itself by having PHP print the
name of the current script — stored in $_SERVER['PHP_ SELF'] — as
the action attribute:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="post">




                                                                         9
Pengaturcaraan PHP




Pengaturcaraan PHP




                     10
Pengaturcaraan PHP




Pengaturcaraan PHP




                     11
Making Sticky Forms



   Pengaturcaraan PHP




Pengaturcaraan PHP
You've certainly come across sticky forms, even if you didn't know that's what
they were called. A sticky form is simply a standard HTML form that
remembers how you filled it out. This is a particularly nice feature for end
users, especially if you are requiring them to resubmit a form (for instance,
after filling it out incorrectly in the first place).

To preset what's entered in a text box, use its value attribute:




                                                                                 12
Pengaturcaraan PHP

To have PHP preset that value, print the appropriate variable:




Pengaturcaraan PHP




                                                                 13
Pengaturcaraan PHP




Pengaturcaraan PHP




                     14
Pengaturcaraan PHP




    Creating Your Own
    Functions


Pengaturcaraan PHP




                        15
Pengaturcaraan PHP
PHP has a lot of built-in functions, addressing almost every need. More
importantly, though, it has the capability for you to define and use your own
functions for whatever purpose. The syntax for making your own function is




The name of your function can be any combination of letters, numbers, and
the underscore, but it must begin with either a letter or the underscore.
The main restriction is that you cannot use an existing function name for your
function (print, echo, isset, and so on).




 Pengaturcaraan PHP
 In PHP, function names are case-insensitive (unlike variable names), so
 you could call that function in several different ways such as:




                                                                                 16
Pengaturcaraan PHP




Pengaturcaraan PHP




                     17
Pengaturcaraan PHP




Pengaturcaraan PHP




                     18
Pengaturcaraan PHP




    Creating a Function
    That Takes Arguments


Pengaturcaraan PHP




                           19
Pengaturcaraan PHP
Just like PHP's built-in functions, those you write can take arguments (also
called parameters). For example, the print() function takes what you want sent
to the browser as an argument and strlen() takes a string whose character
length will be determined.

A function can take any number of arguments that you choose, but the order in
which you put them is critical. To allow for arguments, add variables to your
function's definition:




Pengaturcaraan PHP

You can then call the function as you would any other function in PHP,
sending literal values or variables to it:




                                                                                 20
Pengaturcaraan PHP




Pengaturcaraan PHP




                     21
Pengaturcaraan PHP




    Setting Default
    Argument Values


Pengaturcaraan PHP




                      22
Pengaturcaraan PHP
Another variant on defining your own functions is to preset an argument's
value. To do so, assign the argument a value in the function's definition:




The end result of setting a default argument value is that that particular
argument becomes optional when calling the function. If a value is passed to
it, the passed value is used; otherwise, the default value is used.




Pengaturcaraan PHP
You can set default values for as many of the arguments as you want, as
long as those arguments come last in the function definition. In other words,
the required arguments should always be first. With the example function just
defined, any of these will work:




However, greet() will not work, and there's no way to pass $greeting a value
without passing one to $name as well.




                                                                                23
Pengaturcaraan PHP




Pengaturcaraan PHP




                     24
Pengaturcaraan PHP




Pengaturcaraan PHP




                     25
Pengaturcaraan PHP




Pengaturcaraan PHP




                     26
Returning Values from
            a Function


   Pengaturcaraan PHP




Pengaturcaraan PHP
Some, but not all, functions return values. For example, print() will return
either a 1 or a 0 indicating its success, whereas echo() will not. As another
example, the strlen() function returns a number correlating to the number of
characters in a string.

To have your function return a value, use the return statement.




                                                                                27
Pengaturcaraan PHP

The function can return a value (say a string or a number) or a variable whose
value has been created by the function. When calling this function, you can
assign the returned value to a variable:

 $my_sign = find_sign ('October', 23);


or use it as a parameter to another function:

 print find_sign ('October', 23);




Pengaturcaraan PHP




                                                                                 28
Pengaturcaraan PHP




Pengaturcaraan PHP




                     29
Pengaturcaraan PHP




    Variable Scope



Pengaturcaraan PHP




                     30
Pengaturcaraan PHP
  Variable scope is a tricky but important concept.
  Every variable in PHP has a scope to it, which is
  to say a realm in which the variable (and
  therefore its value) can be accessed. For
  starters, variables have the scope of the page in
  which they reside. So if you define $var, the rest
  of the page can access $var, but other pages
  generally cannot (unless you use special
  variables).


  Since included files act as if they were part of
  the original (including) script, variables defined
  before the include() line are available to the
  included file. Further, variables defined within
  the included file are available to the parent
  (including) script after the include() line.




 Pengaturcaraan PHP

All of this becomes murkier when using your own defined functions. These
functions have their own scope, which means that variables used within a
function are not available outside of it, and variables defined outside of a
function are not available within it. For this reason, a variable inside of a
function can have the same name as one outside of it and still be an entirely
different variable with a different value. This is a confusing concept for most
beginning programmers.




                                                                                  31
Pengaturcaraan PHP
To alter the variable scope within a function, you can use the global statement.




In this example, $var inside of the function is now the same as $var outside
of it. This means that the function $var already has a value of 20, and if that
value changes inside of the function, the external $var's value will also
change.




 Pengaturcaraan PHP




                                                                                   32
Pengaturcaraan PHP




Pengaturcaraan PHP




                     33
Pengaturcaraan PHP




Pengaturcaraan PHP




                     34
Date and Time
           Functions


  Pengaturcaraan PHP




Pengaturcaraan PHP

PHP has several date- and time-related functions for use in your scripts. The
most important of these is the aptly named date() function, which returns a
string of text for a certain date and time according to a format you specify.




The timestamp is an optional argument representing the number of
seconds since the Unix Epoch (midnight on January 1, 1970) for the date
in question. It allows you to get information, like the day of the week, for a
particular date. If a timestamp is not specified, PHP will just use the current
time on the server.




                                                                                  35
Pengaturcaraan PHP

There are myriad formatting parameters available, and these can be used in
conjunction with literal text. For example,




  Character          Meaning                                  Example
  Y                  year as 4 digits                         2005

  y                  year as 2 digits                         05

  n                  month as 1 or 2 digits                   2

  m                  month as 2 digits                        02

  F                  month                                    February

  M                  month as 3 letters                       Feb

  j                  day of the month as 1 or 2 digits        8

  d                  day of the month as 2 digits             08

  l (lowercase L)    day of the week                          Monday

  D                  day of the week as 3 letters             Mon

  g                  hour, 12-hour format as 1 or 2 digits    6

  G                  hour, 24-hour format as 1 or 2 digits    18

  h                  hour, 12-hour format as 2 digits         06

  H                  hour, 24-hour format as 2 digits         18

  i                  minutes                                  45

  s                  seconds                                  18

  a                  am or pm                                 am

  A                  AM or PM                                 PM




                                                                             36
Pengaturcaraan PHP

You can find the timestamp for a particular date using the mktime() function.




Pengaturcaraan PHP

Finally, the getdate() function can be used to return an array of values for a
date and time. For example,




This function also takes an optional timestamp argument. If that
argument is not used, getdate() returns information for the current
date and time.




                                                                                 37
Pengaturcaraan PHP

 The getdate() function returns this associative array.


 Key             Value                      Example
 year            year                       2005
 mon             month                      12
 month           month name                 December
 mday            day of the month           25
 weekday         day of the week            Sunday
 hours           hours                      11
 minutes         minutes                    56
 seconds         seconds                    47




Pengaturcaraan PHP




                                                          38
Pengaturcaraan PHP




Pengaturcaraan PHP




                     39
Pengaturcaraan PHP




Pengaturcaraan PHP




                     40
Pengaturcaraan PHP




Pengaturcaraan PHP




                     41
Pengaturcaraan PHP
Date – “time()”
To display current time and date
Syntax : time();

Example :
echo time();

Output = 23
// sample output: 1060751270
//this represent August 12th, 2003 at 10:07PM




Pengaturcaraan PHP

Date – “mktime”
To display date and time in timestamp

Syntax : mktime();

Example :
echo mktime();
or
$tarikh = $mktime(4,15,0,8,23,2003);
$tarikh = date(“d/m/Y”,mktime()+50);




                                                42
Pengaturcaraan PHP
Others Syntax :

  $tomorrow = mktime (0,0,0,date("m")
  ,date("d")+1,date("Y"));

  $lastmonth = mktime (0,0,0,date("m")-1,date("d"),
  date("Y"));

  $nextyear = mktime (0,0,0,date("m"), date("d"),
  date("Y")+1);




         Sending Email



  Pengaturcaraan PHP




                                                      43
Pengaturcaraan PHP

Using PHP makes sending email very easy. On a properly configured server,
the process is as simple as using the mail() function.




The $to value should be an email address or a series of addresses,
separated by commas. The $subject value will create the email's subject
line, and $body is where you put the contents of the email. Use the
newline character (n) within double quotation marks when creating your
body to make the text go over multiple lines.




Pengaturcaraan PHP
 The mail() function takes a fourth, optional parameter for additional
 headers. This is where you could set the From, Reply-To, Cc, Bcc, and
 similar settings. For example,




                                                                            44
Pengaturcaraan PHP
To use multiple headers of different types in your email, separate each
with rn:




Pengaturcaraan PHP




                                                                          45
Pengaturcaraan PHP




Pengaturcaraan PHP




                     46
Pengaturcaraan PHP




Pengaturcaraan PHP




                     47
End



Pengaturcaraan PHP




                     48

More Related Content

What's hot

9780538745840 ppt ch01 PHP
9780538745840 ppt ch01 PHP9780538745840 ppt ch01 PHP
9780538745840 ppt ch01 PHP
Terry Yoast
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
okelloerick
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
lalithambiga kamaraj
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
REHAN IJAZ
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
sami2244
 
Php web development
Php web developmentPhp web development
Php web development
Ramesh Gupta
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
Chris Stone
 
PHP 7X New Features
PHP 7X New FeaturesPHP 7X New Features
PHP 7X New Features
Thanh Tai
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
tanmaymodi4
 
Welcome to computer programmer 2
Welcome to computer programmer 2Welcome to computer programmer 2
Welcome to computer programmer 2
MLG College of Learning, Inc
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
Cecilia Pamfilo
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
kinish kumar
 
Deep C
Deep CDeep C
Deep C
Olve Maudal
 

What's hot (20)

9780538745840 ppt ch01 PHP
9780538745840 ppt ch01 PHP9780538745840 ppt ch01 PHP
9780538745840 ppt ch01 PHP
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
 
Php NotesBeginner
Php NotesBeginnerPhp NotesBeginner
Php NotesBeginner
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
 
Php1
Php1Php1
Php1
 
Php web development
Php web developmentPhp web development
Php web development
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
topic_perlcgi
topic_perlcgitopic_perlcgi
topic_perlcgi
 
PHP 7X New Features
PHP 7X New FeaturesPHP 7X New Features
PHP 7X New Features
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
 
Welcome to computer programmer 2
Welcome to computer programmer 2Welcome to computer programmer 2
Welcome to computer programmer 2
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
Deep C
Deep CDeep C
Deep C
 
Symfony Components
Symfony ComponentsSymfony Components
Symfony Components
 
Php
PhpPhp
Php
 

Viewers also liked

Developing web applications
Developing web applicationsDeveloping web applications
Developing web applicationssalissal
 
Wells Fargo HAFA Guidelines
Wells Fargo HAFA GuidelinesWells Fargo HAFA Guidelines
Wells Fargo HAFA Guidelines
practicallist
 
Equator Short Sale Manual
Equator Short Sale ManualEquator Short Sale Manual
Equator Short Sale Manualpracticallist
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debuggingsalissal
 
Pfextinguisher
PfextinguisherPfextinguisher
Pfextinguishere'z rules
 
Equator Short Sale Manual
Equator Short Sale ManualEquator Short Sale Manual
Equator Short Sale Manual
practicallist
 
Hcg foods
Hcg foodsHcg foods
Hcg foods
practicallist
 
RMA - Request for mortgage assistance
RMA - Request for mortgage assistanceRMA - Request for mortgage assistance
RMA - Request for mortgage assistance
practicallist
 
bank of america short sale check list
bank of america short sale check listbank of america short sale check list
bank of america short sale check list
practicallist
 
List of Internet Acronyms
List of Internet AcronymsList of Internet Acronyms
List of Internet Acronyms
practicallist
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sqlsalissal
 

Viewers also liked (15)

My sql
My sqlMy sql
My sql
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applications
 
Wells Fargo HAFA Guidelines
Wells Fargo HAFA GuidelinesWells Fargo HAFA Guidelines
Wells Fargo HAFA Guidelines
 
Equator Short Sale Manual
Equator Short Sale ManualEquator Short Sale Manual
Equator Short Sale Manual
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
 
Basic php
Basic phpBasic php
Basic php
 
Pfextinguisher
PfextinguisherPfextinguisher
Pfextinguisher
 
Equator Short Sale Manual
Equator Short Sale ManualEquator Short Sale Manual
Equator Short Sale Manual
 
Hcg foods
Hcg foodsHcg foods
Hcg foods
 
RMA - Request for mortgage assistance
RMA - Request for mortgage assistanceRMA - Request for mortgage assistance
RMA - Request for mortgage assistance
 
bank of america short sale check list
bank of america short sale check listbank of america short sale check list
bank of america short sale check list
 
List of Internet Acronyms
List of Internet AcronymsList of Internet Acronyms
List of Internet Acronyms
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
Test2
Test2Test2
Test2
 
ชุดกิจกรรมที่ 1
ชุดกิจกรรมที่  1ชุดกิจกรรมที่  1
ชุดกิจกรรมที่ 1
 

Similar to Dynamic website

Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
HASENSEID
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
Ashish Chamoli
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_masterjeeva indra
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
Nisa Soomro
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
Unit 1
Unit 1Unit 1
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)Arjun Shanka
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
rasool noorpour
 
chapter Two Server-side Script lang.pptx
chapter  Two Server-side Script lang.pptxchapter  Two Server-side Script lang.pptx
chapter Two Server-side Script lang.pptx
alehegn9
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPrinceGuru MS
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics EbookSwanand Pol
 

Similar to Dynamic website (20)

Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Php basics
Php basicsPhp basics
Php basics
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Unit 1
Unit 1Unit 1
Unit 1
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
chapter Two Server-side Script lang.pptx
chapter  Two Server-side Script lang.pptxchapter  Two Server-side Script lang.pptx
chapter Two Server-side Script lang.pptx
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
phptutorial
phptutorialphptutorial
phptutorial
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 

Dynamic website

  • 1. Including Multiple Files Pengaturcaraan PHP Pengaturcaraan PHP Every PHP script can consist of a single file that contains all of the required HTML and PHP code. But as you develop more complex Web sites, you'll see that this methodology has many limitations. PHP can readily make use of external files, a capability that allows you to divide your scripts into their distinct parts. Frequently you will use external files to extract your HTML from your PHP or to separate out commonly used processes. 1
  • 2. Pengaturcaraan PHP PHP has four functions for using external files: include(), include_once(), require(), and require_once(). To use them, your PHP script would have a line like: Pengaturcaraan PHP 2
  • 3. Pengaturcaraan PHP Both functions also have a *_once() version, which guarantees that the file in question is included only once regardless of how many times a script may (presumably inadvertently) attempt to include it. In this first example, included files are used to separate HTML formatting from PHP code. Then, the rest of the examples in this lesson will be able to have the same appearance without the need to rewrite the HTML every time. The concept results in a template system, an easy way to make large applications consistent and manageable. In our example, we've used a Cascading Style Sheet file to control the layout of all pages. The style sheet code is referenced in each HTML file for consistent styles and formatting throughout the Web site. 3
  • 4. Pengaturcaraan PHP Using PHP Redux Pengaturcaraan PHP 4
  • 5. Pengaturcaraan PHP In many instances, two separate scripts for handling HTML forms can be used: one that displays the form and another that receives it. While there's certainly nothing wrong with this method, you may find your scripts run more efficiently when the entire process is in one script. To have one page both display and handle a form, use a conditional. Pengaturcaraan PHP To determine if the form has been submitted, set a $_POST variable (assuming that the form uses the POST method, of course). For example, you can check $_POST['submitted'], assuming that's the name of a hidden input type in the form. 5
  • 6. Pengaturcaraan PHP If you want a page to handle a form and then display it again (e.g., to add a record to a database and then give an option to add another), use Using the preceding code, a script will handle a form if it has been submitted and display the form every time the page is loaded. Pengaturcaraan PHP Write the conditional for handling the form. As mentioned previously, if the $_POST ['submitted'] variable is set, we know that the form has been submitted and we can process it. This variable will be created by a hidden input in the form that will act as a submission indicator. 6
  • 9. Pengaturcaraan PHP Pengaturcaraan PHP You can also have a form submit back to itself by having PHP print the name of the current script — stored in $_SERVER['PHP_ SELF'] — as the action attribute: <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 9
  • 12. Making Sticky Forms Pengaturcaraan PHP Pengaturcaraan PHP You've certainly come across sticky forms, even if you didn't know that's what they were called. A sticky form is simply a standard HTML form that remembers how you filled it out. This is a particularly nice feature for end users, especially if you are requiring them to resubmit a form (for instance, after filling it out incorrectly in the first place). To preset what's entered in a text box, use its value attribute: 12
  • 13. Pengaturcaraan PHP To have PHP preset that value, print the appropriate variable: Pengaturcaraan PHP 13
  • 15. Pengaturcaraan PHP Creating Your Own Functions Pengaturcaraan PHP 15
  • 16. Pengaturcaraan PHP PHP has a lot of built-in functions, addressing almost every need. More importantly, though, it has the capability for you to define and use your own functions for whatever purpose. The syntax for making your own function is The name of your function can be any combination of letters, numbers, and the underscore, but it must begin with either a letter or the underscore. The main restriction is that you cannot use an existing function name for your function (print, echo, isset, and so on). Pengaturcaraan PHP In PHP, function names are case-insensitive (unlike variable names), so you could call that function in several different ways such as: 16
  • 19. Pengaturcaraan PHP Creating a Function That Takes Arguments Pengaturcaraan PHP 19
  • 20. Pengaturcaraan PHP Just like PHP's built-in functions, those you write can take arguments (also called parameters). For example, the print() function takes what you want sent to the browser as an argument and strlen() takes a string whose character length will be determined. A function can take any number of arguments that you choose, but the order in which you put them is critical. To allow for arguments, add variables to your function's definition: Pengaturcaraan PHP You can then call the function as you would any other function in PHP, sending literal values or variables to it: 20
  • 22. Pengaturcaraan PHP Setting Default Argument Values Pengaturcaraan PHP 22
  • 23. Pengaturcaraan PHP Another variant on defining your own functions is to preset an argument's value. To do so, assign the argument a value in the function's definition: The end result of setting a default argument value is that that particular argument becomes optional when calling the function. If a value is passed to it, the passed value is used; otherwise, the default value is used. Pengaturcaraan PHP You can set default values for as many of the arguments as you want, as long as those arguments come last in the function definition. In other words, the required arguments should always be first. With the example function just defined, any of these will work: However, greet() will not work, and there's no way to pass $greeting a value without passing one to $name as well. 23
  • 27. Returning Values from a Function Pengaturcaraan PHP Pengaturcaraan PHP Some, but not all, functions return values. For example, print() will return either a 1 or a 0 indicating its success, whereas echo() will not. As another example, the strlen() function returns a number correlating to the number of characters in a string. To have your function return a value, use the return statement. 27
  • 28. Pengaturcaraan PHP The function can return a value (say a string or a number) or a variable whose value has been created by the function. When calling this function, you can assign the returned value to a variable: $my_sign = find_sign ('October', 23); or use it as a parameter to another function: print find_sign ('October', 23); Pengaturcaraan PHP 28
  • 30. Pengaturcaraan PHP Variable Scope Pengaturcaraan PHP 30
  • 31. Pengaturcaraan PHP Variable scope is a tricky but important concept. Every variable in PHP has a scope to it, which is to say a realm in which the variable (and therefore its value) can be accessed. For starters, variables have the scope of the page in which they reside. So if you define $var, the rest of the page can access $var, but other pages generally cannot (unless you use special variables). Since included files act as if they were part of the original (including) script, variables defined before the include() line are available to the included file. Further, variables defined within the included file are available to the parent (including) script after the include() line. Pengaturcaraan PHP All of this becomes murkier when using your own defined functions. These functions have their own scope, which means that variables used within a function are not available outside of it, and variables defined outside of a function are not available within it. For this reason, a variable inside of a function can have the same name as one outside of it and still be an entirely different variable with a different value. This is a confusing concept for most beginning programmers. 31
  • 32. Pengaturcaraan PHP To alter the variable scope within a function, you can use the global statement. In this example, $var inside of the function is now the same as $var outside of it. This means that the function $var already has a value of 20, and if that value changes inside of the function, the external $var's value will also change. Pengaturcaraan PHP 32
  • 35. Date and Time Functions Pengaturcaraan PHP Pengaturcaraan PHP PHP has several date- and time-related functions for use in your scripts. The most important of these is the aptly named date() function, which returns a string of text for a certain date and time according to a format you specify. The timestamp is an optional argument representing the number of seconds since the Unix Epoch (midnight on January 1, 1970) for the date in question. It allows you to get information, like the day of the week, for a particular date. If a timestamp is not specified, PHP will just use the current time on the server. 35
  • 36. Pengaturcaraan PHP There are myriad formatting parameters available, and these can be used in conjunction with literal text. For example, Character Meaning Example Y year as 4 digits 2005 y year as 2 digits 05 n month as 1 or 2 digits 2 m month as 2 digits 02 F month February M month as 3 letters Feb j day of the month as 1 or 2 digits 8 d day of the month as 2 digits 08 l (lowercase L) day of the week Monday D day of the week as 3 letters Mon g hour, 12-hour format as 1 or 2 digits 6 G hour, 24-hour format as 1 or 2 digits 18 h hour, 12-hour format as 2 digits 06 H hour, 24-hour format as 2 digits 18 i minutes 45 s seconds 18 a am or pm am A AM or PM PM 36
  • 37. Pengaturcaraan PHP You can find the timestamp for a particular date using the mktime() function. Pengaturcaraan PHP Finally, the getdate() function can be used to return an array of values for a date and time. For example, This function also takes an optional timestamp argument. If that argument is not used, getdate() returns information for the current date and time. 37
  • 38. Pengaturcaraan PHP The getdate() function returns this associative array. Key Value Example year year 2005 mon month 12 month month name December mday day of the month 25 weekday day of the week Sunday hours hours 11 minutes minutes 56 seconds seconds 47 Pengaturcaraan PHP 38
  • 42. Pengaturcaraan PHP Date – “time()” To display current time and date Syntax : time(); Example : echo time(); Output = 23 // sample output: 1060751270 //this represent August 12th, 2003 at 10:07PM Pengaturcaraan PHP Date – “mktime” To display date and time in timestamp Syntax : mktime(); Example : echo mktime(); or $tarikh = $mktime(4,15,0,8,23,2003); $tarikh = date(“d/m/Y”,mktime()+50); 42
  • 43. Pengaturcaraan PHP Others Syntax : $tomorrow = mktime (0,0,0,date("m") ,date("d")+1,date("Y")); $lastmonth = mktime (0,0,0,date("m")-1,date("d"), date("Y")); $nextyear = mktime (0,0,0,date("m"), date("d"), date("Y")+1); Sending Email Pengaturcaraan PHP 43
  • 44. Pengaturcaraan PHP Using PHP makes sending email very easy. On a properly configured server, the process is as simple as using the mail() function. The $to value should be an email address or a series of addresses, separated by commas. The $subject value will create the email's subject line, and $body is where you put the contents of the email. Use the newline character (n) within double quotation marks when creating your body to make the text go over multiple lines. Pengaturcaraan PHP The mail() function takes a fourth, optional parameter for additional headers. This is where you could set the From, Reply-To, Cc, Bcc, and similar settings. For example, 44
  • 45. Pengaturcaraan PHP To use multiple headers of different types in your email, separate each with rn: Pengaturcaraan PHP 45