2013-07-07 80 views
1

我想制作一个简单的脚本,允许用户将图像上传到我的数据库。我有php fopen函数的问题。php fopen动态文件路径

我需要允许用户上传他的计算机上的任何图像文件,因此文件的路径每次都是不同的。

<form method="POST"> 
     <input type="file" name="img"> 
     <input type="submit" value="uload"> 
    </form> 

这种简单的形式返回文件的唯一字符串值,我需要使用,需要的文件直接路径fopen函数打开文件。

fopen($_POST["img"],"r"); 

只有当文件与php脚本位于同一目录时,这才有效。

所以我问是否有办法如何找到文件的存储位置,所以我可以打开它使用fopen函数。

+1

HTTP:// WWW。 w3schools.com/php/php_file_upload.asp – WooDzu

+0

好的,这解释了一切,非常感谢。 –

回答

1

我首先建议你必须看看PHP手册中关于文件上传:http://www.php.net/manual/en/features.file-upload.post-method.php

因为这样的代码可以在你的系统中打开保障厅。一般来说,不建议在做一些检查之前直接执行用户文件,例如病毒扫描,图像的二进制签名,通过尝试调整大小来验证图像等等。从性能的角度来看,不建议将它们保存在数据库中。另外,如果您选择上传到目录,则其权限应设置正确。

我将在这里复制修改到您的情况下,从PHP手册样本文件上传代码:

HTML部分:

<!-- The data encoding type, enctype, MUST be specified as below --> 
<form enctype="multipart/form-data" action="YOUR_Upload_FILE.php" method="POST"> 
    <!-- Name of input element determines name in $_FILES array --> 
    <input name="img" type="file" /> 
    <input type="submit" value="Send File" /> 
</form> 

PHP部分:

<?php 
$uploaddir = '/var/www/uploads/'; 
$uploadfile = $uploaddir . basename($_FILES['img']['name']); 

//At this point you may like to check: 
/* 
1. Upload Errors in $_FILES 
2. Do virus check. 
3. Do binary check for the images type 
4. Do size check for the image 
5. Do actual image resize to confirm it is valid image. 
*/ 

//After everything is safe, you move the temporary file to your permanent store. 
echo '<pre>'; 
if (move_uploaded_file($_FILES['img']['tmp_name'], $uploadfile)) { 
    echo "File is valid, and was successfully uploaded.\n"; 
} else { 
    echo "Possible file upload attack!\n"; 
} 

echo 'Here is some more debugging info:'; 
print_r($_FILES); 

print "</pre>"; 

?> 
0
if ($_FILES["file"]["error"] == 0) { 
    fopen($_FILES["img"]["tmp_name"], 'r'); 
} 
+1

$ _FILES [“img”] [“tmp_name”]已包含上传文件的绝对路径 – WooDzu

+0

我的不好。不确定。谢谢。 –