如何在php中使用函数move_uploaded_file

时间:2016-05-27 19:59:21

标签: php

此代码位于“upload.php”

<?php
    session_start();
        $id = $_SESSION['user_id'];
        $pic = $_FILES['pic']["name"];
        $folder = "../images/users/";
        move_uploaded_file($_FILES['pic']["tmp_name"], "$folder".$pic); 

        $mysqli = connectDB();
        upload($id,$pic,$mysqli);
    ?>

功能上传

function upload($id,$pic,$mysqli)
    {
        $pic = $mysqli->real_escape_string($pic);

        $sql = "UPDATE users SET pic = '$pic' WHERE id = '$id'";
        $result = $mysqli->query($sql);
    }

和html中的代码

<form name="submit" action="include/upload.php" method="post">
    <input type="file" value="Choose file" accept="image/*" id="pic" name="pic">
    <input type="submit" value="Upload" name="submit">
</form>

它不起作用。图像不移动文件夹和图像路径不插入数据库。

2 个答案:

答案 0 :(得分:0)

而不是:

move_uploaded_file($_FILES['pic']["tmp_name"], "$folder".$pic);

你可以这样做:

move_uploaded_file($_FILES["pic"]["tmp_name"], $folder.$pic); // Note the single / double quotes

但更容易:

<?php
    session_start();
    $id = $_SESSION['user_id'];
    $pic = $_FILES["pic"]["name"];
    $folder = "../images/users/";
    $path = $folder.$pic; // New variable

    if( move_uploaded_file($_FILES["pic"]["tmp_name"], $path) ) {
        $mysqli = connectDB();
        if( upload($id, $path, $mysqli) ) {
           echo 'File uploaded';
        } else {
          echo 'Something went wrong uploading file';
        }
    } else {
       echo 'Something went wrong uploading file';
    }

因此功能变为:

function upload($id, $path, $mysqli)
    {
        $path = $mysqli->real_escape_string($path);

        $sql = "UPDATE `users` SET `pic` = '$pic' WHERE `id` = $id";
        $result = $mysqli->query($sql);

        return $result; // returns true or false
    } 

在表名和列名周围添加反引号可防止出现名为mysql保留字的错误。因为$id是一个整数(在大多数情况下)。你不应该引用它。这是因为你从整数中创建一个字符串,这是你不想做的事情,因为整数更快更安全。

要使html清晰,您需要上传文件,您需要在表单中添加内容。因此表格变为:

<form name="submit" action="include/upload.php" method="post" enctype="multipart/form-data">
    <input type="file" value="Choose file" accept="image/*" id="pic" name="pic">
    <input type="submit" value="Upload" name="submit">
</form>

答案 1 :(得分:0)

表单标签的格式应该是:

< form name="submit" action="include/upload.php" method="post" enctype="multipart/form-data" >

(在表单标签中添加 enctype="multipart/form-data",这将解决您的问题。)