Skip to content

Lecture Notes - Week 2

Readings

  • Chapters:
    • 2 - Writing Your First PHP Script (pgs. 19 - 21)
    • 3 - Why Variables Matter
    • 4 - Basic String Interpretation
    • 8 - Verifying Variables and Type Checking (pgs. 68 - 71)
    • 11 - Working with HTML Forms (pgs. 89 - 92)
    • 12 - Inserting Data Into a MySQL Database

Screencast - Week 2

Outline of Topics

  • Getting Started with PHP
  • Introduction to Data Types
  • Variables
  • Constants
  • Using HTML Forms and Form Variables
  • PHP Coding Rules
  • $_POST Superglobal
  • Adding data to a database using a form and mysqli

Lecture

Getting Started with PHP

Mixing in PHP

  • Here's a trivial example of using PHP to generate the text for the header:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  <html>
    <head><title>Mixing HTML and PHP</title></head>
    <body>
    <div class='main'>
      <h1>
        <?php
            print "It's such a perfect day!";
        ?>
      </h1>
      <p>Some paragraph text.</p>
    </div>
    </body>
  </html>

Mixing in PHP (Bad Example)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<html>
   <head><title>Mixing HTML and PHP</title></head>
   <body>
   <div class='main'>
      <?php 
          print "<h1>It's such a perfect day!</h1>"; 
      ?>
      <p>Some paragraph text.</p>
    </div>
   </body>
</html>

Commenting your code

  • We all write code for a reason, we may need at times to share WHY something is the way it is.
1
2
3
4
5
6
7
8
9
<?php
    //Single line comment
    # Also a single line comment
    phpinfo(); //comment after code
    /*
    Multi line block, you can add as many
    lines as you want, but don't write a book
    */
?>
  • Commenting your code (bad)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
    /*
    We are formating phone numbers by stripping all characters
    then putting parens around the first 3 numbers adding a
    space then grouping the next 3 numbers adding a dash
    then the last 4 numbers
    */
    function formatPhoneNumber($phone_string){
        if(  preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches ) )
        {
            $result = "($matches[1]) $matches[2]-$matches[3]";
            return $result;
        }
    }
?>
- Commenting your code (good)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
    /*
    The business has a requirement that all phone numbers be
    formatted with the (123) 123-1234 format 
    */
    function formatPhoneNumber($phone_string){
        if(  preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches ) )
        {
            $result = "($matches[1]) $matches[2]-$matches[3]";
            return $result;
        }
    }
?>
  • The main block explains why

Introduction to Data Types

PHP supports the following fundamental basic data types, also known as scalar types:

What is the difference between Integers and Floats?
  • Integers are whole numbers Floats are fractional numbers (i.e. 1, 2, 3 vs. 1.5, 2.3, 6.6)
What is a String?

A group of characters enclosed in either single or double quotes

  • Quotes must match
1
2
3
4
"This is a string"
'This is also a string'
"This is 'actually' a string"
'This is another "example"'
The Here Document method of quoting strings
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
print <<<EOF
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vulputate, 
arcu a pellentesque viverra, elit metus pretium dui, nec congue ligula 
velit vitae nunc. Aliquam est elit, faucibus vitae tincidunt sed, venenatis 
vitae urna. Duis dignissim vel odio ac convallis. Suspendisse sodales viverra 
ante, in consectetur nulla finibus a. Integer faucibus auctor ipsum, nec 
tincidunt metus mattis id. Morbi non leo tristique, facilisis neque a, 
volutpat purus. Class aptent taciti sociosqu ad litora torquent per 
conubia nostra, per inceptos himenaeos.
EOF;
What is a Boolean?
  • A logical value that is either true or false

PHP supports the following composite data types:

Array
  • An Array is a collection of values
What is a NULL data type?
  • NULL represents a variable with no value
What is a Resource data type?
  • A reference to an external resource
  • Used for working with files and databases
What are Objects?
  • A way of representing every day data
  • We will introduce Objects in week 10

Debugging data types

gettype()

1
<?php gettype($myVariable); ?>

listings/datatypes.php

Variables

PHP supports the following kinds of variables:

  1. Predefined
  2. User-defined
  3. Form variables related to names in an HTML form

Valid variable names

  • All variables start with a $ followed by a letter or an _
1
2
3
4
5
$name1
$price_tag
$_abc
$Abc_22
$A23

Invalid variable names

1
2
3
4
5
$10names
box.front
$name#last
A-23
$5

Displaying Variables

listings/datatypes.php

String Interpolation or Concatenation

1
<?php echo "Hello $name_variable" ?>

or

1
<?php echo "Hello" . $name_variable ?>

Managing Variables

isset() is_int() is_scalar()
empty() is_integer() is_string()
is_bool() is_long() unset()
is_callable() is_null()
is_double() is_numeric()
is_float() is_object()
is_real() is_resource()

REMEMBER: All data entered into form fields has the data type of a String.

Constants

  • Constants are values that do not change
  • Named constatns are created in PHP using the define() function
1
2
define("BOILING_TEMP_IN_CELCIUS", 100);
echo BOILING_TEMP_IN_CELCIUS; // outputs 100

Using HTML Forms and Form Variables

Setting the form

listings/postform.html

  • Note the values of the name attributes in the form

Processing the form

listings/postformprocess.php

Cross-Site Request Forgery (CSRF)

  • More in week 10

OWASP CSRF Prevention Cheat Sheet

PHP Coding Rules

  • PHP code is always enclosed by <?php and ?>
1
2
3
4
5
<?php

...

?>
  • Every PHP statement must end with a semicolon ;
1
echo 'Thanks for submitting the form.';
  • If there is any PHP code in a web page, the file on the web server should be named with a .php extension, not .html
  • PHP variable names must begin with a dollar sign $
1
$email = $_POST['email'];
  • A variable name must be at least one character in length
  • The first character after the dollar sign $ can be a letter or an underscore _, and characters after that can be a letter, an underscore, or a number
  • Spaces and special characters other than _ and $ are not allowed in any part of a variable name

$_POST Superglobal

  • $_POST is a special variable, a superglobal built into PHP that holds form data, and is available throughout an entire script
  • $_POST is an array and you access the form data by using the name attributes as indexed keys into the array

An example would help. Here's a simple form:

  • fullname.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Simple Fullname form</title>
</head>
<body>
  <h2>Simple Fullname</h2>
  <form action="fullname.php" method="post">
    First Name: 
    <input type="text" id="firstname" name="firstname" /><br />
    Last Name: 
    <input type="text" id="lastname" name="lastname" /><br />
    <input type="submit" value="Report Full Name" name="submit" />
  </form>
</body>
</html>

The two name attributes in the form are: "firstname" and "lastname". You access the data in those name attributes by using "firstname" and "lastname" as indexed keys into the $_POST superglobal:

  • fullname.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<html>
<head>
  <title>Full Name</title>
</head>
<body>
  <h2>Full Name</h2>

<?php
    $first_name = $_POST['firstname'];
    $last_name  = $_POST['lastname'];

    echo "Hi " . $first_name . " " . $last_name . ". Thanks for submitting the form!";
?>
</body>
</html>

MySQL

  • databases
    • A MySQL sever can contain multiple databases
    • PHP can communicate easily with your database
  • tables

    • Each database can have multiple tables

    Demo Lab

Adding data to a database using a form and mysqli

  • We can use the same form above for entering a full name along with the database we created in the Demo Lab, however we will have to modify the PHP script to use the database

  • The first thing we will need to do is connect to the database in our PHP script using mysqli_connect()

1
2
$dbc = mysqli_connect('localhost', 'student', 'student', 'kemarks1')
    or die('Error connecting to MySQL server.');
  • Next, we build our query and store it to a variable
1
2
$query = "INSERT INTO fullname (first_name, last_name) " . 
    "VALUES ('$first_name', '$last_name')";
1
2
$result = mysqli_query($dbc, $query)
    or die('Error querying database.');
1
mysqli_close($dbc);
  • Here's the complete PHP script:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
  <title>Full Name</title>
</head>
<body>
  <h2>Full Name</h2>

<?php
    $first_name = $_POST['firstname'];
    $last_name  = $_POST['lastname'];

    $dbc = mysqli_connect('localhost', 'student', 'student', 'kemarks1')
        or die('Error connecting to MySQL server.');

    $query = "INSERT INTO fullname (first_name, last_name) " . 
           "VALUES ('$first_name', '$last_name')";


    $result = mysqli_query($dbc, $query)
        or die('Error querying database.');

    mysqli_close($dbc);

    echo "Hi " . $first_name . " " . $last_name . ". Thanks for submitting the form!";
?>
</body>
</html>

Week 2 Lab