How to Make a Quick and Dirty ArrayList in PHP

At work I usually work with .NET. My own projects however, tend to be PHP for the most part. Tonight I needed to mimic .NET’s ArrayList object. Since PHP does not have such an object (that I know of) I decided to cook one up for myself. My example depicts a book (object) and a shelf (array) scenario for easier comprehension.

<?php
// Holds all our books
Class Shelf {
	private $ar = array();
	public function add($book) {
		array_push($this->ar, $book);
	}
	public function listBooks() {
		return $this->ar;
	}
}
// Book class, kept simple
Class Book {
	public $title;
	public $author;
}

// Declare a new book and add details
$book1 = new Book;
$book1->title = "Death of a Salesman";
$book1->author = "Arthur Miller";

// Declare another book and add details
$book2 = new Book;
$book2->title = "Fight Club";
$book2->author = "Chuck Palahniuk";

// Add the books to our book shelf
$shelf = new Shelf;
$shelf->add($book1);
$shelf->add($book2);

// Take a peek inside the book shelf
print_r($shelf->listBooks());
// TIP: JSON output anyone?
echo json_encode($shelf->listBooks());
?>

Convert Date and Time to UTC

I have dealt with PHP dates and times in the past but it has never been this difficult and time consuming to pick back up.

This week I needed to change a timestamp from Eastern standard time to a UTC for storing in my database. Woah, did this tax my brain!

Anyways here are only four ways (I am sure there are more) I found for changing a date and time to a UTC timestamp.

1. [PHP] Using mktime()

date_default_timezone_set('America/New_York'); 
$date = mktime(0,0,0,7,16,2013); // Construct date to generate a UNIX timestamp (integer)
echo gmdate("Y-m-d H:i:s", $date); // Alternatively date('Y-m-d H:i:s',$date);

2. [PHP] Using strtotime()

date_default_timezone_set('America/New_York'); 
$date = strtotime('2013-07-16 00:00:00'); // Construct date to generate a UNIX timestamp (integer)
echo gmdate("Y-m-d H:i:s", $date); // Alternatively date('Y-m-d H:i:s',$date);

3. [MySQL] Using FROM_UNIXTIME()

This works on-the-fly when inserting your date into the database. And like the above it needs the integer representation of the UNIX timestamp.

date_default_timezone_set('America/New_York'); 
$date = strtotime('2013-07-16 00:00:00'); // Construct date to generate a UNIX timestamp (integer)
$SQL = "INSERT INTO table_name (id, created) VALUES (1,FROM_UNIXTIME({$date}))"; // MySQL does the conversion when you insert the row

4. [MySQL] Using UTC_TIMESTAMP()

This works quickest but only inserts the current date and time into the database. Simple but useful.

$SQL = "INSERT INTO table_name (id, created) VALUES (1,UTC_TIMESTAMP())"; // MySQL does the conversion when you insert the row

Realizations

While changing the integer version of an UTC timestamp to the human readable, SQL version and wasting so much time. I came to a realization, maybe one should store the UTC timestamp in integer form AS IS and convert it on the fly during presentation. Its smaller and easier to compare, who knows, maybe to avoid a little server processing by doing the presentations conversion in JavaScript. Ah well, at least this adventure helped (sort of) remind me of how time conversions works in PHP. But boy are there way too many functions for dealing with it.

Check if User Accepts Cookies (Simple)

I looked around for code that checked whether the user’s browser accepted cookies in PHP and found a few approaches. They involved redirection and setting some sort of test cookie. After scratching my head for a little bit I thought why not just check if the ‘PHPSESSID’ cookie is set and go off of that? So here is my tiny function doing just that. HOWEVER, it is important to realize and accept that if you are checking for the cookie on the first page the user hits this code will fail since cookies are set on the second trip to the server. In which if that is the case, you might want to try either code that redirects and returns or a spaghetti approach of setting the cookie, displaying some html (watch your output buffer), then reading the cookie.
I prefer to avoid all that trouble.

    function userAcceptsCookies() {
        if(isset($_COOKIE['PHPSESSID'])){
            return true;
        } 
        return false;
    }

Get Current Website or Webpage URL

Three useful PHP functions for locating yourself on your site. They can come in useful for when you want to create links in code for external use. The nice part about these is that if you are on SSL, they will generate an SSL link.

Get Current Website URL

function getCurrentWebsiteURL() {
    $url = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
    } else {
        $url .= $_SERVER["SERVER_NAME"];
    }
    return $url;
}

The above will generate the following string.

http://mywebsite.com

Get Current File URL

function getCurrentFileURL() {
    $url = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER['PHP_SELF'];
    } else {
        $url .= $_SERVER["SERVER_NAME"].$_SERVER['PHP_SELF'];
    }
    return $url;
}

The above will generate the following string.

http://mywebsite.com/test.php

Get Current URL (With GET Requests)

function getCurrentURL() {
    $url = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $url;
}

The above will generate the following string.

http://mywebsite.com/test.php?message=hello

How to Check if ‘mod_rewrite’ is On Using PHP

I needed to rewrite my menu’s based on whether mod_rewrite was turned on in the htaccess file and not necessarily if the module existed. This is how I did it in two parts.

Part 1- In the .htaccess file

#Turn on rewrite 
RewriteEngine On

#Notify PHP that rewrite is on
SetEnv HTTP_MOD_REWRITE on

#Continue with your rewrite rules below

Part 2- In the PHP file

function modRewriteIsEnabled() {
    if (strtolower($_SERVER['HTTP_MOD_REWRITE']) == 'on') {
      return true;
    } else {
      return false;
    }
}

How to Keep a JavaScript or CSS File From Caching

Depending on your browser and server settings sometimes JavaScript and CSS files are cached while you are trying to modify a webpage. Here is a quick copy/paste way to assure this happens if you are using PHP or ASP (Classic ASP but I think it should work in .NET as well). Please note the only reason you would want to do this is to assure every time you hit the page you are trying to modify, a fresh copy of the CSS or JavaScript file is downloaded. This should be removed when your site hits production.

Please excuse my wordpress code plugin. It doesn’t seem to be converting less and greater than characters correctly.

PHP

ASP

Set Expires Header

I’ve noticed setting the Expire time for files on the HTACCESS file tends to fail when loading a file using the readfile() function in PHP. A workaround is setting the Expire header before loading the file. This is what that would look like.

header('Expires: '.gmdate('D, d M Y H:i:s', time() + 60*15); // seconds, minutes
header("Content-Type:image/jpeg");
readfile($jpeg_image);

Now when you check the expiration headers via your browser’s Developer Tools you will see this particular file expires one month from now.

Function for Getting the Local Time (Time Zones)

Today I needed to convert the current server time to my local time. I made a quick little function that helps take most of the thinking out of it. At the moment my function just works with just two time zones but you can add more from PHP’s supported list.

function getLocalTime($index) {
$zones = array();
$zones[] = new DateTimeZone('America/New_York');
$zones[] = new DateTimeZone('America/Los_Angeles');

$time = new DateTime(date("Y-m-d H:i:s", time()));
$time->setTimezone($zones[$index]);
return $time->format('Y-m-d H:i:s');
}
// Try it
echo getLocalTime(0); //NY

Resource: http://php.net/manual/en/timezones.php

API Data Caching

I needed to cache some API data to a file recently. However I did not want the file to be saved every single time someone hit my server but every 10 minutes. Below is a function I used to accomplish that.

<?php
function cacheData($api_query, $save_as_file, $minutes_til_expire) {
    try {
        if (file_exists($save_as_file)) {

            $time_expire = time() + ($minutes_til_expire * 60); // Expire Time (3 mins)

            if(filemtime($save_as_file) <= $time_expire) {
                // If file is older than expire time, replace it
                unlink($save_as_file);
                file_put_contents($save_as_file, file_get_contents($api_query));
            }

        } else {
            // If file doesn't exist, create it.
            file_put_contents($save_as_file, file_get_contents($api_query));
        }
        readfile($save_as_file);
    } catch(Exception $e) {
        // In case of exception, email me
        $to      = 'you_email@gmail.com';
        $subject = 'JSON File Exception';
        $message =  $e->errorMessage();
        $headers = 'From: webmaster@your_website.com' . "\r\n" .
        'Reply-To: webmaster@ your_website.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        mail($to, $subject, $message, $headers);
    }
}
?>

A MySQL Database Assistant (Helper) Class

Connecting to a MySQL database is pretty easy but there are things you find yourself always doing over and over again on different projects like sanitizing, outputting your result arrays, changing your errors from displaying on screen to being written to the Apache error log. That’s why I have created this simple database assistant class.

$assistant = new DbAssistant('localhost','database', 'root', 'password');
$assistant->setOutputErrors(true); // display output errors on screen
$assistant->sanitize($user_input);

The following returns a basic results array:

$results = $assistant->executeQuery("SELECT * FROM mytable");

Or the following prints the results array:

$assistant->executeQueryAndDisplayResults("SELECT * FROM mytable");

View: db_helper.php.txt



Warning: This class does not currently support parameterized statements. Please use parameterized statements to avoid SQL injecton attacks.


Parameterized Statements Resource: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Here are some usage examples: