本地,在PHP中,当我使用move_uploaded_file
上传文件(比如图片)时,绝对和相对目标路径都可以正常工作。
将这些图片上传到指定的目标路径后,只能使用相对路径在网页中显示这些图片 - 绝对路径无效。
为什么?!!
操作系统:Windows 7旗舰版
PHP Version 7.1.1
IDE:NetBeans IDE 8.2
项目结构:
example
│
└───Source Files
│
└upload_display_example
│ images
│ │(empty)
│ └
│ display_photo.php
│ photo_upload.php
│
photo_upload.php
<?php
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
// Both $absolute and $relative paths work
function get_path() {
// return $absolute = $_SERVER['DOCUMENT_ROOT'] . DS . 'example' . DS . 'upload_display_example' . DS . 'images' . DS;
return $relative = './images' . DS;
}
if (isset($_POST['submit'])) {
$tmp_path = $_FILES['file_upload']['tmp_name'];
$photo_name = $_FILES['file_upload']['name'];
$photo_path = get_path() . $_FILES['file_upload']['name'];
if (move_uploaded_file($tmp_path, $photo_path)) {
header("Location: display_photo.php?img=$photo_name");
die();
} else {
echo "<script>alert('Cannot move photo to permanent location.');</script>";
}
}
?>
<form action="photo_upload.php" enctype="multipart/form-data" method="POST">
<p><input type="file" name="file_upload" /></p>
<p><input type="submit" name="submit" value="Upload" /></p>
</form>
display_photo.php
<?php
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
// Only $relative path will work
function get_path() {
// return $absolute = $_SERVER['DOCUMENT_ROOT'] . DS . 'example' . DS . 'upload_display_example' . DS . 'images' . DS;
return $relative = './images' . DS;
}
if (isset($_GET['img'])) {
$photo_name = $_GET['img'];
$src = get_path() . $photo_name;
echo "<img src='$src' width='200' height='200' />";
}
?>
<br />
<br />
<a href="photo_upload.php">Upload a new photo</a>