Search code examples
phphtmlauthenticationusing

Using login data to make operations in other pages


I have a homework which is creating a web page which user can share photos or texts in their profile. But I am stuck at using login information to do it.

Here is my login.html:

<form method="post" action="login.php">
<br><label for="username">Username:</label></br>
<input type="text" id="username" name="username">
<br><label for="password">Password:</label></br>
<input type="password" id="password" name="password">
<div id="lower">
<br><input type="submit" value="Login"></br>
<p>
Not yet registered?
 <a href="signup.html">Click here to register</a>

 </p>

</div><!--/ lower-->
</form>

and here is my login.php:

?php 
$con=mysqli_connect("localhost","root","","webpage");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_POST['username'];  
$password = $_POST['password']; 

$sql=mysqli_query($con,"SELECT * FROM user WHERE username='$username' and password='$password'"); 
   if (!mysqli_fetch_assoc($sql)) {
  die("You entered wrong username/password.");}

 while ($sql){

    $sql2="SELECT * FROM user WHERE username='$username' and approval = 1";
    $res = mysqli_query($con,$sql2);    
    if (!$res) {
    echo "Your account isn't approved yet. Please wait for approval. Thanks :)";}
    else echo 'You have succesfully logged in.';
        header('Location: http://localhost/project2/redirect.html');
    }
mysqli_close($conn);


?>

From here, I am stuck. I don't know what to do to use the username that the user has entered. What am I suppose to do?

Thanks.


Solution

  • You can set the username in session which can be used till the session is cleared..ie till the user logs out or close the browser

    A session is a way to store information (in variables) to be used across multiple pages.

    Unlike a cookie, the information is not stored on the users computer.

    By default, session variables last until the user closes the browser.

    Thus, Session variables hold information about one single user, and are available to all pages in one application.

    A session is started with the session_start() function.

    Session variables are set with the PHP global variable: $_SESSION.

    To Set Session variables

    <?php
    // Start the session
    session_start();
    $username = $_POST['username'];  
    // Set session variables
    $_SESSION["uname"] =$username;
    ?>
    

    To Get Session variable's value

    <?php
    session_start();
    $username =$_SESSION["uname"];
    ?>
    

    To Destroy the Session

    <?php
    // remove all session variables
    session_unset(); 
    
    // destroy the session 
    session_destroy(); 
    ?>