Intro to PHP and MySQL

Class 2

Review

  • <?php and .php files
  • Printing to screen
  • Variables
  • Types
  • Constants
  • Arithmetic
  • Conditionals
  • Arrays
  • Includes
  • Loops
  • Templating

Our creation

Looks exactly the same but less repeated code

Functions

Reusable pieces of code


Current code

index.php
 <article class="woman">
  <h3>
    <a href="http://en.wikipedia.org/wiki/Ada_Lovelace">Ada Lovelace</a>
  </h3>

  <h4>(1815&ndash;1852)</h4>
  <img src="images/ada_lovelace.jpg" alt="Ada Lovelace" />
  <p>An analyst of Charles Babbage's analytical engine and is often
    described as the "first computer programmer."</p>
</article>

<article class="woman">
  <h3>
    <a href="http://en.wikipedia.org/wiki/Grace_Hopper">Grace Hopper</a>
  </h3>
  <h4>(1906&ndash;1992)</h4>
  <img src="images/grace_hopper.jpg" alt ="Grace Hopper" />
  <p>A United States Navy officer and the first programmer of the
    Harvard Mark I, known as the "Mother of COBOL". She developed the
    first ever compiler for an electronic computer, known as A-0.</p>
</article>
Notice the same structure just repeated?

Turn the pattern into a function


index.php

<section id="famous">
  <a name="famous"></a>
  <h2>Famous Women</h2>
  <a class="jump up" href="#">&igrave;</a>
  <a class="jump down" href="#organizations">&iacute;</a>
  <div class = "wrapper">
  
    <?php echo viewWoman('Ada Lovelace',
                        'http://en.wikipedia.org/wiki/Ada_Lovelace',
                        '(1815&ndash;1852)',
                        'images/ada_lovelace.jpg',
                        'An analyst of Charles Babbage\'s analytical engine and is often
                          described as the "first computer programmer."'); ?>
  
    <?php echo viewWoman('Grace Hopper',
                        'http://en.wikipedia.org/wiki/Grace_Hopper',
                        '(1906&ndash;1992)',
                        'images/grace_hopper.jpg',
                        'A United States Navy officer and the first programmer of the
                          Harvard Mark I, known as the "Mother of COBOL". She developed the
                          first ever compiler for an electronic computer, known as A-0.'); ?>
  </div>
</section>

Defining the function


functions.php
 <?php
function viewWoman($name, $url, $years_lived, $image_url, $biography)
{
    return '<article class="woman">
            <h3><a href="' . $url . '">' . $name . '</a></h3>
            <h4>' . $years_lived . '</h4>
            <img src="' . $image_url . '" alt="' . $name . '" />
            <p>' . $biography . '</p>
          </article>';
}

Useful functions


explode
implode
trim
str_replace
htmlentities
filter_input
urlencode
htmlspecialchars
func_get_args
glob
...



Arguments


<?php

$class = 'Girl Develop It';

function WhereAmI($class){
  return 'I am in the ' . $class . ' class.';
}

echo WhereAmI($class); // I am in the Girl Develop It class.

echo WhereAmI('Math'); // I am in the Math class.

echo WhereAmI(); // Error
<?php
function WhereAmI($class, $location = 'Detroit'){
  $using = 'a computer;

  return 'I am in the ' . $class . ' class in ' . $location . ', using ' . $using . '.';
}

echo WhereAmI($class); // I am in the Girl Develop It class in Detroit, using a computer.

Variable scope


 <?php

$global_variable = 'Some data';

function MyFunction($argument1, $argument2) {
  $local_variable = $argument1 + $argument2;

  return $local_variable;
}

Let's try it


There seems to be a lot of repeated code in the site.



Task:


Can you find this duplicate code and remove it?

Superglobals


$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV


Classes & Objects


Reusable and extendable representations of things.


Conceptually, a class represents an object, with associated methods and variables


Functions vs Classes


function: 
function my_func($arg1,$arg2) {
  << function statements >>
  return $value;
}
Reusable & local scope

class:
<?php
class Dog {
  public $name;

  public function bark() {
    echo 'Woof!';}
  }
} 
Single attribute, '$name'. Can perform the action of barking.

Using classes


<?php
require_once(‘dog.class.php’);

$puppy = new Dog();
$puppy->name = 'Rover';

echo "{$puppy->name} says ";
$puppy->bark();

Inheritance


<?php

class Poodle extends Dog {
  public $type

  public function set_type($height)
  {
    if ( $height < 10 )
    { 
      $this->type = ‘Toy’;
    }
    elseif ( $height > 15 ) 
    {
      $this->type = ‘Standard’;
    }
    else 
    {
      $this->type = ‘Miniature’;
    }
  }
}

Example


<?php

$puppy = new poodle(‘Oscar’);

$puppy->set_type(12); // 12 inches high!

echo “Poodle is called {$puppy->name}, ”;

echo “of type {$puppy->type}, saying “;

echo $puppy->bark();

…

Extending the example

<?php

class Dog {
  ...

  public function bark() {
    echo 'Woof!';}
  }
} 

<?php

class Poodle extends Dog {
  ...

  public function bark() {
    echo ‘Yip!’;
  }
}

"Poodle is called Oscar, of type Standard, saying Yip!"

Deleting objects


Objects will not be deleted until the script has completed.

It is possible to delete the objects, like any other variable, using the 'unset()' function.

<?php

unset($puppy);
?>

Namespaces


<?php

// Some class included with a framework
class File {
  ...
}
<?php


// Your local file class
class File {
  ...
}

$myFile = new File; // Problem


Namespace


<?php

// Some class included with a framework
class File {
  ...
}
<?php

// Your local file class
namespace Acme;

class File {
  ...
}

$myFile = new Acme\File; // Your local File class

$theirFile = new \File; // The framework File class

Why use objects?


  1. Easier to maintain
    Logical grouping of functions
  2. Extending code is easier
  3. Packaging functionality for re-use is possible


Error Handling


<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL ^ E_NOTICE);

// Report ALL PHP errors
error_reporting(E_ALL);
?>

Hiding errors is NOT a solution to a problem. 

Error suppression


<?php

/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");



Halting the script is NOT a solution to a problem. 

Exceptions


<?php

try {

    if ( ($fp = @fopen($filename, "r")) == false)
    {
        throw new Exception;
    }
    

    do_file_stuff($fp);

} catch (Exception $e) {
    
    handle_exception();
}


Exception class


<?php
Exception {

  /* Properties */
  protected string $message ;
  protected int $code ;
  protected string $file ;
  protected int $line ;

  /* Methods */
  public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
  public string getMessage ( void )
  public Exception getPrevious ( void )
  public mixed getCode ( void )
  public string getFile ( void )
  public int getLine ( void )
  public array getTrace ( void )
  public string getTraceAsString ( void )
  public string __toString ( void )
  private void __clone ( void )
}

Forms



RESTful Resources



Form tag



<form method="get" action="search.php">
  ...
</form>

Input tag


<input type="text" name="first_name">

<textarea name="comment" id="comment" cols="50" rows="4">

<input type="submit" name="submit" id="submit-button" value="Submit" />

Form flow


Form on page

User input

Clean

Process

Display results

Adding search

<?php
// Do search
if ( isset($_GET['q']) )
{
  $results = DoSearch($_GET['q']);
}
...
...
<form method="get" action="search.php">
  <label for="q">Search</label>
  <input type="input" name="q" id="q" value="" />
  <input type="submit" value="Search" />
</form>
...
<section class="results">
<?php 
  echo '<p>Results for: ' . $_GET['q'] . '</p>';
  foreach ( $results as $result )
  {
    ViewResult($result);
  }
?>

Avoiding XSS


What about the following search term?


filter_input()


<?php

$search_term = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS);

?>

echo $_GET['q']
<script>alert('Xss');</script>

echo $search_term
&#60;script&#62;alert(&#39;Xss&#39;);&#60;/script&#62;

Search an array


<?php

// If trying to search
if ( isset($_GET['q']) )
{
    $search_term = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS);

    if ( is_array($women) )
    {
      foreach ($women as $woman)
      {
          if ( stristr($women['name'], $search_term) )
          {
            $results[] = $women;
          }
      }
    }
}

Display the results


<?php if ( isset($search_term) ) { ?>
  <section class="results">
    <p>Results for: <?php echo $search_term; ?></p>

    <?php
      foreach ($results as $woman)
      {
        echo viewWoman($woman['name'], $woman['link'], $woman['years'], $woman['image'], $woman['biography']);
       }
     ?>
  </section>
<?php } ?>

Validation



<?php

$clean = array();

if (ctype_alnum($_POST['username']))
{
  $clean['username'] = $_POST['username'];
}


ctype functions


  • ctype_alnum — Check for alphanumeric character(s)
  • ctype_alpha — Check for alphabetic character(s)
  • ctype_cntrl — Check for control character(s)
  • ctype_digit — Check for numeric character(s)
  • ctype_graph — Check for any printable character(s) except space
  • ctype_lower — Check for lowercase character(s)
  • ctype_print — Check for printable character(s)
  • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
  • ctype_space — Check for whitespace character(s)
  • ctype_upper — Check for uppercase character(s)
  • ctype_xdigit — Check for character(s) representing a hexadecimal digit

Scenario:

Someone want to suggest a women in tech


Task:

Add a suggestion form to the website that 

PHP & MySQL - Class 2 - Girl Develop It

By Nick DeNardis

PHP & MySQL - Class 2 - Girl Develop It

  • 1,587