【发布时间】:2023-03-27 16:58:01
【问题描述】:
我正在学习在 udemy 上使用 php 上传图像文件的教程。我可以选择一张图片并将其上传到一个文件夹中,没有任何问题。
当我在图片上传到文件夹后点击图片时,windows photo viewer 提示:“photo.png 您似乎没有查看此文件的权限。请检查权限并重试”。
当我检查权限时,它说“您必须具有读取权限才能查看此文件的属性”。
我使用了设置为0755的chmod函数,它允许所有者读取和写入,并让其他人读取它。我尝试更改 chmod 代码,但没有帮助。
我认为这与我的服务器权限有关,但在谷歌上找不到任何解决方案。我的图片已上传到 Abyss Web Server。
代码如下:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function upload_file() {
//setup
$tmp_name = $_FILES['file']['tmp_name'];
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES['file']['name']);
$max_file_size = 5000000; //5mb
$allowed_file_types = array('application/pdf; charset=binary');
$allowed_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
//check if image type is allowed
$image_check = getimagesize($tmp_name);
if(! in_array($image_check[2], $allowed_image_types)) {
//if not allowed image check if allowed file type
exec('file -bi' . $tmp_name, $file_check);
if(! in_array($file_check[0], $allowed_file_types)) {
return 'This file type is not allowed';
}
}
//check if file already exists
if(file_exists($target_file)) {
return 'Sorry that file already exists';
}
//check file size
if(file_exists($target_file)) {
return 'Sorry this file is too big';
}
//store the file
if(move_uploaded_file($tmp_name, $target_file)) {
chmod($target_file, 0644);
return 'Your file was uploaded';
}
else {
return 'There was a problem storing your file. Try again?';
}
}
if(! empty($_FILES)) {
echo upload_file();
}
?>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file">
<input type="submit" Value="upload">
</form>
【问题讨论】:
-
尝试使用 HTML 在某个随机页面中打印图像,看看它是否加载并显示它。如果确实发生了这种情况,那么您可能会遇到 热链接保护 问题,可以通过编辑目录或最近的父目录中的
.htaccess文件来解决该问题。郑重声明,我从未使用过深渊网络服务器,也从未听说过。 -
啊,谢谢,当作为 html/php 文件调用时它工作正常,只是无法在本地访问它,这还不错。谢谢你的建议! :) :)
-
好吧!这称为热链接保护。有些人不喜欢访问他们的受版权保护的图像,因此避免没有经验的人(例如,“用户空间中的人”)这样做的一种方法是启用此保护。例如,cPanel 为此提供了一个工具。您可以查看名为
.htaccess的隐藏文件是否在您的服务器中,然后删除或修改它。那,如果您真的需要以这种方式访问它。我应该写一些答案只是为了正式结束这个问题,还是你觉得你的问题没有得到回答? -
这解释了为什么我在文件目录中找不到 .htaccess 文件:) cpanel 它是:) 当然,将它标记为最佳答案会很棒:) 非常感谢您的帮助! :)
-
太棒了,我很高兴听到这个消息。谢谢你也这么好心,我在这里不经常看到这种情况。祝您在 Udemy 上的项目和学习顺利!
标签: php permissions image-uploading