Jump to content

Why I cant get sessions in other pages after deployment to ionos web hosting?


Recommended Posts

Hi

I am trying to access a session variable from one page to another but it is not working and yes, the IONOS is allowing sessions.

here is the code:

login.php:

$sql2 = "SELECT * FROM login_users WHERE username_email = '$myusername' and password = 	'$mypassword' and IsAdmin = 1";
         $result2 = mysqli_query($db, $sql2);
         $count2 = mysqli_num_rows($result2);
         if($count2 == 1) {
            $_SESSION['admin'] = $myusername;
            header('Location: https://www.ramiwahdan.org/main.php', True);
         } else  {
         $error = "Your login Name or Password is invalid";
         $myusername="";
         $mypassword="";
         }

and main.php:

<?php 
      session_start();
      $myusername = $_SESSION['admin'];
      print($myusername);
?>

why is that? I am not getting any errors.

53 minutes ago, rwahdan1978 said:

I am not getting any errors

do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, and you have confirmed using a phpinfo(); statement in your code that these are the values php is using?

you can temporarily put these settings into your code, on both pages, immediately after the first opening <?php tag.

next, if php's output_buffering is on, and you have a redirect in your code, it will discard any non-fatal errors or debugging output you have added. temporarily comment out the header() redirect so that you can see if there are any php errors up to that point.

do you have a session_start() statement in the login.php code?

and as is sometimes given, here's a list of programming practices for the posted code -

  1. don't use variables ending in numbers. you should completely deal with the result from one block of code before performing another operation, and there's no need to use or to keep track of numbered variables.
  2. you should list out the columns you are SELECTing in a query.
  3. you need to use prepared queries, instead of putting dynamic values directly into sql query statements. if it seems like using the mysqli extension is overly complicated and inconsistent when dealing with prepared queries, it is. this would be a good time to switch to the much simpler and better designed PDO extension.
  4. you need to use php's password_hash() and password_verify() for password handling, i.e. don't store passwords as plain text.
  5. the value you store in a session variable upon successful login should be the user's id (autoincrement primary index), and it should be named user_id or similar. you should query on each page request to get any other user data, such as the username or permissions. this is so that any changes made to this other user data take effect on the very next page request after is has been changed, without requiring the user to log out and back in again.
  6. the header() redirect needs an exit/die statement to stop php code execution. you could, for example, have some code following the posted code, that's clearing the session variable.
Edited by mac_gyver

sending a session variable from one page to another involves - having a working, error free, session_start() statement on both pages; have a server properly setup with a folder to hold the session data files; have the session cookie parameters setup so that they match the url for both pages; assign a value to a session variable on one page, that you are sure isn't getting cleared after you have set it, and test for and use the session variable on the second page.

except for very overt symptoms, there is not a 'one symptom' is always caused by 'one thing' relationship in programming. if you are expecting someone here to be able to directly tell you what the cause of this problem is, you are mistaken. there are too many possibilities.

when something in programming doesn't work, you must find where your code and data are doing what you expect and where they are not. the problem lies between those two points. if all you have done is run your code and notice that the output doesn't exist, you haven't narrowed down the problem.

the first step in narrowing down a programming problem is finding any errors that the language is reporting. to do this, you must setup the error related settings and verify that they are actually the values that you have set them to. in your last thread, you would have been getting a fatal run-time error to alert you to one of the problems in the code, but you didn't indicate you were getting any errors. this means that php's error related settings (error_reporting, display_errors, and log_errors) are not setup so that php will help you. once you have set the error settings as i stated, and comment out the redirect, this will narrow down the possibilities, by either producing a error pointing to a problem or if doesn't produce an error this points to where to look at next.

  • Great Answer 1

I found the issue. if I don't have a header redirect to main.php and move manually to main.php it will work. Why is that?

here is the complete code:

login.php

<?php
	session_start();
	//include("header.php");
    	include("config.php");

   $myusername = '';
   $mypassword = '';
   $test2 = 1;
   $error='';
   
   if($_SERVER["REQUEST_METHOD"] == "POST") {
      $myusername = mysqli_real_escape_string($db,$_POST['email']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']); 

    $sql = "SELECT * FROM login_users WHERE username_email = '$myusername' and password = 	'$mypassword' and IsAdmin = $test2";
    $result = mysqli_query($db, $sql);
    $count = mysqli_num_rows($result);

      if($count == 1) {
         $_SESSION['admin'] = $_POST['email'];
         print($_SESSION['admin']);
         //echo '<meta http-equiv="refresh" content="0;url=https://www.ramiwahdan.org/index.php">';
         //header('Location: https://www.ramiwahdan.org/index.php', True); 
      }
       else  {
         $error = "Your login Name or Password is invalid";
         $myusername="";
         $mypassword="";
         }
   }
?>

<link href="//db.onlinewebfonts.com/c/a4e256ed67403c6ad5d43937ed48a77b?family=Core+Sans+N+W01+35+Light" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="register.css" type="text/css">
<div class="body-content">
  <div class="module">
    
    <div class="text-center">
        <img src="2.png" width="90" height="90" class="rounded" alt="">
    </div>
    
    <h1>
        Login User
    </h1>
    <form class="form" action="login.php" method="post" enctype="multipart/form-data" autocomplete="off">
    <div class="alert alert-error"></div>
      <input type="text" placeholder="Email" name="email" required />
      <input type="password" placeholder="Password" name="password" autocomplete="new-password" required />
      <input type="submit" value="Login" name="login" class="btn btn-block btn-primary" />
      <span id="error" style="color:red;font-weight:bold"><?=  $error ?></span>
    </form>
    </div>
</div>

and main.php

<?php 
      session_start();
      include("header.php");
      print($_SESSION['admin']);
      if (!$_SESSION['admin'])
      {
        echo '<meta http-equiv="refresh" content="0;url=https://www.ramiwahdan.org/login.php">';
      }
?>

so commenting out the header in login.php, I will be able to browse to main.php after logging-in and everything is fine. when un commenting the header, it won't!

probably this -

8 hours ago, mac_gyver said:

have the session cookie parameters setup so that they match the url for both pages;

when you browse to main.php (or is it index.php), do you include the www. on the URL or not and does the URL you use for login.php always include the www. or not?

also, since you have shown the full login code, the redirect upon successful completion of the form processing code MUST be to the exact same URL of the login page. this is so that the browser won't attempt to resubmit the form data should that page get browsed back to or reloaded, where someone can use the browser's developer tools to look at what the form 'payload' is and see what the email and password are for the last person to submit the form.

Edited by mac_gyver

You can always check to see if session is started:

<?php
// Include the configuration file and autoload file from the composer.
require_once __DIR__ . '/../config/clearwebconfig.php';
require_once "vendor/autoload.php";

// Import the ErrorHandler and Database classes from the PhotoTech namespace.
use clearwebconcepts\{
    ErrorHandler,
    Database,
    LoginRepository as Login
};

// Create an ErrorHandler instance
$errorHandler = new ErrorHandler();
// Set the exception handler to use the ErrorHandler instance
set_exception_handler([$errorHandler, 'handleException']);

// Create a Database instance and establish a connection
$database = new Database();
$pdo = $database->createPDO();
// Create a LoginRepository instance with the database connection
$login = new Login($pdo);
$checkStatus = new Login($pdo);

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect to dashboard if the user is already logged in
if ($login->check_login_token()) {
    header('Location: dashboard.php');
    exit();
}

// Generate a CSRF token if it doesn't exist and store it in the session
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Detect environment
$isLocal = in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
$cookieDomain = $isLocal ? '' : DOMAIN;
$cookieSecure = !$isLocal; // Set to true on remote server

// Process the login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the submitted CSRF token matches the one stored in the session
    if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Sanitize the username and password input
        $username = strip_tags($_POST['username']);
        $password = $_POST['password'];

        // Verify the user's credentials
        if ($login->verify_credentials($username, $password)) {
            // Generate a secure login token
            $token = bin2hex(random_bytes(32));
            // Store the login token in the database
            $login->store_token_in_database($_SESSION['user_id'], $token);

            // Set a secure cookie with the login token
            setcookie('login_token', $token, [
                'expires' => strtotime('+6 months'),
                'path' => '/',
                'domain' => $cookieDomain, // Adjusted for environment
                'secure' => $cookieSecure, // Adjusted for environment
                'httponly' => true,
                'samesite' => 'Lax'
            ]);

            // Store the login token in the session
            $_SESSION['login_token'] = $token;

            // Redirect the user to the dashboard
            header('Location: dashboard.php');
            exit;
        } else {
            // Log error message for invalid username or password
            $error = 'Invalid username or password';
            error_log("Login error: " . $error);
        }
    } else {
        // Display an error message
        $error = 'Invalid CSRF token';
        error_log("Login error: " . $error);
        $error = 'An error occurred. Please try again.';
    }
}

// Generate a random nonce value
$nonce = base64_encode(random_bytes(16));

?>

You can also make sessions persistent in your configuration and it's always best to start you session in your configuration file:
 

session_set_cookie_params([
    'lifetime' => strtotime('+6 months'),
    'path' => '/',
    'domain' => 'localhost',
    'secure' => false, // Since it's not HTTPS, set this to false
    'httponly' => true,
    'samesite' => 'Lax'
]);

session_start();
ob_start(); // turn on output buffering
if (empty($_SESSION['token'])) {
    try {
        $_SESSION['token'] = bin2hex(random_bytes(32));
    } catch (Exception $e) {
    }
}
if (preg_match('/\.js$/', $_SERVER['REQUEST_URI'])) {
       return false; // Let the webserver handle JavaScript files
   }

 

On 4/18/2025 at 8:53 PM, rwahdan1978 said:

I found the issue. if I don't have a header redirect to main.php and move manually to main.php it will work. Why is that?

so commenting out the header in login.php, I will be able to browse to main.php after logging-in and everything is fine. when un commenting the header, it won't!

So it's something that you put in header.php that you didn't show the code for.

 

On 4/18/2025 at 8:53 PM, rwahdan1978 said:

 

and main.php

<?php 
      session_start();
      include("header.php");
      print($_SESSION['admin']);
      if (!$_SESSION['admin'])
      {
        echo '<meta http-equiv="refresh" content="0;url=https://www.ramiwahdan.org/login.php">';
      }
?>

so commenting out the header in login.php, I will be able to browse to main.php after logging-in and everything is fine. when un commenting the header, it won't!

You need to understand that when you print something out, the browser sends an HTTP response to the request.  Thus the HTTP header is composed and sent.

This is not the way to do a redirect -- using  meta refresh.  You should be doing that in the HTTP header using a location, and that code should be followed by an exit.

 

<?php
session_start();
if (!empty($_SESSION['admin'])) {
    header('Location:/login.php');
    exit();
}
// This user is admin

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.