更新脚本 PHP/HTML


Update Scripts PHP/HTML

我有一个非常简单的网站,有一个按钮可以让人们发布照片。我写了一个PHP脚本,将照片上传到我的网络服务器。

我现在的问题是,我将如何让网站更新其主页以包含新照片?我需要某种脚本来生成 HTML 并保存文件吗?我知道Wordpress和其他一些公司提供该功能,但我只是做了一个非常简单的设置,不想注册或支付帐户。

任何线索都会有所帮助。谢谢!

在为主页提供服务的 PHP 文件中,您需要读取上传的文件并为其创建图像标签。如果将文件移动到 Web 服务器根目录下的目录,则可以使用以下命令。

主页.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 />";
        }
    }
}
?>

但是,您不应该将用户上传的内容存储在Web服务器的根目录下。这是一个替代方案,可以让您朝着正确的方向前进。

上传.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 />";
}

主页.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 />";
        }
    }
}
?>

图像提取器.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();
}