Question

I'm Alex and I am learning PHP. I have two files named.. file1.php and file2.php. I have a variable inside file1.php and I want to refer it in file2.php, how can I do that? I know it's a stupid question for most of you but I'm new to this and I'm trying to learn. Thank you in advance, I'll provide you with my code.

File1.php

<?php

if(isset($_POST['username']) && isset($_POST['password'])){
    $username = $_POST['username'];
    $password = $_POST['password'];
    $passwordmd5 = md5($password);

    if(!empty($username) && !empty($password)){

        $query = "SELECT `id` FROM `users` WHERE `username` = '$username' AND `password` = '$passwordmd5'";

        if($queryrun = mysql_query($query)){
            $query_num_rows = mysql_num_rows($queryrun);
            if($query_num_rows == 0){
                echo 'Invalid username and password';
            } else if($query_num_rows == 1){
                echo $user_id = mysql_result($queryrun, 0, 'id');
                $_SESSION['user_id']=$user_id;
                header('Location: index.php' . $username);
            }
        }  else {
            echo 'Enter a username and a password';
        }
    }

?>

File2.php

<?php
        require 'core.php';
        require 'connectdb.php';

        if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
            echo '<a href = "logout.php"><input type = "submit" id = "logreg" value = "Logout" /></a>';
        }else{
            echo '<a href = "loginregister.php"><input type = "submit" id = "logreg" value = "Login/Register" /></a>';
        }
    ?>

Basically, File1.php is a login form for a website and I am entering a username and submit it, if I succesfully submit it and I login, I want my button to change from "Login/Register" to "Welcome, ", how can I do that? On a short note, how can I transfer my $username variable that I enter in my File1.php to File2.php? For example.. I press the Login/Register button, I type in Alex as a username and 123 as password and press the Login button. (That to be done in file1.php) Considering the user and the password being correct, I am moving to file2.php and instead of the Login/Register button, I want a new button, or a div (whatever) to show up with the text "Welcome, Alex" or "Welcome, -username-". How can I do that?

Was it helpful?

Solution

You need to include session_start on your file2.php code. If file1.php isn't the first page you will need to add the session_start at the beginning of it as well.

<?php
   session_start();
    require 'core.php';
    require 'connectdb.php';

    if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
        echo '<a href = "logout.php"><input type = "submit" id = "logreg" value = "Logout" /></a>';
    }else{
        echo '<a href = "loginregister.php"><input type = "submit" id = "logreg" value = "Login/Register" /></a>';
    }
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top