Hi,

I have been trying for the last few days to figure out how to send a particular user to their own specific URL. For example, all users will use the same login.php page but when User A logs in they will be redirected to A.php and if User B logs in they will be redirected to B.php.

I am totally new to php and have been using it for about 3 weeks. I am very familiar with html. So far I have managed to create a script where a user can log in and they will be redirected to logged-in.php regardless of who logs in.

This is the code in which I am having problems:

<?php

require 'config.php';

$login = $_POST['login'];
$password = sha1($_POST['password']);

$db->query("
    SELECT      COUNT(id) AS total,
                login
    FROM        users 
    WHERE       login = '$login'
    AND         password = '$password'
");

$result = $db->get();

if ($result[0]['total'] == 1) 
{
    $_SESSION['userLogin'] = $result[0]['login'];
    $_SESSION['isLogged'] = 1;
    header("location: " . $row['id'] . ".php");
    exit;
}
else 
{
    header('location: index.html');
    exit;
}

I am trying to redirect a user to their particular id and then index.php. For example User A's id (created in phpmyadmin) is 12345 - So what they should be redirected to is 12345/index.php. What is currently happening with this is users are simply getting redirected to http://mydomain/.php

I feel as though I should be adding a mysql_num_rows somewhere but have no idea where to put that script. Any help would be greatly appreciated. If required I can add my currently working php script which allows users to log in to logged-in.php and allows them to successfully log out.

Kind regards,

Robert.

You can attempt to put a number/letter in the database to detict the user, and check it in there login then if the number/letter matches whatever they go to a.php or b.php

That's exactly what I'm trying to do. I'm using the id number. But I don't know how to script it so it would check the user id and then take it to a specific URL.

hey, your select query isn't pulling the id

$db->query("
SELECT COUNT(id) AS total,
login
FROM users
WHERE login = '$login'
AND password = '$password'
");

$db->query("
    SELECT      COUNT(id) AS total,
                id,
                login
    FROM        users 
    WHERE       login = '$login'
    AND         password = '$password'
");

i also don't see you declare session_start(); that should be called pretty early on, probably just after require('config.php');

<?php
require('config.php');
session_start();
//....

and also register the user id to the session so you know exactly who it is for updates

$_SESSION['user_id'] = $row['id'];

Thank you very much for your reply. I have added the id and now am receiving these two errors:

Warning: Division by zero in /test/login.php on line 23

Warning: Cannot modify header information - headers already sent by (output started at /test/login.php:23) in /test/login.php on line 23

..and yet another post, you may want to store the page url in the user database in a column called say 'homepage' rather than just their id then add the homepage into the select query and redirect them to it on login.

That way you don't have to create as many pages as there are users or hardcode it into php everytime you want to change it - later on you could even set it so they can edit their homepage themselves

Thank you very much for your reply. I have added the id and now am receiving these two errors:

Warning: Division by zero in /test/login.php on line 23

Warning: Cannot modify header information - headers already sent by (output started at /test/login.php:23) in /test/login.php on line 23

will need to see the code for login.php, on line 23 something is being divided by zero - maybe a variable isn't what you expect it to be or a zero managed to get through the second warning is just caused by the first warning, cause the warning printed out headers cant be modified.

Thank you for the quick reply. The session start is in the config.php. Here is the config.php script:

<?php

$config = array();
$config['host'] = 'localhost';
$config['user'] = 'root';
$config['pass'] = '';
$config['table'] = 'members';

session_start();

$db = new DB($config);

and the login.php script which is causing the errors is:

<?php

require 'config.php';

$login = $_POST['login'];
$password = sha1($_POST['password']);

$db->query("
    SELECT      COUNT(id) AS total,
                id
                login
    FROM        users 
    WHERE       login = '$login'
    AND      password = '$password'
");

$result = $db->get();

if ($result[0]['total'] == 1) 
{
    $_SESSION['userLogin'] = $result[0]['login'];
    $_SESSION['isLogged'] = 1;
    header("location: " . $row['id'] / ".php");
    exit;
}
else 
{
    header('location: index.html');
    exit;
}

you may want to store the page url in the user database in a column called say 'homepage' rather than just their id then add the homepage into the select query and redirect them to it on login.

I actually like the sound of this. It might be a lot easier if my site starts to get many users.

So in phpmyadmin I create a new field called homepage and type varchar? Then I insert the URL in full as to where the redirect should go. Is that correct? Nothing else needs to be filled in on the database side?

Then what should I put in the script? This is the part I find tricky as a newbie. Is it just required to change the header on line 23 in login.php?

header("location: " . $row['id'] / ".php");

I also like the idea of storing the full url in the database, but your current script is trying to divide on line 23.
it should be something like:
header("location: " . $row['id']."/index.php");
with the slash being outside of the raw ". $php . " part of your script.

Thank you ddymacek. I have corrected the error which you found and now the script is doing what it was originally doing in that it's basically just redirecting to index.php rather than the userid/index.php.

I think maybe I need to store the full URL in the database but wouldn't know how to script this.

Sorry i had to run last night.

I standardly have a config.php file, an application.php file and a func.php file. Which act as the center of the site.

config.php has main site settings that you normally change when you move hosting eg the web address/database passwords

func.php has all the functions written for the site

application.php requires this config.php & func.php file and uses it to connect/check logins and pull user data and access levels and puts it into an array for access if you want it later such as:

application.php

<?php
$USERDATA = array();
//login check etc get data
$USERDATA['user_id'] = $userid;
$USERDATA['access_level'] = $access;
?>

afterwards all other files on the site require application.php so where ever the user is you always know who he is and if he should be allowed access and you get access to all the functions written in func.php

In config.php i would put in this:

<?php
define('DIR_ROOT','http://www.example.com/');
?>

Then change header("location: " . $row['id'] / ".php"); to header("location: ".DIR_ROOT.$result[0]['homepage']);

Then the data stored in the database in the homepage field is just the local url eg. "dir/page.php" or "index.php" or "sales.php"

If you'd prefer the full URL to let people have external links as their homepage, not sure why since they just logged into the site then get redirected away, you would change the header to header("location: ".$result[0]['homepage']); then the data stored in the database would have to be the full url such as "http://www.example.com/page5.php" or "https://www.google.co.uk/"

Thank you Biiim for your reply. I have added a 'homepage' field in my database. The field is called homepage and type is varchar, is this the correct way?

I have added the define('DIR_ROOT','http://www.example.com'); to my config.php file. I have also added the header header("location: ".DIR_ROOT.$result[0]['homepage']); but I am only getting redirected to http://www.example.com/ (Basically whatever I am putting in the 'define' string)

here is my config code:

<?php

require 'libs/mysqli.class.php';

$config = array();
$config['host'] = '';
$config['user'] = '';
$config['pass'] = '';
$config['table'] = '';

session_start();


$db = new DB($config);

define('DIR_ROOT','http://www.example.com/test/');

and here is my login.php code:

<?php

require 'config.php';

$login = $_POST['login'];
$password = sha1($_POST['password']);

$db->query("
    SELECT      COUNT(id) AS total,
                login
    FROM        users 
    WHERE       login = '$login'
    AND         password = '$password'
");

$result = $db->get();

if ($result[0]['total'] == 1) 
{
    $_SESSION['userLogin'] = $result[0]['login'];
    $_SESSION['isLogged'] = 1;
    header("location: ".DIR_ROOT.$result[0]['homepage']);
    exit;
}
else 
{
    header('location: index.html');
    exit;
}

Ok I've asked a friend of mine to help me and he's given me this code:

<?php
session_start();
$users['Username Goes Here'] = array('password' => 'Password Goes Here', 'redirect' => 'Redirect URL Goes Here');
$users['Username Goes Here'] = array('password' => 'Password Goes Here', 'redirect' => 'Redirect URL Goes Here');

if(array_key_exists($_POST['username'],$users)) {
    if($_POST['password'] == $users[$_POST['username']]['password']) {
        $_SESSION['loggedIn'] = true;
        header('Location:'.$users[$_POST['username']]['redirect']);
        exit();
    }
else {
    // invalid password
    header('location: login.php');
    exit;
    }
}
else {
    // invalid username
    header('location: login.php');
    exit;
}
?>

and this code for every page which requires a login:

<?php
session_start();
if(!$_SESSION['loggedIn']) {
    header('Location: login.php');
    exit();
}
?>

This works 100% and is almost exactly what I was looking for, The user will get redirected to their own specific URL. The only problem is that the code is not connected to a database and the users, password and redirection are all hard-coded within the script. Is there anyway to adapt the above code so it would connect to a database for the information?

you need to pull the field in the mysql query:

$db->query("
    SELECT      COUNT(id) AS total,
                login,
                homepage
    FROM        users 
    WHERE       login = '$login'
    AND         password = '$password'
");

The data pulled is only what you tell it to after the SELECT

SELECT columns FROM table WHERE critera

So whenever you add a field and want to pull data from it add its name into the columns,.

count() is a mysql function that adds up all the matching rows in a group by - I don't think that will ever say anything other than 1 even if there are multiple users with the same login and password.

AS gives the value resulting from the function a name.

I would instead just give the login column a unique index so you can't have more than one of the same username.

$db->query("
    SELECT      login,
                homepage
    FROM        users 
    WHERE       login = '$login'
    AND         password = '$password'
");

on your friends code, its a pretty nice use of arrays i don't think its the most efficient way as for every logon it will have to pull the entire list of users to check against each one and its not going to be very manageable when or if it is going to get bigger

heres a standard setup i use for a site with a login

config.php

<?php 
define("DB_HOST","1.2.3.4");
define("DB_USER","username");
define("DB_PASS","password");
define("DB_DB","database");

define("DIR_ROOT","http://www.example.com/");
?>

app.php

<?php 
require_once ('config.php');
session_start();
$A = array();
$db_link = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_DB);
if($_SESSION['loggedIn'] && is_int($_SESSION['user_id'])){
    //logged in get user data
    $Q = "SELECT `user_id`,`username`,`homepage` FROM `users` WHERE `user_id` = {$_SESSION['user_id']}";
    $R = mysqli_query($db_link,$Q);
    if($R !== false){
        //found user
        $A = mysql_fetch_assoc($R);
        $A['loggedin'] = true;
        $A['DB'] = $db_link;
    }else{
        //error didnt find user, set as not logged in
        $A['username'] = 'guest';
        $A['loggedin'] = false;
        $A['DB'] = $db_link;
    }
}else{
    //not logged in
    $A['username'] = 'guest';
    $A['loggedin'] = false;
    $A['DB'] = $db_link;
}
?>

login.php

<?php
require_once 'app.php';

if(ISSET($_POST['password'])){
    $username = str_replace("'", '', $_POST['username']);
    $password = str_replace("'", '', $_POST['password']);
    $Q = "SELECT `user_id`,`homepage` FROM `users` WHERE `username` = '$username' AND `password` = '{$password}'";
    $R = mysqli_query($A['DB'],$Q);
    if($R !== false){
        $data = mysqli_fetch_assoc($R);
        if(isset($data['user_id'])){
            $_SESSION['loggedIn'] = true;
            $_SESSION['user_id'] = $data['user_id'];
            header('Location: '.DIR_ROOT.$data['homepage']);
        }else{
            //error
            $_SESSION['loggedIn'] = false;
        }
    }else{
        //wrong user/pass
        $_SESSION['loggedIn'] = false;
    }
}
?>

anyotherpage.php

<?php 
require_once 'app.php';
if(!$A['loggedin']){//not logged in
    header("Location: login.php");
    die();
}
?>

Of course if you just have to be logged in for every page you could just redirect straight from app.php and your other pages will all just need to include app.php

<?php 
require_once 'app.php';
//app.php already redirects if not logged in
//anyone seeing code after this must be logged in
?>

and i also make a func.php which is required by app.php, func.php contains a large list of all functions defined on the site. So you only need to define say, pulling a forum thread, once then every other time you need to the function is already written and you just need to call it.

config.php makes it easy if you ever need to move the site or change any hosting

app.php is like the security gateway, you turn off/on access for anyone in seconds

func.php is prewritten code you could use again in multiple places

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.