0

在我的网站上,我有 2 个不同的地方供用户上传图片。第一个完美运行。第二个没有。据我所知,它们完全相同。为了测试,我在两者上都使用了相同的图像,它适用于第一个,但不是第二个。这是非工作代码的代码:

<?php
include('cn.php');

$name = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
$temp = $_FILES['image']['tmp_name'];
$error = $_FILES['image']['error'];

echo $name; //Doesnt echo anything

$rand_num = rand(1, 1000000000);

$name = $rand_num . "_" . $name;

echo $name; //Echos just the random number followed by _

if ($error > 0) { 
    die("Error uploading file! Go back to the <a href='gallery.php'>gallery</a> page and try again.");
} else {
    $sql = "INSERT INTO gallery (image) VALUES ('".$name."')"; //Inserts the random number to the database
    $query = mysql_query($sql) or die(mysql_error());
    echo $sql; 

    move_uploaded_file($temp, "gallery_pics/$name"); //Doesn't move the file.  gallery_pics exists, if that matters
    echo "Upload complete! Go back to the <a href='gallery.php'>album</a>.";
}

?>

如果有人可以请在这里帮助我。我确信这很简单,但我还没有找到任何有帮助的东西。谢谢!

编辑:代码上方有两行无法正确显示。一个启动php,另一个打开数据库。

4

2 回答 2

0

在开发或尝试查找故障时启用错误报告,同时检查您的服务器错误日志。检查$_FILES['image']['error']错误代码并相应地显示错误。试试下面的代码。希望能帮助到你

<?php
//Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors',1);

$error_types = array(
    0=>"There is no error, the file uploaded with success",
    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    3=>"The uploaded file was only partially uploaded",
    4=>"No file was uploaded",
    6=>"Missing a temporary folder"
);

if($_FILES['image']['error']==0) {
    // process
    $name = $_FILES['image']['name'];
    $type = $_FILES['image']['type'];
    $size = $_FILES['image']['size'];
    $temp = $_FILES['image']['tmp_name'];

    //mt_rand() = 0-RAND_MAX and make filename safe.
    $name = mt_rand()."_".preg_replace('/[^a-zA-Z0-9.-]/s', '_', $name);

    //insert into db, swich to PDO
    ...

    //Move file upload
    if (move_uploaded_file($_FILES['image']['tmp_name'], "gallery_pics/$name")) {
        echo "Upload complete! Go back to the <a href='gallery.php'>album</a>.";
    } else {
        echo "Failed to move uploaded file, check server logs!\n";
    }
} else {
    // error
    $error_message = $error_types[$_FILES['userfile']['error']];
    die("Error uploading file! ($error_message)<br/>Go back to the <a href='gallery.php'>gallery</a> page and try again.");
}
?>
于 2012-11-01T14:22:33.273 回答
0

两个脚本是否位于同一目录中?如果没有,请确保您指定正确的相对路径或完整路径,并在斜线前面,如下所示:

move_uploaded_file($temp, "/some_folder/gallery_pics/$name");

另外,你检查上传文件的扩展名吗?如果没有,例如,用户可以上传并执行一个 PHP 文件。顺便说一句,您的文件名这样看起来会更好:

$rand_num = rand(1111111111, 9999999999);
于 2012-11-01T14:11:20.367 回答