Here's an example that works with .htaccess to generate images a couple different ways. (All of them are basically using the output of file_get_contents). It's designed to be "index.php" in, say, your /images/ directory. URL's can be "site.com/images/whatever.jpg", and you can generate the image like the original, read it from disk, DB, etc.
Please don't use a database to store images in real life.
<?php
// Log the json-encoded SERVER array for later parsing. This can also be had from access.log
error_log(json_encode($_SERVER));
if (isset($_GET['f'])) {
/* prevent path traversal */
$f = basename($_GET['f']);
/**
* Determine the picture by UserAgent
*/
$image = '';
if ($f == 'useragent.png') {
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'linux')) {
$image = 'linux.png';
} elseif (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows')) {
$image = 'windows.png';
} elseif (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'osx')) {
$image = 'osx.png';
}
/*
* You could then continue with the image manipulation functions
* to output text. e.g., timestamps, 'your IP is..' images, etc.
*/
/**
* Just read out the file
*/
if ($image && file_exists($image)) {
header('COntent-Type: image/png');
die(file_get_contents($image));
}
}
/**
* An example of aliasing an image to another site.
* The IP of your server will be visible in evilzone's logs
* each time someone views this page.
*/
if ($f == 'hacking.jpg' || $f = 'hacking.foo') {
header('Content-Type: image/png');
die(file_get_contents('https://evilzone.org/logo_02.png'));
}
/**
* You'll obviously need a database with info for this to work.
*/
if ($f == 'database.png') {
$stmt = $pdo->prepare('SELECT image_data, content_type FROM images WHERE image_name = :name');
$stmt->execute(array('name' => $f));
$row = $stmt->fetch();
header('Content-Type: ' . $row['content_type']);
die($row['image_data']);
}
/**
* Get from local filesystem
* 1) Don't trust user's file extension for Content-Type and do some
* long switch/case. Just read it from the source file.
*/
if ($f && file_exists($f)) {
$contentType = exif_imagetype($f);
header("Content-Type: {$contentType}");
die(file_get_contents($f));
}
}
/**
* Make it look like native 404 page
*/
header('HTTP/1.0 404 - Not Found');
$url = htmlentities($_SERVER['REQUEST_URI']);
$html=<<<EOF
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL {$url} was not found on this server.</p>
<hr>
<address>Apache/2.4.7 (Ubuntu) Server at {$SERVER['SERVER_NAME']} Port {$_SERVER['SERVER_PORT']}</address>
</body></html>
EOF;
die($html);
And the .htaccess rewrite rule:
RewriteEngine On
# Redirect /<file>.<ext> to index.php?f=<file>.<ext> [NoCasesensitive, Last]
RewriteRule ([^\.]+)\.(png|jpg|gif)$ index.php?f=$1.$2 [NC,L]