Reputation: 423
I have a very simple website that has a button to allow people to post a photo. I wrote a PHP script that uploads the photo to me web server.
My question now is how would I go about having the website update its homepage to include the new photo? Would I need some kind of script for generating HTML and saving it file? I know Wordpress and some other companies provide the functionality but I am just doing a very simple setup and don't feel like signing up or paying for an account.
Any leads would help. Thanks!
Upvotes: 1
Views: 57
Reputation: 16506
In the PHP file that serves your home page you will need to read the uploaded files and create image tags for them. If you moved the files to a directory under the web server root, you can use the following.
homepage.php
<?php
$path = 'where/your/images/are/';
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry !== '.' && $entry !== '..') {
echo "<img src='{$path}{$entry}' /><br />";
}
}
}
?>
But you should not be storing user uploaded content under your web server's root directory. Here is an alternative scheme to get you heading in the right direction.
upload.php
$uploadsDir = '/not/under/web/root';
if ($_FILES["file"]["error"] !== 0) {
header("HTTP/1.1 400 internal server error");
die();
}
$tmpName = $_FILES["file"]["tmp_name"];
$info = getimagesize($tmpName);
if (is_array($info) && array_key_exists('mime', $info) && $info['mime'] === 'image/jpeg') {
$name = sha1($tmpName) . '.jpg';
move_uploaded_file($tmpName, $uploadsDir . $name);
echo "Image uploaded<br />";
}
else {
echo "Sorry we only take jpegs<br />";
}
homepage.php
<?php
$path = '/not/under/web/root/';
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry !== '.' && $entry !== '..') {
echo "<img src='imagefetcher.php?id={$entry}' /><br />";
}
}
}
?>
imagefetcher.php
<?php
if (isset($_GET['img']) && !empty($_GET['img'])) {
$img = $_GET['img'];
// since we know that all files in this directory are sha1 digests followed by .jpg
// make sure that $img matches $pattern
$pattern = "/^[0-9a-f]{40}\\.jpg$/";
$success = preg_match($pattern, $img);
if ($success === 1) {
$fp = fopen('/not/under/web/root/' . $img, 'rb');
if ($fp) {
header("Content-Type: image/jpeg");
header("Content-Length: " . filesize('not/under/web/root/' . $img));
fpassthru($fp);
die();
}
fail();
}
fail();
}
fail();
function fail() {
header("HTTP/1.1 400 malformed request");
die();
}
Upvotes: 2