让我们从头开始。我是一名学生,最近上了一门带有数据库的网络开发课程(我确定该课程的英文名称不同),我正在创建一个动态网站。您可以添加、编辑和删除站点/文章。
我希望能够在您的“标签”旁边的导航栏上上传您自己的徽标,但我走到了死胡同。我在 youtube 上关注了一个人,他解释了如何将文件上传到我的服务器到特定文件夹中,并将其限制为仅某些文件类型和特定文件大小。
但是现在我需要检索该图像的文件路径,以便我可以在网站的导航栏上将其显示为徽标。
我开始思考的方式是,我需要以某种方式获取最新修改的文件,然后以某种方式获取其位置/文件路径,然后将其保存到变量中。
我上传图像的当前代码是这样的:它在根文件夹中,名为“upload.php”
<?php
if (isset($_POST['upload'])) {
$file = $_FILES['file'];
/* $_FILES gives you an array of info of an file */
/* below i give each variable some info from my file */
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
/* Ext = extension.*/
/* i only want .jpg and. png files on my site */
/* Here i check if it has .jpg or png at the end of the file name */
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
/* Creating an array with accepted file endings */
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
/* newimages get uniq names inside database */
/* in this case it uses milliseconds */
$fileNameNew = uniqid('', true).".".$fileActualExt;
/* set file destination */
$fileDestination = 'images/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
header('Location: index.php?uploadsuccess');
}else {
echo "Your file was to big! Make sure it's less than 1MB!";
}
}else {
echo "There was an error uploading your file! Please try again!";
}
}else {
echo "You cannot Upload files of this type!";
}
}
然后我需要将文件路径放入一个变量中,然后将其添加到:
<img src="images/file_name.jpg>" class="navbar-logo" alt="">
然后用我的变量替换 file_name.jpg。
我不明白我怎么能做到这一点。我没有这方面的知识,我希望转向stackoverflow我可以得到一些帮助并在途中学习一些新东西。
我已经搜索并尝试了这段代码:(写在底部的“upload.php”文件内,在“if”语句之外。
/* get latest image name */
$path = "images";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
也许我无法从我试图从中获取它的文件中访问变量?如前所述,此文件(“upload.php”)位于根文件夹中。我试图在以下位置使用变量 $latest_filename:root/views/master.php
我不知道还要添加什么,我试着让它尽可能透明。