Introduction

What is PHP?

  • Stands for PHP: Hypertext Preprocessor
     
  • Open source scripting language
     
  • PHP scripts are executed on the server
     
  • PHP is free to download and use
     
  • File extension is .php
     
  • Files can contain HTML, CSS, JavaScript and PHP

Examples what to use if for

  • Send an e-mail from a form
  • Redirect pages or users
  • Forums
  • Template your website
  • Content Management Systems (CMS)
  • Generating PDF files
  • Parsing XML files
  • Encrypt data

Benefits of PHP

  • Easy to learn
     
  • Open source, free to use
     
  • Supports a wide range of databases
     
  • Compatible with almost all servers
     
  • Can run on various platforms

Syntax basics

<?php // PHP inside a HTML page ?>
<!DOCTYPE html>
<html lang="en">
    <head>
    </head>
    <body>
    
        <h1>This is a HTML page</h1>
    
        <?php
            // Print 'Hello World!' on the HTML page
            echo "Hello World!";
        ?>
    </body>
</html>

Where to place?

  • In separate PHP files
     
  • Included in HTML
<?php

    // This is a single-line comment
    
    # This is a single-line comment
    
    /*
        This is a multiple-lines 
        comment block that uses 
        multiple lines
    */
    
    // Inline comment
    $total = 2 /* + 3 */ + 4;

?>

Comments

  • Short concreet description of your code
     
  • Support yourself and others while working on code

Variables

What is a variable?

  • Keeps track of information in a program
     
  • Containers for storing data values
     
  • Can hold many data types: numbers, strings, arrays and many more
     
  • Starts with the $ sign, followed by the name of the variable
<?php
    
    $count = 12;

    $name = 'John Doe';

?>

Rules declaring a variable

  • Starts with $ sign, followed by the name of the variable
     
  • Cannot start with a number
     
  • Has to start with a letter or underscore
     
  • Can only contain A-z, 0-9, and _
     
  • Are case-sensitive

Superglobals

  • They are always accessible, regardless of scope, you can access them from any function, class or file
     
  • $_COOKIE
    $_ENV
    $_FILES
    $_GET
    $GLOBALS
    $_POST
    $_REQUEST
    $_SERVER
    $_SESSION

Datatypes

String

  • A sequence of characters
     
  • You can use single or double quotes
<?php
    
    // Single quotes
    echo 'Hello world!';

    // Double quotes
    echo "Hello world!";

?>

Integer

  • A non-decimal number between -2,147,483,648 and 2,147,483,647
     
  • Can be either positive or negative
     
  • Can be specified in three formats:
    • decimal
    • hexadecimal
    • octal
<?php

    $total = 23654;

?>

Float

  • A number with a decimal point or a number in exponential form
<?php

    $total = 23.654;

?>

Boolean

  • Can either be true or false
     
  • Often used in conditional testing
<?php

    $outcome1 = true;
    $outcome2 = false;

?>

Array

  • Can store multiple values in one variable
<?php

    // Create an Array
    array();


    // Example of an Array
    $music = array("Rock","Hardstyle","R&B");


    // Check the length of an Array
    echo count($music); // Output is: 3


    // Associative Array
    $hobbies = array("John"=>"Travelling", "Jane"=>"Kickboxing", "Joe"=>"Gaming");

?>

Object

  • Stores data and information on how to process that data
<?php

    // Declare a class of Object
    class Team {
        function Team() {
            $this->developer = "John Doe";
        }
    }


    // Create an Object
    $dev = new Team();


    // Show properties of Object
    echo $dev->developer; // Output is: John Doe

?>

NULL

  • Can have only one value: NULL
<?php

    // Empty variable will have NULL as value
    $total;


    // Empty a variable and set to NULL
    $total = 10;
    $total = null;

?>

Statements

Echo

  • Can be used with or without parentheses
     
  • Has no return value
     
  • Can take multiple parameters
<?php

    echo "Hello world!";

?>

Print

  • Has a return value of 1
     
  • Can be used in expressions
     
  • Can only take one argument
     
  • Slower than echo()
<?php

    print "Hello world!";

?>

If/else/elseif

<?php

    // If statement
    if (condition) {
        // Code gets executed if condition is true
    }


    // If else statement
    if (condition) {
        // Code gets executed if condition is true
    } else {
        // Code gets executed if the other conditions are false
    }
    

    // If elseif else statement    
    if (condition) {
        // Code gets executed if condition is true
    } elseif (condition) {
        // Code gets executed if condition is true
    } else {
        // Code gets executed if the other conditions are false
    }

?>

Switch

<?php

    switch ($block) {
        case option1:
            // Code gets executed if $block = option1
            break;
        case option2:
            // Code gets executed if $block = option2
            break;
        case option3:
            // Code gets executed if $block = option3
            break;
        default:
            // Code gets executed if $block is different than the rest
    }

?>
  • Uses the break to prevent the code from running into the next case automatically

Loops

While loop

  • The loop will continue to run as long as the condition is true
<?php

    while (condition is true) {
        // Code gets executed
    }

?>

For loop

  • Initialise the loop counter value
     
  • Evaluated for each loop iteration. If true then continue else it stops
     
  • Increases the loop counter value
<?php

    for (init counter; test counter; increment counter) {
        // Code gets executed
    }

?>

Do while

  • The condition is tested AFTER executing the statements within the loop
<?php
    
    do {
        // Code gets executed
    } while (condition is true);

?>

Foreach

  • Works only on arrays
     
  • Loops through each key/value pair in an array
<?php
    
    foreach ($array as $value) {
        // Code gets executed
    }

?>

Functions

What is a function?

  • A block of statements that can be re-used
     
  • Only executes when it gets called
     
  • A function name can start with a letter or underscore
     
  • Can use arguments to pass information on
<?php

    function functionName($argument1, $argument2) {
        // Do something, for example:
        echo "$argument1 loves $argument2";
    }

    // Call the function
    functionName("John", "traveling");
    functionName("Jane", "horse riding");

?>

Include & require

What are they?

  • Statements that are identical except upon failure ​
     
  • Statements that give you the option to insert a PHP file into another
     
  • Saves work by creating standard files
     
  • Possible to include files that are required for the application to run

Differences

<?php

    // Will only produce a warning and continues running
    // File is not required and application should continue when file is not found
    include 'filename.php';

?>
<?php

    // Will produce a fatal error and stops running the script
    // Use require when the file is required by the application
    require 'filename.php';

?>

Manipulating files

Why?

  • You often have to open and close files, easy to do with file functions
     
  • Makes it easier to process tasks on files, e.g.:
    • reading
    • creating
    • opening
    • (over)writing
    • closing

File functions

<?php

    // Reads a file and writes it to the output buffer
    echo readfile();

    // Similar to readfile() but gives you more options by using parameters
    // Will create a file if it doesn't exist yet
    echo fopen();
    
    // Reads from an open file, using parameters to specify max number of bytes to read
    echo fread();
    
    // Is used to close an open file
    echo fclose();
    
    // Is used to read a single line from a file
    echo fgets();
    
    // checks if the "end-of-file" (EOF) has been reached, can be used to loop through data
    echo feof();
    
    // Reads a single character from a file
    echo fgetc();
    
    // Is used to write to a file by using parameters
    echo fwrite();

?>

Cookies

What is a cookie?

  • A small file that gets embedded on a user's computer by the server
     
  • Used to identify a user
     
  • With PHP you can create and retrieve cookies

setcookie() function

  • Used to create a cookie
     
  • Has optional parameters, only "name" is required
     
  • Must appear before the html tag
<?php

    setcookie(name, value, expire, path, domain, secure, httponly);

?>
<?php
    $cookie_name = "admin";
    $cookie_value = "John Doe";
    // Create cookie with name and value, expire after 30 days, available entire app
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Example Cookies</title>
    </head>
    <body>
    
        <?php
            // Use $_COOKIE global to retrieve value of cookie "admin"
            if(!isset($_COOKIE[$cookie_name])) {
                echo "Fail!";
            } else {
                echo "Cookie '" . $cookie_name . "' is set!";
                echo "Value is: " . $_COOKIE[$cookie_name];
            }
        ?>
    
    </body>
</html>

Sessions

What is a session?

  • A way to store information (in variables) to be used across multiple pages
     
  • Is not stored on the users computer
     
  • By default, session variables last until the user closes the browser
     
  • Most sessions set a user-key on the user's computer that looks e.g. like: 765487cf34ert8dede5a562e4f3a7e12.

Session functions

<?php

    // Start the session
    session_start();

    // Remove all session variables
    session_unset(); 
    
    // Destroy the session 
    session_destroy(); 

?>
<?php
    // Start session
    session_start();
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Example Sessions</title>
    </head>
    <body>
    
        <?php
            // To change a session variable, just overwrite it 
            $_SESSION["fav_car"] = "Maserati";
    
            // Displays information about a variable in a way that's readable by humans
            print_r($_SESSION);
        ?>
        
    </body>
</html>

Filters

What is it?

  • Are used to validate and sanitise external input
     
  • Example what you can do with a filter:
    • Validate IP address, URL, integers, e-mail address, regular expression
    • Remove characters
    • Call a user-defined function

Filter functions

<?php

    // Used to list what the PHP filter extension offers
    filter_list();

    // Filters a single variable with a specified filter
    filter_var();

    // Checks if a variable of a specific input type exists
    filter_has_var();

    // Returns the filter ID of a specific filter name
    filter_id();

    // Gets an external variable and optionally filters it
    filter_input();

?>
<?php

    // Set e-mail address
    $email = "j.doe@example.com";
    
    // Remove all illegal characters from email using e.g a constant
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    
    // Validate e-mail e.g. using a constant
    if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        echo("$email is a valid e-mail address");
    } else {
        echo("$email is not a valid e-mail address");
    }
?>

Constant

What is a constant?

  • An identifier (name) for a simple value
     
  • The value cannot be changed during the script
     
  • Starts with a letter or underscore
     
  • They are automatically global across the entire script

Error handling

Types of errors

  • System errors (Internal)
    • The logic errors in your code
    • Can be prevented by careful programming
       
  • External
    • Related to the interactions with the world outside your code, such as:
      • Failing to open a file
      • Dropped network connection
    • Can't always avoid these type of error, but you can prepare your code for them

How to deal with errors

  • Display the error
     
  • Log or report the error
    • Log errors in a file and alerts a user/developer when
       
  • Act on the error
    • Differs for each situation
       
  • Ignore the error

Error levels

Notice

  • Will not stop the execution of the script
     
  • A way of telling you that you probably shouldn't be doing what you're doing
Notice: Undefined variable: VARIABLE_NAME in PATH_TO_FILE

Warning

  • Will not stop the execution of the script
  • To warn you that what you're doing will probably cause errors
Warning: include(PATH_TO_FILE): failed to open stream: No such file or directory

Fatal error

  • Will stop the execution of the script
     
  • Are caused when PHP encounters a logical error
     
  • What you’re asking the script to do, can't be done
Fatal error: Call to undefined function MY_FUNCTION()

Display errors

Ways to display errors

  • In your own code
     
  • .htaccess
     
  • php.ini file

In your own code

  • Can be helpful and quick
     
  • Allows you to override the setting in the php.ini or .htaccess file
     
  • You can also suppress errors for a particular line using the @ symbol
<?php

    // Report simple running errors
    error_reporting(E_ALL);
    // Make sure they're on screen
    ini_set('display_errors', 1);
    // HTML formatted errors
    ini_set("html_errors", 1);

    $error_levels = array("E_ALL", "E_NOTICE", "E_WARNING", "E_ERROR",
                      "E_STRICT", "E_DEPRECATED", "E_PARSE");

    ...

?>
<?php

    error_reporting(E_ALL);
    ini_set('display_errors','On');

    // Include the file you want to test
    include('file.php');

?>

.htaccess

  • A configuration file used by Apache-based web servers that controls the directory and all the subdirectories underneath
     
  • It overwrites the php.ini file on a server
     
  • Also used for redirections
php_flag display_startup_errors on
php_flag display_errors on
php_value error_reporting -1
php_flag html_errors on

php.ini file

// Show all error levels
error_reporting: E_ALL

// Print errors to the screen
display_errors: ON

// Shows errors at startup, only use this setting when debugging
display_errors_startup: ON

// Error logging
log_errors: ON

// Path to log file
error_log: /My/Path/file.log

Addressing errors

Custom function

<?php 

    function customError($errno, $errstr) {
        echo "<b>Error:</b> [$errno] $errstr<br>";
        echo "Ending Script";
        die();
    }

    set_error_handler(“customError”);

?>

Trigger an error

<?php 

    $test = 2;
    
    if ($test > 1) {
    
        trigger_error("Value must be 1 or below");
    
    }

?>

Logging

In your own code

<?php

    ini_set("log_errors", 1);
    ini_set("error_log", "php-error.txt");

?>

.htaccess

# log errors
php_value log_errors 1

# log file for errors
php_value error_log php-error.txt

php.ini file

log_errors = On
error_log = "/YOUR/PATH/htdocs/php-error.txt"

Questions?

PHP

By CodePamoja

PHP

Basic introduction

  • 47