文件不会移动到服务器文件夹

时间:2018-08-12 06:38:32

标签: php mysql

我创建了一个php文件,该文件的工作是将文件保存在服务器文件夹中,然后将该文件的url保存在数据库中,但是它们存在一些问题,应该保存url,但文件不会移动服务器文件夹。如果用户上传文件,我想这样做,那么该文件应保存在以公共HTML 创建的特定文件夹中,并将该文件的url保存到数据库中。但是在我的情况下,仅将url保存到数据库,但文件未在特定文件夹中移动。我不知道发生这种情况。 我的上传代码是          `

define('DB_HOST','localhost');
define('DB_USERNAME','username');
define('DB_PASSWORD','password');
define('DB_NAME','dbname');

//this is our upload folder
$upload_path = 'pdffiles/';


//creating the upload url
$upload_url = 'https://balajismajkalyansantha.000webhostapp.com/'.$upload_path;

//response array
$response = array();


if($_SERVER['REQUEST_METHOD']=='POST'){

    //checking the required parameters from the request
    if(isset($_POST['name']) and isset($_FILES['pdf']['name'])){

        //connecting to the database
        $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');

        //getting name from the request
        $name = $_POST['name'];

        //getting file info from the request
        $fileinfo = pathinfo($_FILES['pdf']['name']);

        //getting the file extension
        $extension = $fileinfo['extension'];

        //file url to store in the database
        $file_url = $upload_url . getFileName() . '.' . $extension;

        //file path to upload in the server
        $file_path = $upload_path . getFileName() . '.'. $extension;

        //trying to save the file in the directory
        try{
            //saving the file
            move_uploaded_file($_FILES['pdf']['tmp_name'],$file_path);
            $sql = "INSERT INTO  `id4834528_try`.`pdf` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');";

            //adding the path and name to database
            if(mysqli_query($con,$sql)){

                //filling response array with values
                $response['error'] = false;
                $response['url'] = $file_url;
                $response['name'] = $name;
            }
            //if some error occurred
        }catch(Exception $e){
            $response['error']=true;
            $response['message']=$e->getMessage();
        } 
        //closing the connection
        mysqli_close($con);
    }else{
        $response['error']=true;
        $response['message']='Please choose a file';
    }

    //displaying the response
    echo json_encode($response);
}

/*
We are generating the file name
so this method will return a file name for the image to be upload
*/
function getFileName(){
    $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');
    $sql = "SELECT max(id) as id FROM pdf";
    $result = mysqli_fetch_array(mysqli_query($con,$sql));

    mysqli_close($con);

        if($result['id']==null)
            return 1;
        else
            return ++$result['id'];
    }`

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

确保文件夹“ pdffiles”对此文件具有公共写入权限。 (0777)