Skip to content

Instantly share code, notes, and snippets.

@dwayne
Last active February 26, 2021 22:10
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save dwayne/5078372 to your computer and use it in GitHub Desktop.
Save dwayne/5078372 to your computer and use it in GitHub Desktop.

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".

<?php
// helper functions
function is_blank($str) {
return !isset($str) || $str === '';
}
function redirect($url) {
header("Location: $url");
exit; // or die();
}
$contact_form = new stdClass;
$contact_form->name = '';
$contact_form->email = '';
$contact_form->message = '';
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// name - required
// email - required, must be a valid email address
// message - required, length at least 10 chars
$contact_form->name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$contact_form->email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$contact_form->message = filter_var($_POST['message'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (is_blank($contact_form->name)) {
$errors['name'][] = 'Name is required.';
}
if (is_blank($contact_form->email)) {
$errors['email'][] = 'Email is required.';
}
if (!filter_var($contact_form->email, FILTER_VALIDATE_EMAIL)) {
$errors['email'][] = 'Email is invalid.';
}
if (is_blank($contact_form->message)) {
$errors['message'][] = 'Message is required.';
}
if (strlen($contact_form->message) < 10) {
$errors['message'][] = 'Message must be at least 10 characters long.';
}
if (empty($errors)) {
$to = 'dwayne.crooks@gmail.com';
$subject = 'I used your contact form';
$message = "Hi,\n\nMy name is $contact_form->name.\n\n$contact_form->message";
$headers = "From: $contact_form->email";
$mail_sent = mail($to, $subject, $message, $headers);
redirect(sprintf('/mail.php?sent=%s', $mail_sent ? 'true' : 'false'));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Contact Us</title>
<style>
label {
display: block;
}
.error-field label {
color: red;
}
.error-field input[type="text"], .error-field textarea {
background-color: red;
}
</style>
</head>
<body>
<h1>Contact Us</h1>
<?php if (!empty($errors)) : ?>
<ul class="errors">
<?php
foreach ($errors as $field => $messages) :
foreach ($messages as $message) :
?>
<li><?php echo $message; ?></li>
<?php endforeach; endforeach; ?>
</ul>
<?php endif; ?>
<form action="" method="post">
<p <?php if (!empty($errors['name'])) : echo 'class="error-field"'; endif; ?>>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php echo $contact_form->name; ?>">
</p>
<p <?php if (!empty($errors['email'])) : echo 'class="error-field"'; endif; ?>>
<label for="email">Email:</label>
<input type="text" id="email" name="email" value="<?php echo $contact_form->email; ?>">
</p>
<p <?php if (!empty($errors['message'])) : echo 'class="error-field"'; endif; ?>>
<label for="message">Message:</label>
<textarea id="message" name="message"><?php echo $contact_form->message; ?></textarea>
</p>
<p>
<input type="submit" value="Send my message">
</p>
</form>
</body>
</html>

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

?>

Functions

<?php

function hello($name = 'world') {
  return "Hello, $name!";
}

echo hello('Dwayne');

?>

Closures in PHP

<?php

// PHP's scoping rules causes this code to fail
// function array_pluck($to_pluck, $arr) {
//   return array_map(function ($elem) {
//     // $to_pluck - doesn't exist in this function's local scope
//     return $elem[$to_pluck]; // error
//   }, $arr);
// }

// However, this works
function array_pluck($to_pluck, $arr) {
  return array_map(function ($elem) use($to_pluck) {
    return $elem[$to_pluck];
  }, $arr);
}

?>

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;

?>

MySQL

A database system.

Logging into MySQL

$ mysql

or

$ mysql -u username -p
Enter password:

It's a good practice to setup different users with access to specific databases. N.B. Don't use the root account for user databases.

Let's assign a unique password to the root user:

$ mysql -u root -p
mysql> SET PASSWORD FOR root@localhost = PASSWORD('root');

See SET PASSWORD for further details.

Working with MySQL from the Terminal

# Showing the databases
mysql> SHOW DATABASES;

# Creating a database
mysql> CREATE DATABASE blog;

# Using a specific database
mysql> USE blog;

# Showing the tables in the database
mysql> SHOW TABLES;

# Creating a table
mysql> CREATE TABLE users(
    ->   id INT AUTO_INCREMENT,
    ->   first_name varchar(50) NOT NULL,
    ->   last_name varchar(50) NOT NULL,
    ->   email_address varchar(100) NOT NULL,
    ->   PRIMARY KEY (id)
    -> );

# Viewing the structure of a table, i.e. it's schema
mysql> DESCRIBE users;

# Selecting all rows from a table
mysql> SELECT * FROM users;

Inserting, Selecting, and Deleting

mysql> INSERT INTO users VALUES(null, 'John', 'Doe', 'john@doe.com');

or

mysql> INSERT INTO users (first_name, last_name, email_address) VALUES('John', 'Doe', 'john@doe.com');
mysql> SELECT email_address FROM users;
mysql> SELECT first_name, last_name FROM users;

Ordering your selections:

mysql> SELECT * FROM users ORDER BY last_name ASC;
mysql> SELECT * FROM users ORDER BY last_name DESC;

Limiting the number of rows returned:

mysql> SELECT * FROM users LIMIT 2;
mysql> DELETE FROM users WHERE [condition];

mysql> DELETE FROM users WHERE id = 123;
mysql> DELETE FROM users WHERE last_name = 'Crooks';

Updating Rows and Tables

To update a row in a table we use the UPDATE query.

mysql> UPDATE users SET last_name = 'Alexander' WHERE first_name = 'Jane';

To change a column name and type in a table use the ALTER query.

mysql> ALTER TABLE users CHANGE last_name surname varchar(80);

Joining Tables

GUI Apps

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.

Installing phpsh Locally on Ubuntu 12.04

http://phpsh.org/

phpsh is an interactive shell for PHP.

  1. Download a snapshot of the latest version as a gzipped tarball
  2. python setup.py build
  3. python setup.py install --prefix=~/local
  4. export PYTHONPATH=~/local/lib/python2.7/site-packages
  5. ~/local/bin/phpsh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment