【发布时间】:2020-03-05 10:55:59
【问题描述】:
抱歉,我无法在我的问题标题中提供更多描述性,我正在努力正确地表述这个问题。我有一个脚本add-new-post.php,它向数据库添加了一个新的博客文章。我在文件上传过程中苦苦挣扎,因为上传文件距离正在上传的脚本只有几个级别。
文件位置:
public_html/content/uploads/imgs
public_html/content/themes/admin-cm/post/add-new-post.php
因此,脚本正在尝试将文件上传到第一个目录。下面是有关文件上传的相关 sn-p,目前我只是让它在页面上回显一些信息,这样我就可以看到发生了什么:
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() 丢失点并尝试丢失./。任何想法我做错了什么?
已解决(感谢 cmets 中的 Martin):
我替换了以下内容:
$target_dir = '/content/uploads/imgs/';
$target_file = dirname(__FILES__, 4 ) . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
与:
$target_dir ="content/uploads/imgs/";
$target_file = $_SERVER[ "DOCUMENT_ROOT" ] . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
【问题讨论】:
-
$target_dir = '/content/uploads/imgs/';——这是一个指向服务器文件系统根目录的绝对路径。我怀疑您实际上在根级别有content......?我想您可能在这里将 URL 与文件系统路径混淆了?
标签: php file-upload