1) Идея состоит в том, что эта страница требует, чтобы администратор был авторизован, чтобы иметь возможность получить доступ к странице добавления курса
(add-course. php). Любой человек, не вошедший в систему при попытке доступа к странице, должен быть перенаправлен для входа. php.
Но в настоящее время он не перенаправляет незарегистрированных пользователей на страницу входа, а вместо этого отображает содержимое страницы.
Как это исправить?
2) Страница содержит форму для администратора сайта для добавления курсов в базу данных. Но когда я нажимаю кнопку отправки
, после заполнения формы в базу данных ничего не добавляется.
Что я здесь делаю не так и как это исправить?
add-course. php:
<?php
// configuration
require("../includes/config.php");
// query users table to retrieve current admin's profile
if (array_key_exists('aid', $_GET)) {
// select a particular admin by id
$stmt = $pdo->prepare("SELECT * FROM admin WHERE aid=?", $_SESSION["aid"]);
$stmt->execute([$aid]);
$admin = $stmt->fetch(); # get admin data
//if (!$admin)
if (!$_SESSION["aid"] = $admin)
{
redirect("login.php");
exit();
}
//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("../classes/upload/upload_class.php");
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//This gets all the other information from the form
$coursename = $_POST["c_name"];
$course_title = $_POST["c_title"];
$meta_keywords = $_POST["meta_keywords"];
$meta_description = $_POST["meta_description"];
$short_desc = $_POST["short_desc"];
$coursedesc = $_POST["desc"];
//$userimage = ($_FILES["userimage"]["name"]);
$courseduration = $_POST["duration"];
$coursecode = $_POST["code"];
$fees = $_POST["fees"];
// validate submission
if (empty($_POST["c_name"]))
{
echo "Provide the course name.";
}
if (empty($_POST["duration"]))
{
echo "Provide the course duration.";
}
if (empty($_POST["code"]))
{
echo "Provide the course code.";
}
//This is the directory where images will be saved
$max_size = 1024*250; // the max. size for uploading
$my_upload = new file_upload;
$my_upload->upload_dir = "../images/courses/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = true;
$my_upload->the_temp_file = $_FILES['image']['tmp_name'];
$my_upload->the_file = $_FILES['image']['name'];
$my_upload->http_error = $_FILES['image']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file
{
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
$imagename = $my_upload->file_copy;
}
else
{
$imagename = "";
}
if (!empty($_POST["c_name"]))
{
// validate coursename
$c_name = ($_POST["c_name"]);
//if (!preg_match("/^[a-zA-Z0-9]*$/", $coursename))
//{
//adminapologize("A course name can only contain letters and numbers.");
//}
if (strlen($c_name) < 20 || strlen($c_name) > 50)
{
echo "A course name must be from 20 to 50 characters.";
}
// validate course duration
if (!preg_match("/^[a-zA-Z0-9]*$/", $courseduration))
{
echo "Invalid course duration.";
}
// validate course code
if (!preg_match("/^[a-zA-Z0-9]*$/", $coursecode))
{
echo "A course ID can only contain letters and numbers.";
}
//validate course code length
if (strlen($code) < 3 || strlen($code) > 10)
{
echo "A course code must be from 3 to 10 characters.";
}
if ($_POST["code"] === false)
{
echo "The course code has already been taken.";
}
// insert form input into database
$result = query("INSERT INTO courses (c_name, c_title, meta_keywords, meta_description, short_desc, desc, duration, code, fees, image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
$_POST["c_name"],
$_POST["c_title"],
$_POST["meta_keywords"],
$_POST["meta_description"],
$_POST["short_desc"],
$_POST["desc"],
$_POST["duration"],
$_POST["code"],
$_POST["fees"],
$imagename);
// if coursename has been taken
if ($coursename === false)
{
echo "An error occurred, while trying to add the course.";
}
// find out user's ID
$stmt = $pdo->query("SELECT LAST_INSERT_ID() AS user_id");
$id = $stmt[0]["user_id"];
// redirect to list courses
redirect("list-courses.php");
}
}
}
// render the header
include("templates/header.php");
// render add course form
include("templates/add-course_template.php");
// render the footer
include("templates/footer.php");
?>
config. php:
<?php
/**
* config.php
*
*
* Configures pages.
*/
// display errors, warnings, and notices
ini_set("display_errors", true);
error_reporting(E_ALL);
// requirements
require("constants.php");
require("functions.php");
// enable sessions
session_start();
// require authentication for most pages
if (!preg_match("{(admin/login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
{
if (empty($_SESSION["aid"]))
{
header("Location: login.php");
}
}
elseif (!preg_match("{(?:login|logout|register)\.php$}", $_SERVER["PHP_SELF"]))
{
if (empty($_SESSION["id"]))
{
header("Location: login.php");
}
}
?>
функций. php
<?php
/**
* functions.php
*
* FlamyTech Computer School
*
* Helper functions.
*/
require_once("constants.php");
/**
* Facilitates debugging by dumping contents of variable
* to browser.
*/
function dump($variable)
{
require("../templates/dump.php");
exit;
}
/*
Check if the admin is logged in or not
*/
function adminLogin()
{
if (!isset($_SESSION['aid']) || $_SESSION['aid'] == false) {
header('Location: login.php');
exit;
}
}
/**
* Logs out current user, if any. Based on Example #1 at
* http://us.php.net/manual/en/function.session-destroy.php.
*/
function logout()
{
// unset any session variables
$_SESSION = [];
// expire cookie
if (!empty($_COOKIE[session_name()]))
{
setcookie(session_name(), "", time() - 42000);
}
// destroy session
session_destroy();
}
//Properly connect to Mysql database using PDO./*
$host = 'localhost';
$db_name = 'comschool';
$db_username = 'root';
$db_password = '';
$charset = 'utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db_name;charset=$charset";
try {
$pdo = new PDO($dsn, $db_username, $db_password, $options);
} catch (\PDOException $e) {
$error = $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();
error_log(MYSQL_DATETIME_TODAY . "|$error\r\n", 3, ERROR_LOG_PATH);
$subject = "Database Down";
$email_body = "The Database is down for " . APP_NAME . "\n ERROR: $error";
send_email(ADMIN_EMAIL_TO, $subject, $email_body, ADMIN_EMAIL_FROM);
die('<h1><span style="color:red">FATAL ERROR: No Database Connection</span></h1>');
}
?>
Спасибо за ваше время и предварительный ответ.