php fopen动态文件路径

时间:2013-07-07 08:29:00

标签: 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函数打开它。

2 个答案:

答案 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>";

?>

答案 1 :(得分:0)

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