在我的网站上,我有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,另一个打开数据库。
答案 0 :(得分:0)
两个脚本都位于同一目录中吗?如果没有,请确保指定正确的相对路径或完整路径,前面加斜杠,如下所示:
move_uploaded_file($temp, "/some_folder/gallery_pics/$name");
另外,你检查上传文件的扩展名吗?如果没有,用户可以上传并执行PHP文件。顺便说一句,你的文件名看起来会更好:
$rand_num = rand(1111111111, 9999999999);
答案 1 :(得分: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.");
}
?>