如何使用PHP检索上传的文件

Ane*_*ele 1 php mysql file-upload download

好.我在2011年8月24日以来在这个网站上搜索.(并不重要)一种显示用户上传文件的方法.我在管理员方面有我的表格,一切正常.我还有一个表格,显示用户填写的表格中的任何内容.但我无法在桌面上查看文件或其名称.

我的数据库表有一个主要标识auto_increment int(11)unsigned.

这是我写的代码:

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

$query = "INSERT INTO user_DB VALUES ('','$company', '$location', '$userfile' )";

//target to the path of my files
$target_path = "uploads/post_id/";
if(!is_dir($target_path)) mkdir($target_path);
$uploadfile = $target_path . basename($_FILES['userfile']['name']);

//Move the uploaded file to $taget_path
(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile));
Run Code Online (Sandbox Code Playgroud)

在您填写详细信息的表单上,我有以下内容:

<tr>
<td><label for="company_name">Company Name</label></td>
<td><input type="text" name="company" id="company" value="" size="38" /></td>
</tr>
<tr>
<td><label for="location">Location</label></td>
<td><input type="text" name="location" id="location" value="" /></td>
</tr>
<tr>
<td>Upload a File:</td>
<td><input name="userfile" id="userfile" type="file" /></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

显示查询结果的前端表格就像这样,只是文件场.

echo "<td>";
echo "<a href=../admin/uploads/post_id/> $row'userfile'</a>";
echo "</td>";
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到我正在尝试获取文件名以及文件本身.如果是pdf/jpg/doc,我应该能够在单击链接时查看/下载它.

蚂蚁想法......

Tre*_*non 6

一些建议,你可以改变什么来使这个工作.

1.上传表格

你的表格标签是什么样的?不要忘记enctype按以下方式包含参数:

<form type="post" action="" enctype="multipart/form-data">
    ...
</form>
Run Code Online (Sandbox Code Playgroud)

2.消毒

$company  = mysql_real_escape_string($_POST['company']); 
$location = mysql_real_escape_string($_POST['location']);
$pic      = mysql_real_escape_string($_FILES['userfile']['name']);
Run Code Online (Sandbox Code Playgroud)

以上几行是帮助防止查询遭受SQL注入攻击的第一步.

3. SQL查询

$userfile因为您实际上已将文件名分配给而不存在,$pic所以您的查询应如下所示:

$query = "INSERT INTO user_DB 
          VALUES ('','$company', '$location', '$pic')";
Run Code Online (Sandbox Code Playgroud)

4. HTML输出

现在链接到输出表中的文件:

echo "<td>";
echo "<a href=" . $target_path . basename($row['userfile']) . ">
         {$row['userfile']}</a>";
echo "</td>";
Run Code Online (Sandbox Code Playgroud)