简体   繁体   中英

PHP show logged-in username on the top of every page

I'm building a College blackboard type app and I have a php file that handles authorization. I use javascript ajax post to send data to server and intermediate php to echo the response back. Then i redirect to the home page.

I can't figure out how to save the username from initial page and display to the top right of the redirected page logged in as 'username' .

I've tried things like

<!-- main.php -->  
<?php session_start(); $_SESSION['u-name'] = $_POST['ucid'];?>  

Then inside other file

include 'main.php'
echo $_SESSION['id'];  

Didn't work.

inside other file it should be

include 'main.php'
echo $_SESSION['u-name']; 
            //--^^^^^^---here

cause your setting the session to u-name and not id

If the 'ucid' in your example is the username, you can use the following codes:

Main.php

<?php 
    session_start();

    if(isset($_POST['ucid'])) { // Added check to make sure it does not empty the session variable if there is no post (because you include this on every page)
        $_SESSION['u-name'] = $_POST['ucid'];
    }
?>

Other file

<?php
    include 'main.php';
    echo $_SESSION['u-name'];
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM