使用php mysql将文件上传到服务器

时间:2012-02-03 17:42:38

标签: php mysql

我通过填写表单将文件上传到服务器。应该上传文件,并在mysql表中创建包含许多数据的记录。这是我指定上传路径的方式:

$upload_path = "upload/";

在public_html文件夹中,我有所有必需的.php文件和预先创建的上传文件夹。上传成功,mysql表有一条新记录,一切似乎都没问题,除了我在public_html / upload文件夹中看不到该文件。

我知道这一定是一个新手问题,我需要帮助。

   $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.tif','.doc','.docx','.xls','.xlsx','.pdf','.psd');
     $filename = $_FILES['file']['name'];
     $max_filesize = 524288; //0.5MB
     $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
     //$upload_path = "C:/wamp/www/upload/";    //'./files/';
     $upload_path = "upload/";
      if(!in_array($ext,$allowed_filetypes))
      {
        die('The file you attempted to upload is not allowed or you haven not selected any files!');
      }
      if(filesize($_FILES['file']['tmp_name']) > $max_filesize)
      {
        die('The file you attempted to upload is too large.');
      }
      if(!is_writable($upload_path))
      {
        die('Invalid or non-writable folder');
      }


      if (file_exists($upload_path . $_FILES["file"]["name"]))
      {
        //echo $_FILES["file"]["name"] . " already exists. ";
    ?>
          <script type="text/javascript">
          alert('File with this name already exists!');
          </script>
    <?php

      }
      else
      {
        if(move_uploaded_file($_FILES['file']['tmp_name'],$upload_path . $filename))
        {
            ?>
          <script type="text/javascript">
            alert('Successful upload!');
          </script>
    <?php   
    }
//getting variables, insert into statement -> record added to table, this part is fine
    }
    ?>

2 个答案:

答案 0 :(得分:1)

也可能是未设置文件夹的权限,因此可以创建文件。这是通过两种方式之一完成的。

1)如果您具有root访问权限,则可以让运行Web服务器的用户使用chown命令拥有该目录。

chown username dirpath

2)如果您没有root访问权限,则必须使目录世界可写。

chmod 777 dirpath

试试这个代码......

$uploads_dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads';

if(is_dir($upload_dir) && is_writable($upload_dir))
{
  // put your code to handle uploaded file here
}
else
{
    echo "Sorry the upload file does not exist or I can not save the file there due to directory permissions";
}

答案 1 :(得分:0)

当PHP上传时,它会上传到tmp目录(通常由php.ini设置),然后使用move_uploaded_file(http://php.net/manual/en/function.move-uploaded-file.php)来重命名并将文件移动到您想要的位置。

你错过了这一步吗?很难从你问题的信息中分辨出来。