Close

Miscellaneous Snippets

How to Create a Custom Error 404 Not Found Page

In this PHP tutorial, you’ll learn how to create a custom 404 page not found error page. Watch the tutorial below:

Links mentioned in the video:

Get the source code for this video as a supporting listener of the John Morris Show on Patreon

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

November 5, 2015

How to Send Mail Using PHP

In this PHP tutorial, you’ll learn how to send mail using PHP. Watch the tutorial below:

Links mentioned in the video:

Get the source code for this video as a supporting listener of the John Morris Show on Patreon

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

October 29, 2015

How to Parse XML With SimpleXML and PHP

In this PHP tutorial, you’ll learn how to parse XML using SimpleXML and PHP.

Watch the tutorial below:

Links mentioned in the video:

Get the source code for this video as a supporting listener of the John Morris Show on Patreon

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

October 22, 2015

How to Create a Zebra Striped Table With Odd Even Row Colors Using PHP

In this PHP tutorial, you’ll learn how to create a zebra striped table by adding odd and even classes in a loop using PHP.

Watch the tutorial below:

Links mentioned in the video:

Here’s the code I used in the video:

Get the source code for this video as a supporting listener of The John Morris Show on Patreon

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

October 14, 2015

Build a Grid Layout For WordPress Using WP_Query

Here’s how to build a grid layout for WordPress via shortcodes and WP_Query:

A lot of WordPress developers immediately rush to query_posts in order to create custom loops.

But, query_posts is meant for altering the main loop of a WordPress page/post (actually, it’s not even recommended for that anymore).

Using get_posts() is okay… but, if you want that real WordPress flavor using WP_Query is the way to go.

In the video above, I show you how to use WP_Query to create a custom loop inside WordPress in order to build a Pinterest-style grid layout.

Here’s the code I used in the video:

<?php
/*
Plugin Name: John Morris Grid
Plugin URI: https://johnmorrisonline.com/
Description: Demo plugin that displays posts in a grid format via shortcode
Version: 1.0.1
Author: John Morris
Author URI: https://johnmorrisonline.com
Text Domain: johnmorris-grid
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Domain Path: /lang
*/

if ( ! class_exists( 'John_Morris_Grid' ) ) {
class John_Morris_Grid {
/**
* Init
*
* Initializes the plugin
*/
public function init() {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
add_image_size( 'jmogrid', 220, 220, true );
add_shortcode( 'jmogrid', array( $this, 'shortcode_handler' ) );
}

/**
* Enqueue Scripts and Styles
*
* Enqueues styles and scripts used throughout the plugin
*/
public function enqueue() {
wp_enqueue_style('jmogrid', plugins_url( '/css/style.css', __FILE__) );
}

/**
* Shortcode Handler
*
* Handles shortcode processing
*/
public function shortcode_handler($atts) {
$atts = shortcode_atts(
array(
'posts_per_page' => 100
), $atts, 'jmogrid'
);

return $this->grid($atts);
}

/**
* Grid Builder
*
* Builds the grid
*
* @param array $args Query argumenst passed to WP_Query
*
* @return string $html The HTML output
*/
public function grid($args) {
$grid = new WP_Query($args);

ob_start(); ?>

<div id="jmogrid">

<?php $count = 1; if ( $grid->have_posts() ) : while( $grid->have_posts() ) : $grid->the_post(); ?>
<?php
$modulus = $count % 5;

if ( $modulus == 1 ) {
$class = 'first';
} elseif ( $modulus == 0 ) {
$class = 'last';
}
?>
<div class="jmogrid-item <?php echo $class; ?>">
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('jmogrid'); ?>
</a>
<?php endif; ?>
<h4>
<a href="<?php the_permalink(); ?>"><?php echo wp_trim_words(get_the_title(), 6); ?></a>
</h4>
<p class="jmogrid-meta">
<?php _e( 'Written by', 'johnmorris-grid' ); ?> <?php the_author(); ?><br />
<?php echo get_the_date( get_option( 'date_format' ) ); ?>
</p>
<p><?php echo wp_trim_words( get_the_content(), 10); ?></p>
</div>

<?php unset($class); $count++; endwhile; wp_reset_postdata(); endif; ?>

</div>

<?php return ob_get_clean();
}
}

// Instantiate Class
$JohnMorrisGrid = new John_Morris_Grid;

// Hook in
add_action( 'init', array( $JohnMorrisGrid, 'init' ) );
}

/* John Morris Grid CSS */

#jmogrid {
overflow: hidden;
clear: both;
}

.jmogrid-item {
overflow: hidden;
box-sizing: border-box;
width: 18%;
float: left;
margin: 20px 1%;
border: 1px solid #e4e4e4;
border-radius: 3px;
}

.jmogrid-item.first {
width: 19%;
margin-left: 0;
}

.jmogrid-item.last {
width: 19%;
margin-right: 0;
}

.jmogrid-item h4,
.jmogrid-item p {
margin: 0;
padding: 20px;
}

.jmogrid-item h4 {
padding-bottom: 0;
}

.jmogrid-item p {
font-size: 1.5rem;
}

p.jmogrid-meta {
font-size: 1.2rem;
color: #777;
padding-bottom:0;
padding-top: 5px;
}

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

July 16, 2015

PHP Try Catch Error Handling

How do you PHP try catch blocks to efficiently handle errors? Here’s the answer:

Here’s the code I used in the video:

<pre>
<?php
try {
echo "Try to do something here.<br />";
throw new Exception("Yikes. Something went funky.<br />", 234);
} catch (Exception $e) {
//print_r($e);
echo $e->getMessage();
} finally {
echo "This will always run in our try block.<br />";
}

// try {
// // connect (create a new MySQLi object)
// $mysqli = new MySQLi('localhost', 'root', 'root', 'snippet');

// if (mysqli_connect_error()) {
// throw new Exception(mysqli_connect_error());
// }

// $sql = "SELECT * FROM search LIMIT 10";
// $result = $mysqli->query($sql);

// if (!$result) {
// throw new Exception($mysqli->error);
// }

// while($row = $result->fetch_object()) {
// $results[] = $row;
// }
// }
// catch (Exception $e)
// {
// echo 'We are having issues. Here is how to get help.';
// }

// print_r($results);
?>
</pre>

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

May 28, 2015

How to Create a PHP 301 Header Redirect Script

How do you implement a 301 header redirect in PHP? Here’s the answer and how to do it:

Here’s the code I used in the video:

<?php
/**
* PHP Redirect Script
*
* @author https://johnmorrisonline.com
*/

// Map IDs to URLs
$accepted_ids = array(
'goog' => 'http://www.google.com',
);

// Die on no ID
if ( !isset( $_GET['id'] ) ) {
die('Oops. Need an ID');
}

// Set ID
$id = $_GET['id'];

// Die on ID not supported
if ( ! in_array( $id, array_keys( $accepted_ids ) ) ) {
die('Oops. That ID is not supported.');
}

// Get campaign if set
if ( isset( $_GET['utm_campaign'] ) ) {
$campaign = $_GET['utm_campaign'];
}

// Create redirect
$redirect = sprintf('%s?q=%s', $accepted_ids[$id], $campaign);

// Run the redirect
//echo $redirect;
header("HTTP/1.1 301 Moved Permanently");
header("Location: {$redirect}");

// Exit
exit;

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

May 21, 2015

MD5, SHA-1 or BCRYPT For Hashing and Storing Passwords in PHP?

Should you use MD5, SHA-1 or BCRYPT when hashing and storing passwords using PHP? Here’s the answer and how to do it:

Here’s the code I used in the video:

<?php
/**
* Performs password hashing
*
* This class is used to perform common password hashing routines
*
* @version 1.0
* @author John Morris <support@johnmorrisonline.com>
*/
class Hash_Password {
/**
* Hashing algorithm
* @access private
* $var int
*/
private $algorithm = PASSWORD_DEFAULT;

/**
* Hashing options
* @access private
* $var array
*/
private $options;

/**
* Constructor
*
* Sets up class options
*/
public function __construct() {
$this->options = array(
// Add SALT and cost options here if desired
);
}

/**
* Hash and store password
*
* Hashes the password then stores it in the database
*
* @param string $password The password to hash and store
*
* @return boolen true/false True if hash and store is successful. False if not
*/
public function hash_and_store($password) {
// Hash the password
$hash = $this->hash( $password );

// Check for successful hashing
if ( ! $hash ) {
return false;
}

// Store password in database
// Check if storing was successful. Return false if not

return true;
}

/**
* Verify password
*
* Gets the hash from the database and verifies user-submitted password
*
* @param string $password The password to check
*
* @return boolean true/false True if password matches. False if not
*/
public function get_and_verify($password) {
// Get hash from database
$hash = '12lkjrelkjelkjrekjel';

// Check if user-submitted password matches hash
if ( $this->verify( $password, $hash ) ) {

// Check if password needs rehashed
if ( $this->needs_rehash( $hash ) ) {

// Rehash and store new hash
if ( ! $this->hash_and_store( $password ) ) {
return false;
}

}

return true;
}

return false;
}

/**
* Hashing method
*
* Hashes a password
*
* @param string $password The password to hash
*
* @return $string $hash The hashed password
*/
public function hash($password) {
return password_hash( $password, $this->algorithm, $this->options );
}

/**
* Verify method
*
* Verifies a password matches the hash
*
* @param string $password The plain text password to check
* @param string $hash The hash to check against
*
* @return boolean true/false True if it matches. False if not
*/
public function verify($password, $hash) {
return password_verify( $password, $hash );
}

/**
* Needs rehash method
*
* Checks if a hash needs rehashed. For new algorithms/options
*
* @param string $hash The hash to check for rehashing
*
* @return boolean true/false True if needs rehashing. False if not
*/
public function needs_rehash($hash) {
return password_needs_rehash($hash, $this->algorithm, $this->options );
}

/**
* Get hash info
*
* Gets the hashing algorithm and options used while hashing
*
* @param string $hash The hash to get info from
*
* @return array $info An associate array containing the hashing info
*/
public function get_info($hash) {
return password_get_info($hash);
}

/**
* Find cost
*
* This code will benchmark your server to determine how high of a cost you can
* afford. You want to set the highest cost that you can without slowing down
* you server too much. 8-10 is a good baseline, and more is good if your servers
* are fast enough. The code below aims for ≤ 50 milliseconds stretching time,
* which is a good baseline for systems handling interactive logins.
*
* @param int $baseline Baseline cost to start testing from
*
* @return int $cost Cost to use for server
*/
public function find_cost($baseline = 8) {
// Target time. 50 milliseconds is a good baseline
$time_target = 0.05;
$cost = $baseline;

// Run test
do {
$cost++;
$start = microtime( true );
password_hash( 'test', $this->algorithm, array( 'cost' => $cost ) );
$end = microtime( true );
} while( ( $end - $start ) < $time_target );

return $cost;
}
}

<?php
// Require password hashing class
require_once('/class-hash-password.php');

// Example password
$password = '1234567qwerty';

// Instantiate new instance of class
$hash_password = new Hash_Password();

// Hash a password
$hash = $hash_password->hash($password);

echo $hash;

// Spacer
echo '<br />';

// Verify a password
echo $hash_password->verify($password, $hash);

// Spacer
echo '<br />';

// Get hash info
print_r($hash_password->get_info($hash));

// Spacer
echo '<br />';

// Find appropriate cost
echo $hash_password->find_cost();

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

May 12, 2015

How to Calculate an Age By Birthday Using PHP

This PHP function accepts a birthday as a parameter and will return the age based on that birthday. Handy for social sites/applications.

<?php
// PHP 5.3-
function birthday($birthday){
$age = strtotime($birthday);

if($age === false){
return false;
}

list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));

$now = strtotime("now");

list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));

$age = $y2 - $y1;

if((int)($m2.$d2) < (int)($m1.$d1))
$age -= 1;

return $age;
}

echo birthday('1981-05-18');

// PHP 5.3+
function birthday($birthday) {
$age = date_create($birthday)->diff(date_create('today'))->y;

return $age;
}

echo birthday('1981-05-18');

December 8, 2013

How to Create an ics Import File Using PHP

In this video, you’ll learn how to create an .ics import file using PHP. This allows you to dynamically generate the .ics file based on stored event data. Users can then download the file and import the event information in their calendar of choice… Outlook, Thunderbird(Lightning), Apple Calendar, etc.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
/**
* Get the event ID
*/
$event_id = @$_GET['event_id'];
/**
* If no event ID or event_id is not an integer, do nothing
*/
if ( !$event_id || !is_numeric( $event_id ) ) {
die();
}
/**
* Event information
*/
//$event = get_event($event_id);
$event = array(
'event_name' => 'Test Event',
'event_description' => 'This is a test event. This is the description.',
'event_start' => time(),
'event_end' => time() + 60*60*2,
'event_venue' => array(
'venue_name' => 'Test Venue',
'venue_address' => '123 Test Drive',
'venue_address_two' => 'Suite 555',
'venue_city' => 'Some City',
'venue_state' => 'Iowa',
'venue_postal_code' => '12345'
)
);
$name = $event['event_name'];
$venue = $event['event_venue'];
$location = $venue['venue_name'] . ', ' . $venue['venue_address'] . ', ' . $venue['venue_address_two'] . ', ' . $venue['venue_city'] . ', ' . $venue['venue_state'] . ' ' . $venue['venue_postal_code'];
$start = date('Ymd', $event['event_start']+18000) . 'T' . date('His', $event['event_start']+18000) . 'Z';
$end = date('Ymd', $event['event_end']+18000) . 'T' . date('His', $event['event_end']+18000) . 'Z';
$description = $event['event_description'];
$slug = strtolower(str_replace(array(' ', "'", '.'), array('_', '', ''), $name));
header("Content-Type: text/Calendar; charset=utf-8");
header("Content-Disposition: inline; filename={$slug}.ics");
echo "BEGIN:VCALENDAR\n";
echo "VERSION:2.0\n";
echo "PRODID:-//LearnPHP.co//NONSGML {$name}//EN\n";
echo "METHOD:REQUEST\n"; // requied by Outlook
echo "BEGIN:VEVENT\n";
echo "UID:".date('Ymd').'T'.date('His')."-".rand()."-learnphp.co\n"; // required by Outlok
echo "DTSTAMP:".date('Ymd').'T'.date('His')."\n"; // required by Outlook
echo "DTSTART:{$start}\n";
echo "DTEND:{$end}\n";
echo "LOCATION:{$location}\n";
echo "SUMMARY:{$name}\n";
echo "DESCRIPTION: {$description}\n";
echo "END:VEVENT\n";
echo "END:VCALENDAR\n";

October 22, 2012