SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
PHP Basics
●   We will look at the language more formally later.
●   For now
–become       familiar with the programming model
–get    familiar with server-side programming
–get    used to handling form submission




                          PHP Basics                    1
PHP: Hypertext Preprocessor

          Some References:


           www.php.net

        www.w3schools.com

http://www.oreillynet.com/pub/ct/29


                PHP Basics            2
A PHP Program
●   contained in an HTML document.
●   All code is found inside:
            <?php        ...          ?> tags.
●   conditional HTML
    –you can have PHP control what HTML actually
     makes it to the output document.
    <?php if (foo) { ?>
         <h3> foo is true!</h3>
    <?php else ?>
         <h3> foo is false!</h3>
                         PHP Basics                3
Web Server and PHP
●   A client sends a request to a server, perhaps:
           GET /myprog.php HTTP/1.1
●   The server must be configured to recognize that
    the request should be handled by PHP.
●   PHP reads the document myprog.php and
    produces some output (which is typically
    HTML).
    –   all normal HTML tags are output without
        modification.
                            PHP Basics               4
Our first PHP program?
<html>
<head>
<title>I am a PHP program</title>
</head>
<body>
<h3>PHP can handle HTML</h3>
</body>
</html>




               PHP Basics           5
A better example – try this
<html>
<head>
<title>I am a PHP program</title>
</head>
<body>
<?php phpinfo(); ?>
</body>
</html>




               PHP Basics
Server-side programming
●   This is not like JavaScript
    –   the browser does not understand PHP.
●   You have to use a web server that supports
    php.
    –   php preprocesses a file that contains HTML and
        code, and generates pure HTML (could actually be
        anything that the browser can understand).
    –   If you “view source” in the browser, you can't tell the
        page was produced by php.

                             PHP Basics                       7
The Language in one slide
●   Similar syntax to C/C++/Javascript
    –   statements end with ';'
    –   if, while, for, ... all just like we are used to.
    –   assignment statements are the same.
●   Variables are untyped (like Javascript)
    –   can create a new variable by assigning a value.
    –   variable names start with '$'
●   arrays are different (associative arrays), but
    easy to get used to.
                                PHP Basics                  8
Generating HTML
●   You can use functions echo , print and/or
    printf to generate HTML:
<?php
echo("<h3>Dynamic H3 tag</h3>");
print("<p>a paragraph produced with the print
  function</p>");
printf("<p>printf %s, works as well</p>n",
       "(from C)");
?>


                       PHP Basics               9
Jump right in!
<h3>Here are some lines</h3>
<?php                 variable names start with $
                      variables don't need to be declared.
echo "<p>";
for ($i=0;$i<10;$i++) {
    echo "line " . $i . "<br>";
}
echo "</p>";          string concatenation operator!

?>


                      PHP Basics                             10
First Exercise
                                        i              2i
                                        ----------------------------------
●   Create a PHP script that produces   1              2
    an HTML table with the first 10     2              4
                                        3              8
    powers of two.                      4              16
●   You need to use the pow()           5              32
                                        6              64
    function:                           7              128
                                        8              256
    –   pow(x,y) = xy                   9              512
                                        10             1024




                         PHP Basics                                      11
Non-obvious solution?
<table border=1>
<tr>
  <th>i</th>
  <th>2<sup>i</sup></th>
</tr>
<?php for ($i=1;$i<=10;$i++) { ?>
<tr>
  <td> <?php echo($i); ?></td>
  <td> <?php echo pow(2,$i);?></td>
</tr>
<?php } ?>
</table>
                     PHP Basics       12
PHP style
●   some PHP programmers think:
    –   "I have an HTML document and I can add little bits
        of PHP code in special places"
●   some others think:
    –   "I have a PHP document in which I can add a few
        HTML tags".

●   Use whatever style seems most comfortable to
    you.
                            PHP Basics                       13
PHP and forms
●   Recall that an HTML form submission looks
    something like this (GET method):
     GET /somefile?x=32&name=Joe+Smith
●   Typically a PHP script wants to get at the
    values the user typed into the form.
    –   often the form itself came from a php script.




                             PHP Basics                 14
Form example
<form method="GET" action="form.php">
<p>
First Name: <input type="text" name="first"><br>
Last Name: <input type="text" name="last"><br>
<input type="submit">
</p>
</form>




                        PHP Basics                 15
Receiving the submission
●   You can put the form in a file named "form.php",
    and set the action to also be "form.php".
    –   The php file will receive the submission itself
    –   You could also leave off the action attribute

●   Unless we add some php code, all that will
    happen when the form is submitted is that we
    get a new copy of the same form.


                             PHP Basics                   16
Form Fields and PHP
●   PHP takes care of extracting the individual form
    field names and values from the query.
    –   also does urldecoding for us.
●   A global variable named $_REQUEST holds all
    the form field names and values.
    –   this variable is an associative array – the keys
        (indicies) are the form field names.




                             PHP Basics                    17
Getting the values
●   To get the value the user submitted for the field
    named "first":
                  $_REQUEST['first']


●   To get the value the user submitted for the field
    named "last":
                  $_REQUEST['last']



                         PHP Basics                 18
Adding some PHP to the form
●   We could simply print out the values entered
    (as HTML):
<?php
    echo "<p>First name is ";
    echo   $_REQUEST['first'] . "</p>";


    echo "<p>Last name is ";
    echo $_REQUEST['last'] . "</p>";
?>

                         PHP Basics                19
Or do it like this
<p>First name is <?php echo $_REQUEST['first'] ?>
</p>


<p>Last name is <?php echo $_REQUEST['last'] ?>
</p>




                     PHP Basics                   20
Make a php form handler
<form method="GET" action="form.php">
<p>First Name: <input type="text" name="first"><br>
   Last Name: <input type="text" name="last"><br>
   <input type=submit>
</p></form>
<?php
 echo "<p>First name is ";
 echo $_REQUEST['first'] . "</p>";

 echo "<p>Last name is ";
 echo $_REQUEST['last'] . "</p>";
?>

                         PHP Basics                   21
Looking for Joe Smith
●   We can easily turn this into a primitive login
    system.
    –   we only allow Joe Smith to login
    –   If the name is not Joe Smith, we send back the form
        along with a rude message.
●   A real login system would not have the valid
    login names (passwords) hard-coded in the
    program
    –   probably coming from a database.

                            PHP Basics                    22
Login handling form

<?php
 if (($_REQUEST['first'] == "joe") &&
     ($_REQUEST['last'] == "smith")) {
    echo "<p>Welcome back joe</p>;
 } else {
    ?>
   <p>You are not the correct person.</p>
   <p>Try again</p>
   <form method="GET" action="form.php">
   <p>First Name: <input type="text" name="first"><br>
   Last Name: <input type="text" name="last"><br>
   <input type=submit>
   </p></form>            PHP Basics                   23
<?php } ?>
Exercise
●   Create a php script with a form where the user
    enters a number between 1 and 10.
●   If they guess correctly, tell them!
●   If they guess wrong – send the form back.

●   Play with your php program directly (skipping
    the form) by constructing URLs manually.


                          PHP Basics                 24

Mais conteúdo relacionado

Mais procurados

Php hypertext pre-processor
Php   hypertext pre-processorPhp   hypertext pre-processor
Php hypertext pre-processor
Siddique Ibrahim
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
Niit
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 

Mais procurados (20)

Php introduction
Php introductionPhp introduction
Php introduction
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
Php
PhpPhp
Php
 
01 Php Introduction
01 Php Introduction01 Php Introduction
01 Php Introduction
 
Php hypertext pre-processor
Php   hypertext pre-processorPhp   hypertext pre-processor
Php hypertext pre-processor
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Overview of PHP and MYSQL
Overview of PHP and MYSQLOverview of PHP and MYSQL
Overview of PHP and MYSQL
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Software Design
Software DesignSoftware Design
Software Design
 
php
phpphp
php
 
Welcome to computer programmer 2
Welcome to computer programmer 2Welcome to computer programmer 2
Welcome to computer programmer 2
 
Php introduction and configuration
Php introduction and configurationPhp introduction and configuration
Php introduction and configuration
 
Presentation php
Presentation phpPresentation php
Presentation php
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 

Semelhante a Phpbasics

Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
ShaimaaMohamedGalal
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
GiyaShefin
 
Article 01 What Is Php
Article 01   What Is PhpArticle 01   What Is Php
Article 01 What Is Php
drperl
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHP
Nat Weerawan
 

Semelhante a Phpbasics (20)

PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
PHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web DevelopmentPHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web Development
 
Day1
Day1Day1
Day1
 
Php
PhpPhp
Php
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
introduction_php.ppt
introduction_php.pptintroduction_php.ppt
introduction_php.ppt
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Php
PhpPhp
Php
 
Php modul-1
Php modul-1Php modul-1
Php modul-1
 
PHP-Part1
PHP-Part1PHP-Part1
PHP-Part1
 
Article 01 What Is Php
Article 01   What Is PhpArticle 01   What Is Php
Article 01 What Is Php
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
php 1
php 1php 1
php 1
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHP
 

Mais de PrinceGuru MS

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
PrinceGuru MS
 
Phpjedi 090307090434-phpapp01 2
Phpjedi 090307090434-phpapp01 2Phpjedi 090307090434-phpapp01 2
Phpjedi 090307090434-phpapp01 2
PrinceGuru MS
 
Php and-web-services-24402
Php and-web-services-24402Php and-web-services-24402
Php and-web-services-24402
PrinceGuru MS
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
PrinceGuru MS
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
Codeigniter 1.7.1 helper_reference
Codeigniter 1.7.1 helper_referenceCodeigniter 1.7.1 helper_reference
Codeigniter 1.7.1 helper_reference
PrinceGuru MS
 
Cake php 1.2-cheatsheet
Cake php 1.2-cheatsheetCake php 1.2-cheatsheet
Cake php 1.2-cheatsheet
PrinceGuru MS
 
Phpworks enterprise-php-1227605806710884-9
Phpworks enterprise-php-1227605806710884-9Phpworks enterprise-php-1227605806710884-9
Phpworks enterprise-php-1227605806710884-9
PrinceGuru MS
 

Mais de PrinceGuru MS (13)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Php security3895
Php security3895Php security3895
Php security3895
 
Phpjedi 090307090434-phpapp01 2
Phpjedi 090307090434-phpapp01 2Phpjedi 090307090434-phpapp01 2
Phpjedi 090307090434-phpapp01 2
 
Php and-web-services-24402
Php and-web-services-24402Php and-web-services-24402
Php and-web-services-24402
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
Php tizag tutorial
Php tizag tutorialPhp tizag tutorial
Php tizag tutorial
 
Drupal refcard
Drupal refcardDrupal refcard
Drupal refcard
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Codeigniter 1.7.1 helper_reference
Codeigniter 1.7.1 helper_referenceCodeigniter 1.7.1 helper_reference
Codeigniter 1.7.1 helper_reference
 
Class2011
Class2011Class2011
Class2011
 
Cake php 1.2-cheatsheet
Cake php 1.2-cheatsheetCake php 1.2-cheatsheet
Cake php 1.2-cheatsheet
 
Phpworks enterprise-php-1227605806710884-9
Phpworks enterprise-php-1227605806710884-9Phpworks enterprise-php-1227605806710884-9
Phpworks enterprise-php-1227605806710884-9
 
Firstcup
FirstcupFirstcup
Firstcup
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Phpbasics

  • 1. PHP Basics ● We will look at the language more formally later. ● For now –become familiar with the programming model –get familiar with server-side programming –get used to handling form submission PHP Basics 1
  • 2. PHP: Hypertext Preprocessor Some References: www.php.net www.w3schools.com http://www.oreillynet.com/pub/ct/29 PHP Basics 2
  • 3. A PHP Program ● contained in an HTML document. ● All code is found inside: <?php ... ?> tags. ● conditional HTML –you can have PHP control what HTML actually makes it to the output document. <?php if (foo) { ?> <h3> foo is true!</h3> <?php else ?> <h3> foo is false!</h3> PHP Basics 3
  • 4. Web Server and PHP ● A client sends a request to a server, perhaps: GET /myprog.php HTTP/1.1 ● The server must be configured to recognize that the request should be handled by PHP. ● PHP reads the document myprog.php and produces some output (which is typically HTML). – all normal HTML tags are output without modification. PHP Basics 4
  • 5. Our first PHP program? <html> <head> <title>I am a PHP program</title> </head> <body> <h3>PHP can handle HTML</h3> </body> </html> PHP Basics 5
  • 6. A better example – try this <html> <head> <title>I am a PHP program</title> </head> <body> <?php phpinfo(); ?> </body> </html> PHP Basics
  • 7. Server-side programming ● This is not like JavaScript – the browser does not understand PHP. ● You have to use a web server that supports php. – php preprocesses a file that contains HTML and code, and generates pure HTML (could actually be anything that the browser can understand). – If you “view source” in the browser, you can't tell the page was produced by php. PHP Basics 7
  • 8. The Language in one slide ● Similar syntax to C/C++/Javascript – statements end with ';' – if, while, for, ... all just like we are used to. – assignment statements are the same. ● Variables are untyped (like Javascript) – can create a new variable by assigning a value. – variable names start with '$' ● arrays are different (associative arrays), but easy to get used to. PHP Basics 8
  • 9. Generating HTML ● You can use functions echo , print and/or printf to generate HTML: <?php echo("<h3>Dynamic H3 tag</h3>"); print("<p>a paragraph produced with the print function</p>"); printf("<p>printf %s, works as well</p>n", "(from C)"); ?> PHP Basics 9
  • 10. Jump right in! <h3>Here are some lines</h3> <?php variable names start with $ variables don't need to be declared. echo "<p>"; for ($i=0;$i<10;$i++) { echo "line " . $i . "<br>"; } echo "</p>"; string concatenation operator! ?> PHP Basics 10
  • 11. First Exercise i 2i ---------------------------------- ● Create a PHP script that produces 1 2 an HTML table with the first 10 2 4 3 8 powers of two. 4 16 ● You need to use the pow() 5 32 6 64 function: 7 128 8 256 – pow(x,y) = xy 9 512 10 1024 PHP Basics 11
  • 12. Non-obvious solution? <table border=1> <tr> <th>i</th> <th>2<sup>i</sup></th> </tr> <?php for ($i=1;$i<=10;$i++) { ?> <tr> <td> <?php echo($i); ?></td> <td> <?php echo pow(2,$i);?></td> </tr> <?php } ?> </table> PHP Basics 12
  • 13. PHP style ● some PHP programmers think: – "I have an HTML document and I can add little bits of PHP code in special places" ● some others think: – "I have a PHP document in which I can add a few HTML tags". ● Use whatever style seems most comfortable to you. PHP Basics 13
  • 14. PHP and forms ● Recall that an HTML form submission looks something like this (GET method): GET /somefile?x=32&name=Joe+Smith ● Typically a PHP script wants to get at the values the user typed into the form. – often the form itself came from a php script. PHP Basics 14
  • 15. Form example <form method="GET" action="form.php"> <p> First Name: <input type="text" name="first"><br> Last Name: <input type="text" name="last"><br> <input type="submit"> </p> </form> PHP Basics 15
  • 16. Receiving the submission ● You can put the form in a file named "form.php", and set the action to also be "form.php". – The php file will receive the submission itself – You could also leave off the action attribute ● Unless we add some php code, all that will happen when the form is submitted is that we get a new copy of the same form. PHP Basics 16
  • 17. Form Fields and PHP ● PHP takes care of extracting the individual form field names and values from the query. – also does urldecoding for us. ● A global variable named $_REQUEST holds all the form field names and values. – this variable is an associative array – the keys (indicies) are the form field names. PHP Basics 17
  • 18. Getting the values ● To get the value the user submitted for the field named "first": $_REQUEST['first'] ● To get the value the user submitted for the field named "last": $_REQUEST['last'] PHP Basics 18
  • 19. Adding some PHP to the form ● We could simply print out the values entered (as HTML): <?php echo "<p>First name is "; echo $_REQUEST['first'] . "</p>"; echo "<p>Last name is "; echo $_REQUEST['last'] . "</p>"; ?> PHP Basics 19
  • 20. Or do it like this <p>First name is <?php echo $_REQUEST['first'] ?> </p> <p>Last name is <?php echo $_REQUEST['last'] ?> </p> PHP Basics 20
  • 21. Make a php form handler <form method="GET" action="form.php"> <p>First Name: <input type="text" name="first"><br> Last Name: <input type="text" name="last"><br> <input type=submit> </p></form> <?php echo "<p>First name is "; echo $_REQUEST['first'] . "</p>"; echo "<p>Last name is "; echo $_REQUEST['last'] . "</p>"; ?> PHP Basics 21
  • 22. Looking for Joe Smith ● We can easily turn this into a primitive login system. – we only allow Joe Smith to login – If the name is not Joe Smith, we send back the form along with a rude message. ● A real login system would not have the valid login names (passwords) hard-coded in the program – probably coming from a database. PHP Basics 22
  • 23. Login handling form <?php if (($_REQUEST['first'] == "joe") && ($_REQUEST['last'] == "smith")) { echo "<p>Welcome back joe</p>; } else { ?> <p>You are not the correct person.</p> <p>Try again</p> <form method="GET" action="form.php"> <p>First Name: <input type="text" name="first"><br> Last Name: <input type="text" name="last"><br> <input type=submit> </p></form> PHP Basics 23 <?php } ?>
  • 24. Exercise ● Create a php script with a form where the user enters a number between 1 and 10. ● If they guess correctly, tell them! ● If they guess wrong – send the form back. ● Play with your php program directly (skipping the form) by constructing URLs manually. PHP Basics 24