PHP Code Snippets

From Daves Wiki
Revision as of 21:25, 23 June 2020 by Dmeehan (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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

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.

if ($_SESSION['logged_in'] != 1)
  // remove all session variables
  // destroy the session 

  header('Location: login.php');

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 == 2) ? echo "TRUE" : echo "FALSE";

The above snippet will output TRUE

PHP Error Log

Use this command to get the PHP error log on a Raspberry Pi:

cat /var/log/apache2/error.log

Back to PHP main page.