[抱歉,我的问题标题没有太多描述性,我正在努力正确地表达问题的内容。我有一个脚本add-new-post.php
,可以将新博客文章添加到数据库中。我在文件上传过程中苦苦挣扎,因为上传文件与执行上传的脚本相距几个级别。
文件位置:
public_html/content/uploads/imgs
public_html/content/themes/admin-cm/post/add-new-post.php
因此,脚本正在尝试将文件上传到第一个目录。以下是有关文件上传的相关代码段,此刻,我只是想让它向页面回显一些信息,以便我可以看到发生了什么:
if ( !empty( $_FILES[ "featured_image" ][ "name" ] ) ) {
$target_dir = '/content/uploads/imgs/';
$target_file = dirname(__FILES__, 4 ) . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
$upload_ok = 1;
$image_file_type = strtolower( pathinfo( $target_file, PATHINFO_EXTENSION ) );
$check = getimagesize( $_FILES[ "featured_image" ][ "tmp_name" ] );
if ( $check !== false ) {
echo "File is an image - " . $check[ "mime" ] . ".";
echo "<br>" . $target_file;
$upload_ok = 1;
} else {
$errors[] = "The uploaded file is not an image.";
$upload_ok = 0;
}
if ( file_exists( $target_file ) ) {
echo "Sorry, this file already exists.";
$upload_ok = 0;
} else {
echo "<br>This image doesn't exist already.";
}
if ( $_FILES[ "featured_image" ][ "size" ] > 500000 ) {
echo "Sorry, your file is too large.";
$upload_ok = 0;
}
if ( $upload_ok ) {
if ( move_uploaded_file( $_FILES[ "featured_image" ][ "name" ], $target_file ) ) {
echo "<br>Successfully uploaded the image.";
} else {
echo "<br>Couldn't upload the image.";
}
}
}
[我猜我的问题是目录,我尝试了几种输入目标目录的方法,但似乎没有效果(例如,最初将$target_file
变量输入为字符串,即"../../../../content/uploads/imgs
)。我正在尝试通过上载目录中当前不存在的文件来测试这一点,以下是打印到页面上的内容:
File is an image - image/jpeg.
./content/uploads/imgs/post-img-8.jpg
This image doesn't exist already.
Couldn't upload the image.
对我而言,目标目录看起来正确。.我也尝试过substr()
丢失点,并尝试使其失去./
。有什么想法我做错了吗?
已解决(在评论中感谢Martin):
我替换了以下内容:
$target_dir = '/content/uploads/imgs/';
$target_file = dirname(__FILES__, 4 ) . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
with:
$target_dir ="content/uploads/imgs/";
$target_file = $_SERVER[ "DOCUMENT_ROOT" ] . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
您应使用$_SERVER['DOCUMENT_ROOT']
设置绝对文件路径,以将文件保存到服务器的文件系统。
$_SERVER['DOCUMENT_ROOT']
通常是$_SERVER['DOCUMENT_ROOT']
,并且该文件夹中是世界可访问的网站;
/user/domain/public_html
与:]相同>
https://www.mywebsite.co.uk/somefolder/somefile.php
因此将文件保存到:
$_SERVER['DOCUMENT_ROOT']."/somefolder/somefile.php";
,您将其保存到www.mywebsite.org/content/uploads/imgs/post-img-8.jpg
请勿使用给定的$_SERVER['DOCUMENT_ROOT']."/content/uploads/imgs/post-img-8.jpg";
保存文件值,可以很容易地折衷该值,应该至少使用正则表达式转义以删除任何无效字符。
$_FILES[ "featured_image" ][ "name" ]
不信任上载MIME类型。甚至$name = preg_replace('/[^a-z0-9_-]/i','',$_FILES['featured_image']['name']);
也会受到损害。最好的建议是使用PHP getimagesize
函数。
imagecreatefromjpeg
数据中,这尤其可以包含JPG图像imagecreatefromjpeg
。