Skip to content

Instantly share code, notes, and snippets.

@RicardoWEBSiTE
Created September 3, 2013 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicardoWEBSiTE/6427573 to your computer and use it in GitHub Desktop.
Save RicardoWEBSiTE/6427573 to your computer and use it in GitHub Desktop.
PHP References Documentation and Examples

Instructor: Jeffrey Way

Prerequisites

To get up and running quickly on Ubuntu 12.04, try XAMPP for Linux.

Hello World

<?php echo "Hello, world!" ?>

Resources

Tutorials & Articles

Next Steps

REPL

Composer and Packagist

Useful Packages

Syntax and Variables

PHP: Language Reference

<?php

/* Tells Apache we need to execute some PHP. */

?>

We can either use single or double quotes to specify a string.

<?php

echo 'Hello, world!';
echo "My name is Dwayne.";

?>

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Constants

We create constants in PHP using define. See here.

<?php

define('PI', 3.14159265359);

?>

Displaying Errors

# php.ini
error_reporting = E_ALL # http://php.net/error-reporting
display_errors  = On    # http://php.net/display-errors

Tip: If you can't find your php.ini file, open the terminal, and type: php -i | grep "Loaded Configuration File".

Arrays

<?php

$day_of_the_week = array(
  'Sunday',
  'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
  'Saturday'
);
var_dump($days_of_the_week);

?>

Conditionals

Lookups

<?php

$month = 'Feb';
// $month = 'April';

$months = array(
  'Jan' => 'It is January',
  'Feb' => 'It is February',
  'Mar' => 'It is March',
  ...
);

echo isset($months[$month]) ? $months[$month] : 'Not the right month!';

?>

Formatted Strings

<?php

// Example sscanf and list usage

$results = sscanf("June 7th, 2012", "%s %[^,], %d");
print_r($results);

list($month, $day, $year) = sscanf("June 7th, 2012", "%s %[^,], %d");

sscanf("June 7th, 2012", "%s %[^,], %d", $m, $d, $y);

// $results[0] === $month === $m
// $results[1] === $day   === $d
// $results[2] === $year  === $y

?>

Heredocs

Heredocs can be an enormous help when preparing HTML and SQL statements.

<?php

$post = array(
  'title'          => 'How to Register a Business in Trinidad and Tobago',
  'author'         => 'Dwayne R. Crooks',
  'body'           => 'Step 1. Do a name search.',
  'published-date' => '10-10-2012'
);

// common to see EOT or EOD, but you can call it whatever you want
$email = <<<EOT
<h1>{$post['title']}</h1>
<p>By: {$post['author']}</p>

<div>
  {$post['body']}
</div>
EOT; // N.B. Cannot end the file with a heredoc

echo $email;

// alternatively

extract($post);

$email = <<<EOT
<h1>$title</h1>
<p>By: $author</p>

<div>$body</div>
EOT; // N.B. Must be on it's own line with no spaces at the beginning

echo $email;

?>

Includes and Requires

Resources

Loops

Namespaces

stdClass

Object-Oriented PHP

Passing Values From Page to Page

Using the Query String

Superglobals are built-in variables that are always available in all scopes.

You can use the superglobal array $_GET to fetch information from the query string. Use isset to determine if a variable is set and is not NULL.

<?php

$name = 'world';

if (isset($_GET['name'])) {
  $name = $_GET['name'];
}

echo "Hello, $name!";

?>

N.B. Always assume that data taken from the user is dangerous. What if the user entered the url http://www.example.com/index.php?name=<h3>Dwayne</h3>.

$_POST

Here are two ways to test if a page is called via an HTTP POST:

<?php


// Way #1
if (empty($_POST)) {
  echo 'not posted';
} else {
  echo 'posted';
}

// Way #2
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  echo 'posted';
} else {
  echo 'not posted';
}

?>

Sessions

Generally we use sessions to store user specific data. Sessions are stored on the server. The PHP engine sets a cookie (a way to store little bits of information on the client) and stores a session ID (a really long, randomly generated, string that's difficult to guess). When the user requests a specific URL on the website that session ID cookie that we set will be sent back to the server at which point the PHP engine would validate it and then subsequently retrieve the data that's associated with that specific session.

Using Sessions

The first step when working with sessions is to call session_start. It's important that this occurs before any HTML is echoed out. This is because, session_start actually sets some HTTP headers. Once this is done we can start setting values via keys on the session superglobal $_SESSION.

<?php

session_start();

$_SESSION['username'] = 'dwayne';

?>

When it's time to cleanup our sessions, we use session_destroy. Think of a session as a user specific life-cycle. You open the browser, you visit a webpage, you close the browser. That was a session. In this case, the session would automatically be destroyed. However, say you want to manually destroy the session, for e.g. as part of some logout functionality. Then, that's where session_destroy comes into play.

<?php

session_start();

// do your stuff with sessions

// cleanup after yourself
session_destroy();
$_SESSION = array(); // or [] if using PHP 5.4+
// may also need to delete the cookie being used to propagate the session ID

?>

TODO: Write a login form

Cookies

Think of cookies as text files that can store a maximum of 4KB worth of information.

N.B. You should never use cookies to store private information. Instead you'd use a cookie to store more casual information.

We can create cookies using the setcookie function. You access cookies values using the cookie superglobal $_COOKIE.

To delete a cookie you need to also use the setcookie function, but this time setting the expiration time to any time in the past.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment