0

So I'm trying my hand at learning more PHP.

I believe I have set the $_SESSION['user'] on successful login, then I want to direct the user to the profile.php page using the header. What I am trying to do is view other users profiles using either their user ID or username in the URL.

For example: /profile.php?id=7 or /profile.php/John

if(!isset($_SESSION['user'])){
    header("Location:profile.php?id=" . $_SESSION['user']);

}else if(!empty($_GET['name'])) {

    $username = $_GET['name'];
    $getUserProfile = mysqli_query($connection, "SELECT user.username, user.userID
                                     FROM profile, user
                                     WHERE profile.userID = user.userID
                                     AND user.username = '{$username}'");
    while($getResult = mysqli_fetch_array($getUserProfile)){
        $usersname = $getResult["username"];
        $usersId = $getResult["userID"];

    }
}

I have tried to do this but I cannot get it to work. I would greatly appreciate any help on how to do this!

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
John107
  • 2,157
  • 3
  • 20
  • 36
  • 1
    This is wrong `if(!isset($_SESSION['user'])){` try `if(isset($_SESSION['user'])){` – hungrykoala Jun 14 '17 at 12:17
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Jun 14 '17 at 12:19

1 Answers1

2

Try this:

if(!empty($_SESSION['user']) && empty($_GET['name'])){
    header("Location:profile.php?id=" . $_SESSION['user']);

}else if(!empty($_GET['name'])) {

    $username = $_GET['name'];
    $getUserProfile = mysqli_query($connection, "SELECT user.username, user.userID
                                     FROM profile, user
                                     WHERE profile.userID = user.userID
                                     AND user.username = '{$username}'");
    while($getResult = mysqli_fetch_array($getUserProfile)){
        $usersname = $getResult["username"];
        $usersId = $getResult["userID"];

    }
    header("Location:profile.php?id=" . $usersId);
}
hungrykoala
  • 1,083
  • 1
  • 13
  • 28
  • Hi, Thanks for your reply! It was certainly very helpful! But now whenever I enter any url it always relays back to the logged in user (for example "/profile.php?id=John") - If I wanted to view Mandy's profile how could I do this? Thanks – John107 Jun 14 '17 at 13:55
  • Hi @John107, I've updated the code to include in the condition if the URL parameter is empty. – hungrykoala Jun 15 '17 at 04:09