【问题标题】:php fopen dynamic file pathphp fopen 动态文件路径
【发布时间】:2013-07-07 08:28:59
【问题描述】:

我正在尝试制作允许用户将图像上传到我的数据库的简单脚本。我的 php fopen 函数有问题。

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

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

这个简单的表单只返回文件的字符串值,我需要使用需要文件直接路径的 fopen 函数打开文件。

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

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

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

【问题讨论】:

标签: php fopen


【解决方案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>";

?>

【讨论】:

    【解决方案2】:
    if ($_FILES["file"]["error"] == 0) {
        fopen($_FILES["img"]["tmp_name"], 'r');
    }
    

    【讨论】:

    • $_FILES["img"]["tmp_name"] 已经包含上传文件的绝对路径
    • 我的错。不确定。谢谢。
    猜你喜欢
    • 2018-03-09
    • 1970-01-01
    • 2014-01-10
    • 2013-03-05
    • 2021-06-24
    • 2018-02-09
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    相关资源
    最近更新 更多