2012-11-01 160 views
0

在我的网站上,我有2个独立的地方供用户上传图片。第一个完美的作品。第二个不是。据我所知,他们是完全一样的。为了测试,我在两者上都使用了相同的图像,它在第一个而不是第二个上进行。这里是从非工作的代码:PHP图片未上传到网站

<?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

这两个地方都在同一台服务器上? – Bgi

+0

你可以把你的HTML代码? – George

+0

两个文件都移动到gallery_pics?检查该文件夹的权限。 – Bgi

回答

0

这两个脚本都驻留在同一个目录中吗?如果没有,请确保您指定正确的相对或完整路径,通过斜线像这样开头:

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

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

$rand_num = rand(1111111111, 9999999999); 
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."); 
} 
?>