PHP Code Snippets

From Daves Wiki
Revision as of 21:28, 31 March 2020 by Dmeehan (talk | contribs) (Ternary Operator)
Jump to navigation Jump to search

PHP Code Snippets

Basic structure of a PHP Class

class ClassName 
{
  public $variable;

  public __construct()
  { 
    // do some stuff
  }

  public function methodName()
  {
    // do some other stuff 
  }

}

Class Autoloader

Use this code to autoload all the classes defined in the /Classes folder

 
<?php 
spl_autoload_register(function ($class_name) {
  include './Classes/' . $class_name . '.php';
});
?>

Session Start

The check for session data should be done at the very beginning of every page where it's needed, and also before any text it output. This examples checks if a user is logged in, and redirects to the login page if not. It also destroys any existing session data before redirecting.

<?php 
session_start();
if ($_SESSION['logged_in'] != 1)
{
  // remove all session variables
  session_unset(); 
  	
  // destroy the session 
  session_destroy(); 

  header('Location: login.php');
  die();
}
?>

Ternary Operator

The PHP Ternary Operator uses the following structure:

(Condition) ? (Statement1) : (Statement2); 

Statement1 is executed if Condition == TRUE and Statement2 is executed if Condition == FALSE

$var = 2
($var == true) ? echo "TRUE" : echo "FALSE";

The above snippet will output TRUE


Back to PHP main page.