1

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

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

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

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

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

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

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

4

2 回答 2

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

?>
于 2013-07-07T10:22:23.307 回答
0
if ($_FILES["file"]["error"] == 0) {
    fopen($_FILES["img"]["tmp_name"], 'r');
}
于 2013-07-07T08:38:59.477 回答