0

I have login.php folder and addpost.php folder. I want to create session and store session in login.php and if it is created it will redirect to addpost.php. In addpost.php i want to check if there's no session stored it will redirect to login.php again.

My Problem: it works fine when i don't put my code in addpost.php yet but when i put my code there and come back to test my code i can't redirect login page to addpost page.

here's my code in folder login.php

<?php
require('../koneksi.php');
if(isset($_POST['login'])){

    $username = mysqli_real_escape_string($kon, ($_POST['username']));
    $password = mysqli_real_escape_string($kon, ($_POST['password']));
    $query = "SELECT * FROM admin WHERE username = '$username' AND password = '$password'";
    $result = mysqli_query($kon, $query);
    if(!$result || mysqli_num_rows($result) == 0){
        echo '<script>alert("Username atau password Anda salah!")</script>';
    } else {
        $_SESSION['admin'] = 'username';
        $_SESSION['admin'] = $username;

        header('Location: addpost.php');
    }
}

?>

here's my code in addpost.php

<?php
require('../koneksi.php');
session_start();
if(!isset($_SESSION['admin'])){
    header('Location: index.php');
} ?>

could you guys help me with this! thank you!

1 Answers1

0

The problem seems to be in your

if(isset($_POST['login']))

replace it with

if($_SERVER['REQUEST_METHOD'] === 'POST')

which is if the form in posted with method POST then do the following Also no need of that extra variable introduced

$_SESSION['admin'] = $username;

here's how I found the solution

index.php

<!DOCTYPE html>
<html>
<head>
    <title>
        Index
    </title>
</head>
<body>
    <form action="login.php" method="post">
        <input type="text" name="username">
        <input type="password" name="password"> 
        <button type="submit" value="submit">submit</button>
    </form>
</body>
</html>

login.php

<?php
include_once 'db_connect.php';

if($_SERVER['REQUEST_METHOD'] === 'POST'){
$username = mysqli_real_escape_string($conn, ($_POST['username']));
$password = mysqli_real_escape_string($conn, ($_POST['password']));
$query = "SELECT * FROM admin WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if(!$result || mysqli_num_rows($result) == 0){
    echo '<script>alert("Username atau password Anda salah!")</script>';
    header('Location: login.php');

} else {
    session_start();
    $_SESSION['admin'] = 'username';
    header('Location: addpost.php');
}
}
?>

addpost.php

    <?php
session_start();
if(!isset($_SESSION['admin'])){
    header('Location: index.php');
}
//your code here
?>

Happy Coding!