PHP generated image caching

So a recent challenge I had was storing binary data (a PNG image) in a MySQL database behind PHP, to which I would pull out upon request, format it and use it as a displayed image in the webpage.

My initial code looked very simple and easy.

header(“Cache-Control: private, max-age=10800, pre-check=10800”);
header(“Pragma: private”);
header(“Expires: ” . date(DATE_RFC822,strtotime(” 2 day”)));

header(‘Content-type: image/png’);
header(‘Content-MD5: ‘. base64_encode(pack(‘H*’, md5($row[‘Icon’]))));
header(‘Content-Length: ‘.filesize($row[‘Icon’]));
header(‘Content-Disposition: attachment; filename=”‘.$_GET[“ElementID”].’.png”‘);
echo $row[‘Icon’];

Now I wouldn’t suggest using this, as I found out Content-Length was way wrong, along with expires just set for 2 days. I needed to manually flush my browser cache to see any updates. Bad way to push out an image from MySQL through PHP.

The link below from rd2inc.com was the majority of my solution, but to that I had to change the way it got the additional header information. This was because apache_request_headers() wasn’t a function in my PHP. So in the link to php manual (below) I found and then had to slightly modify the code for the .htaccess file to this:

RewriteEngine on
RewriteRule (.*) – [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]
RewriteRule (.*) – [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

Now I can use:

$_SERVER[‘HTTP_IF_MODIFIED_SINCE’]
$_SERVER[‘HTTP_IF_NONE_MATCH’]

And how did I check for update change? Just set a hook in MySQL to update a timestamp  whenever that row is updated!

Links where I got info:

mysql_insert_id()

$query = “INSERT something into some table somewhere“;
//  Run query
$row = mysql_query($query);

// Make sure query inserted user successfully
if ( !mysql_insert_id() ){
echo($query);
die(“Error: User not added to database.”);
}

This little nifty function “mysql_insert_id()” has solved several of my problems, although the problems were never surfaced, I knew that it would lead to problems in high traffic scenarios. My old method was to do the insert and then immediately call for the latest ‘ID’ by date… the problem is what happens when two people click the ‘submit’ button at the same time? The ‘ID’ returned to the user may be the other persons! All depending on the somewhat random order that the code gets executed. I knew this would be a problem, but now after finding this nifty function, it has alleviated all of that!

http://php.net/manual/en/function.mysql-insert-id.php Says this:

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

For you PHP/MySQL programmers out there, note this down! It is good to know for the bigger than normal DB-based project.