Jump to content

Help needed to make a login script redirect to another reserved page


3joez
 Share

Recommended Posts

Please, help. I'm new to php but I've tried so many times to make it work.

I've wrote a script that reads user and password data correctly, to log into a reserved webpage. The problem is that when you press the login button, it doesn't redirect to the target.php (reserved) page. The form is in a file called login.php. It reads and connect to the db, but stays on this login page. As a matter of fact, if I manually type in the url mywebsite/target.php after putting the credentials, it works. But I need an automatic redirect from login.php page and if credentials are correct, redirect to target.php.

<?php


    session_start();


    function loginform(){

        echo "<form action='' method='POST'>
              Username: <input type = 'text' name='username'>
              Password: <input type = 'text' name='password'>
              <input type = 'submit' name='login' value='Login'>
              </form>

        ";
    }

    function logoutform(){

        echo "<form action='' method='POST'>
              <input type = 'submit' name='logout' value='Logout'>
              </form>

        ";

    }

    function login($username, $password){

        $pass = md5($password);

        $con= mysqli(whateverwebsite.com, 'Nameofthetable', 'hashedmd5password') or die (mysql_error());

        mysql_select_db('whateverdb', $con) or die (mysql_error());

        $result = mysql_query(" SELECT * FROM user WHERE username='$username' AND password='$pass' ") or die (mysql_error);

        $count= mysql_num_rows($result);

        if($count==1) {
            $_SESSION['login']=$username;
            header('Location:Aggiornamenti/Aggiornamenti.php'); /*this doesn't actually work*/
        }

        else {
            header('Location:index.php'); /*this doesn't actually work*/
            echo "Wrong login"; 
        }

    }

    function logout(){
        session_destroy();
    }

    if (isset($_SESSION['login'])) {       /*this function seems to be ignored*/
        echo "Success";
        logoutform();
    }

    else{
        echo "Log in with username and password.";
        loginform();
    }

    if ($_POST['login']) {
        login($_POST['username'], $_POST['password']);
    }

    elseif($_POST['logout']){
        echo "you are logging out";
        logout();
    }

?> 

also, Before the html of the target.php page, there is this

<?php

session_start();
echo "Reserved area<br>";

if (!isset($_SESSION['login'])) {
exit("you must login <a href='../login.php'>Login<a>");
}
else {
echo "Do the <a href='../login.php'>Logout</a>";
}

?>
Edited by 3joez
Link to comment
Share on other sites

Not sure if it affects the header or not, but I've always used a space between the colon and the location. Also, use an exit after the location header to stop execution (otherwise the php will continue to execute, even though you are redirecting the user.

 

header("Location: some/page.php");
exit;
I *think* leaving off the exit, if there is code further down that sends something to the browser, it will cause the location redirect to fail. Edited by hitman6003
Link to comment
Share on other sites

Add some debug output to your code and make sure that what you expect to happen is happening...

 

<?php

//at the start of each page have:
start_session();
print "<pre>The contents of session are:\n" . print_r($_SESSION, 1);
....
....
function login($username, $password){
  print "\n At function login with username $username";
  .........
  if ($count==1) {
    print "\nThe user was found";
    $_SESSION['login']=$username;
    // this won't work because we've already output something to the browser
    header('Location:Aggiornamenti/Aggiornamenti.php'); /*this doesn't actually work*/

  } else {
    header('Location:index.php'); /*this doesn't actually work*/
    echo "Wrong login"; 

  }
}
Link to comment
Share on other sites

print "<pre>The contents of session are:\n" . print_r($_SESSION, 1);

 

This line return

The contents of session are: Array ( )

and I don't know if it's ok.

 

-----------------------------------------------------

this

print "\n At function login with username $username";

returns the name of the username, and it's ok.

 

-----------------------------------------------

this

print "\nThe user was found";

returns nothing

 

and again I don't know if that is ok.

Edited by 3joez
Link to comment
Share on other sites

Social,  you're saying to change this line

$con= mysqli(whateverwebsite.com, 'Nameofthetable', 'hashedmd5password') or die (mysql_error());

with this?

$con= mysql(whateverwebsite.com, 'Nameofthetable', 'hashedmd5password') or die (mysql_error());

if yes, that doesn't work.

 

@hitman when print "\nThe user was found"; prints nothing, could that mean that the problem is in the db connection?

It's strange anyway, because if I manually load the target.php in the url it works.

Link to comment
Share on other sites

 

$con= mysqli(whateverwebsite.com, 'Nameofthetable', 'hashedmd5password') or die (mysql_error());

 

If you are going to use it like that, you'll need to adopt the object oriented style...

 

$con = new mysqli($host, $user, $pass, $database);
$result = $con->query("SELECT something FROM somewhere");

if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    echo $row['something'] . "\n";
  }
}
Edited by hitman6003
Link to comment
Share on other sites

Ok, I'm missing the point I must admit, because of my lack of experience but this code

$con= new mysqli(whateverwebsite.com, 'Nameofthetable', 'hashedmd5password') or die (mysql_error());

        mysql_select_db('whateverdb', $con) or die (mysql_error());

        $result = $con->mysql_query(" SELECT * FROM user WHERE username='$username' AND password='$pass' ") or die (mysql_error);

        if($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo $row['test']. "/n";
            }
        }

behaves exactly as before.
 It hangs in the login page whitout jumping to target.php.

There are so many things I could have done wrong, but I just want the page to redirect to another page. I'm applying every single tip and adding also variations. I just still can't understand what am I doing wrong.

Link to comment
Share on other sites

You're still not using the mysqli object correctly...it has four options: hostname, username, password, database.

 

http://php.net/mysqli.__construct

 

mysql_error will not work when using mysqli...use mysqli->connect_error or mysqli_connect_error().

 

http://php.net/mysqli.connect_error

 

You're using "mysql_query" instead of the mysqli object's "query" method.

 

http://php.net/mysqli.query

Edited by hitman6003
Link to comment
Share on other sites

Reading that, I'm changing a lot, to this(but same result):

function login($username, $password){
      
        $pass = md5($password);

        $con= new mysqli(whateverwebsite.com, 'User', 'hashedmd5password', 'whateverdb');

        $result = $mysqli->query(" SELECT * FROM user WHERE username='$username' AND password='$pass' ") or die (mysqli_connect_error());

        if($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo $row['test']. "/n";
            }
        }

Still navigatin in the dark but I can't see some little lights. After this function is done properly(where are the errors?), shall I call a redirect?

Meanwhile let me say thanks for helping me.

Link to comment
Share on other sites

if you start with the object style mysqli, you have to use it...can't switch between them...so your use of mysql_i_connect_error() won't ever return anything.

 

Aside from that, add in some debug to check for expected results:

 

<?php

function login($username, $password) {
	$con = new mysqli("db_server.com", 'User', 'plain text password', 'whateverdb');
	
	if ($con->connect_errno) {
		die($con->connect_error);
	}
	
	$pass = md5($password);
	
	$query = "SELECT * FROM user WHERE username = '$username' AND password = '$pass'";
	
	if ($result = $mysqli->query($query)) {
		if ($result->num_rows > 0) {
			print "<pre>got the following results:\n\n";
			
			while ($row = $result->fetch_assoc()) {
				print_r($row);
			}
			
		} else {
			print "no rows were returned!";
			
		}
		
	} else {
		die($con->error);
	}
}
Edited by hitman6003
Link to comment
Share on other sites

Ok, I was messing mysqli parameters.

But now it enters even with wrong credentials.

<?php


    session_start();
    
    function loginform(){

        echo "<form action='Target.php' method='POST'>   /* I'm not sure I have to reach target.php from here */ 
              Username: <input type = 'text' name='username'>
              Password: <input type = 'text' name='password'>
              <input type = 'submit' name='login' value='Login'>
              </form>

        ";
    }

    function logoutform(){

        echo "<form action='' method='POST'>
              <input type = 'submit' name='logout' value='Logout'>
              </form>

        ";

    }

    function login($username, $password){
        
        

        $con= new mysqli("db_server.com", 'User', 'plain text password', 'whateverdb');

        if ($con->connect_errno) {
            die($con->connect_error);
        }

        $pass = md5($password);

        $query = "SELECT * FROM user WHERE username='$username' AND password='$pass' ";

        if($result = $mysqli->query($query)) {
            if ($result->num_rows > 0) {
                print "<pre>got the following result:\n\n";
                
                while ($row = $result->fetch_assoc()) {
                    print_r ($row);
                }
            }
        

        else {
            print "no rows were returned";
        }
    }

        else {
            die ($con->error);
        }


    }

    function logout(){
        session_destroy();
    }

    if (isset($_SESSION['login'])) {
        echo "You've logged login";
        logoutform();
    }

    else{
        echo "Wrong credentials";
        loginform();
    }

    if ($_POST['login']) {
        login($_POST['username'], $_POST['password']);
    }

    elseif($_POST['logout']){
        echo "you are logging out";
        logout();
    }

?> 
Edited by 3joez
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.