使用php Form将图像上传到服务器

时间:2015-03-09 20:47:16

标签: php html

我正在尝试让用户将图像上传到我创建的目录中的服务器。用户使用表单选择图像然后我使用PHP代码将图像上传到目录“image / Profile_Pic /”以及它的位置我的数据库。但是当我测试我的代码时,它总是让我无法上传文件,我的表中没有任何内容出现在用户的数据中,我无法弄清楚原因。

HTML表格:

<form enctype="multipart/form-data" action="upload.php" method="POST"> 
        Photo: <input type="file" name="photo"><br>  
        <input type="submit" value="Add">  
</form>

upload.php的:

<?php   
    session_start();
    $user = $_SESSION['user'];
    $host_name = "";
    $user_name = "";
    $password = "";
    $db_name = "";
    $db_link = mysqli_connect($host_name, $user_name, $password, $db_name) or die(mysqli_error($db_link));

error_reporting(E_ALL); ini_set('display_errors', 1);

//This is the directory where images will be saved  
$target = "image/Profile_Pic/";  
$target = $target . basename( $_FILES['photo']['name']);  


$target = $target . $_FILES['photo']['name'];   

//This gets all the other information from the form  
$pic=($_FILES['photo']['name']);  

//Writes the information to the database  

$table_name = "User";
$query = "UPDATE $table_name SET Profile_Pic = '$pic' WHERE Username='$user';";
$result = mysqli_query($db_link, $query) or die(mysqli_error($db_link));


//Writes the photo to the server  
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))  {   
    //Tells you if its all ok  
    echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory $user";
}else{   
    //Gives and error if its not  
    echo "Sorry, there was a problem uploading your file.";  
} 

mysqli_close($db_link);
?>

所以在你的帮助之后,我设法让这段代码起作用了。但现在图像上传的名称重复,如image.jpgimage.jpg。我如何解决这个问题,以便用户是$user中存储的当前会话用户的imageuser.jpg?

2 个答案:

答案 0 :(得分:0)

//This is the directory where images will be saved  
$target = __DIR__ . "image/Profile_Pic/";
if (!file_exists($target)) {
    mkdir($target);
}
$target = $target . $_FILES['photo']['name'];  

basename适用于完整路径,所以你应该这样使用它。

另外move_uploaded_file应该使用$ _FILES [&#39;照片&#39;] [&#39; tmp_name&#39;]而不仅仅是$ _FILES [&#39;照片&#39;]

答案 1 :(得分:0)

$target = "image/Profile_Pic/";  
$target = $target . basename( $_FILES['photo']['name']);  


$target = $target . $_FILES['photo']['name'];

这就是原因。您将名称两次分配给$target变量。

删除最后一行并且不使用basename(),因为它在此代码中毫无意义。