我正在为我的网站创建一个管理员端。
我创建了一个添加页面,在这个页面中有一个包含几个字段的表单。其中 2 个是供我上传图片的上传按钮。另一个是我输入 URL 的填充框。
我已经设置了它,以便它们都更新相同的 mysql 字段,并且当两者都输入时,填充框是优先级的。
然而。搜索框很好,因为它正确保存了链接,但是使用选择框选择图像只会将文件名保存在 mysql 的此字段中,例如:xxxxxxxxxxxxx.png
因此,当我的网站显示这些图像时,它不会显示上传的图像。显然是因为这些保存在我的计算机上,而不是我的 cpanel 上。
所以我的问题是:如何使用上传框上传图像并将其保存到我的 /images 文件夹,然后让 mysql 在相关字段中显示该 URL 链接?
我的 add.php 代码是这样的:
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (!empty($_POST['image']))
{
$image = $_POST['image'];
}
else
{
$image = $_POST['imageupload'];
if (isset($_FILES['Filedata']))
{
$filename = $_FILES['Filedata']['name'];
$targetpath = "/images/" . $filename; //target directory relative to script location
$copy = copy($_FILES['Filedata']['tmp_name'], $targetpath);
if (!$copy)
$error = "Image was not uploaded successfully";
}
}
$link = $_POST['link'];
$category = $_POST['category'];
$brand = $_POST['brand'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO mobi (promo_title, promo_content, promo_image, promo_link, promo_cat, promo_name) VALUES(?, ?, ?, ?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $image);
$query->bindValue(4, $link);
$query->bindValue(5, $category);
$query->bindValue(6, $brand);
$query->execute();
header('location: index.php');
}
}
?>
<?php
if (isset($_FILES['Filedata']))
{
// And if it was ok
if ($_FILES['Filedata']['error'] !== UPLOAD_ERR_OK)
exit('Upload failed. Error code: ' . $_FILES['image']['error']);
$filename = $_FILES['Filedata']['name'];
$targetpath = "../img/news/" . $filename; //target directory relative to script location
$copy = copy($_FILES['Filedata']['tmp_name'], $targetpath);
}
?>
<html>
<head>
<title>Add Article</title>
<link rel="stylesheet" href="../other.css" />
</head>
<body>
<div class="container">
<a href="index.php" id="logo"><b>← Back</b></a>
<br />
<div align="center">
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input name="imageupload" type="file" id="image" placeholder="Imageupload" />
<input type="text" name="image" placeholder="Image" /><br /><br />
<input type="link" name="link" placeholder="Link" /><br /><br />
<input type="category" name="category" placeholder="Category" /><br /><br />
<input type="category" name="brand" placeholder="Brand" /><br /><br />
<input type="submit" value="Add Article" />
</form>
</div>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
?>
请帮忙。谢谢。