就像我在之前的问题中提到的那样,我目前正在自己的论坛上工作,这是我过去几个月一直在努力的。我希望能够允许用户在帖子或回复中上传图片。
我知道HTML看起来像这样:
<input type="file" name="imgUpload" id="imgUpload">
但它是处理它然后实际显示图像的PHP。我已经看过W3Schools的教程https://www.w3schools.com/php/php_file_upload.asp,但我无法让它发挥作用。
以下是用户在我的网站上提交新帖子的示例:
<?php
session_start();
ob_start();
$host = "host"; // Host name
$username = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "db"; // Database name
$tbl_name = "users"; // Table name
$tbl_name2 = "fquestions"; // Table name
$error_page ="../error-message"; //Error Page
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$email = $_SESSION['email'];
$sql = "SELECT * FROM $tbl_name WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_array($result);
//Checks if user is logged in and account is active (not banned)
if($_SESSION['logged_in'] == true && $rows['active'] == 1) {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'secret_key',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
$_SESSION['message'] = 'CAPTCHA Not Checked!';
header( "Location: $error_page" );
} else {
// get data that sent from form
$topic = $_POST['topic'];
$username = $_SESSION['username'];
$detail = $_POST['detail'];
$email = $_SESSION['email'];
$datetime = date("d/m/y h:i:s"); //create date time
//Inserts information to database
$sql2 = "INSERT INTO $tbl_name2(topic, detail, username, email, datetime)VALUES('$topic', '$detail', '$username', '$email', '$datetime')";
if (empty($topic) || empty($username) || empty($email)) {
$_SESSION['message'] = 'Missing information!';
header( "Location: $error_page" );
} else {
$result2 = mysqli_query($conn, $sql2);
}
if($result) {
$sql3 = "SELECT MAX(id) FROM $tbl_name2";
$result3 = mysqli_query($conn, $sql3);
$row = mysqli_fetch_row($result3);
$id = $row[0];
//Redirects to topic page
header('Location: view-topic?id='.$id.'');
} else {
echo "ERROR";
}
mysqli_close($conn);
}
} else {
echo '<p>You must be signed in to add a new topic</p>';
}
ob_end_flush();
?>
CAPTCHA检查完成后,我希望能够检查用户是否提交了图像。如果有,请将其上传到注册时创建的目录,例如:上传/用户名/然后处理文本。如果没有,那么它只是正常处理他们输入的文本。
至于将它显示到页面我不太确定,因为你需要某种ID我想或者可能会得到图像名称来显示它。如果我能让它发挥作用,我将非常感激。