Redirection not working after online host

Below code works well on localhost, but when I upload this page online then page is not redirected to intended page after login

PHP Code :

<?php
session_start();

if(is_array($row)) {
$_SESSION["id"] = $row['id'];
$_SESSION["username"] = $row['username'];
} else {

$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["username"])) {
  header("Location:main");
}
?>

Open in new window

Nikhil DangeWeb Developer InternAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
header("Location:main");

Open in new window

That is not a valid or complete URL.
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gr8gonzoConsultantCommented:
Also, make sure you call exit() after doing a Location header:

header("Location: new_url");
exit();

Open in new window


And also, your script is vulnerable to SQL injection. Make sure you get that query fixed!
https://www.experts-exchange.com/articles/1263/5-Steps-to-Securing-Your-Web-Application.html
0
Nikhil DangeWeb Developer InternAuthor Commented:
how to give online path in header before webfile?
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

gr8gonzoConsultantCommented:
Assuming you're not redirecting to a different domain, just specify the part after the domain name. So to send the user to http://www.yourdomain.com/some/page.php

header("Location: /some/page.php");
1
Julian HansenCommented:
You probably want this

header('location: main.php');

Open in new window

Or
header('location: main.html');

Open in new window

Unless you are using URL Rewriting and main needs to be redirected somewhere else in which case you need to check your .htaccess file and make sure it has been configured to match your online hosting environment
0
Nikhil DangeWeb Developer InternAuthor Commented:
How I assign path in header("location: main.php"); from the following?

index.php is login page and after authentication from database should be redirected to main.php page.

I learning new things, so I'm trying on free web hosting

URL of project URL of project
Login Code Login Code
Files for Host Files for Host
0
Julian HansenCommented:
I don't understand the question.

Your code was working locally.

Does not work on the server.

This is not a portable statement
header('location: main');

Open in new window

It is dependent on the configuration of the server you are on.
If main.php is the desired destination then always do this
header('location: main.php');

Open in new window

Which ensures it will work in all environments.
0
Nikhil DangeWeb Developer InternAuthor Commented:
I tried header('location: main.php'); then also page not redirected on main.php page
0
Julian HansenCommented:
Are you sure this condition is true
if(isset($_SESSION["username"])) {
  header("Location:main.php");
}

Open in new window

Try this
if(isset($_SESSION["username"])) {
  die('Redirecting to main.php
  //header("Location:main.php");
}
else {
   die('Session username is not set');
}

Open in new window

What do you get from that?
0
Nikhil DangeWeb Developer InternAuthor Commented:
if(isset($_SESSION["username"])) {
  header("Location:main.php");
}
I dont get anything from this code.
Shows same page after login.
0
Julian HansenCommented:
Did you try the code from my last post?

The problem is most likely it is never getting to the header() line - but at this stage we can only guess as we don't have anything to work with.

Please implement the suggestion above and let us know what the response is so we can get more information.
0
Nikhil DangeWeb Developer InternAuthor Commented:
Give output as Session username is not set.
0
gr8gonzoConsultantCommented:
Can you post the full code (just edit out any valid credentials or domain names first) ? You used to have your DB connection code in your question, which was helpful in knowing that you were first connecting to the database before running a query.

Also, I looked at your site, and you have some DB connection code that doesn't have the right PHP start tag:

< ?php

Open in new window


If you have a space between < and ?, it won't start your PHP correctly, so it won't connect to the database. It should look like this:

<?php

Open in new window


Also, you're using mysql_ functions - make sure you use mysqli_ functions instead.
0
Julian HansenCommented:
That's your problem.

if the SESSION['username'] is not set then
if(isset($_SESSION["username"])) {

Open in new window

Will never evaluate to true.

So, up until now we have been chasing shadows - focusing on the header() redirect instead of the SESSION

Now we have to backtrack and see why the SESSION['username'] is not set
Looking here
if(is_array($row)) {
$_SESSION["id"] = $row['id'];
$_SESSION["username"] = $row['username'];
}

Open in new window

This is where it is set - so I am guessing that $row is not set which makes sense if you posted your entire script and not a snippet because nowhere in the code you have given us does it say where $row is initialised / set.

So let's start there.
Where does $row come from.
0
gr8gonzoConsultantCommented:
I did a little snooping around your site and have a couple other suggestions:

Make use of include() or require() commands to create a consistent experience across your site, since you have different pages. You can put session checking and authentication handling and start of a template into a header file and the footer into a separate footer file. Here's a sample skeleton of a site that uses headers/footer and has a basic login requirement.

header.inc.php
<?php
// Start / continue the session
session_start();

// Connect to the database
$db = new mysqli("localhost","username","password","database_name");

// Check authentication
if(!isset($_SESSION["id"]))
{
  // Not logged in yet - do we have a username/password?
  if(isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["btnLogin"]))
  {
    // Check the database for the user (adjust the query to match your setup)
    if($rs = $db->query("SELECT * FROM your_users_table WHERE username='" . $db->real_escape_string($_POST["username"]) . "' AND password='" . $db->real_escape_string($_POST["password"]) . "'"))
    {
      if($rs->num_rows == 1)
      {
        // User logged in successfully
        $row = $rs->fetch_assoc();
        $_SESSION["id"] = $row["id"];
        $_SESSION["username"] = $row["username"];
        header("Location: main.php");
        exit();
      }
      else
      {
         // User not found
         $loginError = "User not found!";
      }
    }
  }
}

// Start the page
?>
<!doctype html>
<html>
<head>
  <title>My Site</title>
</head>
<body>
<h1>My Site</h1>
<center>
<?php
if(isset($login_required))
{
  echo "This page requires you to be logged in!";
  require("footer.inc.php");
  exit();
}

Open in new window


footer.inc.php
</center>
<footer>
<hr size='1'><p>Design by so and so</p>
</footer>
</body>
</html>

Open in new window



Then your pages can all reuse that code:
index.php
<?php require("header.inc.php"); ?>

Content of index.php

<!-- Login form -->
<form action='index.php' method='post'>
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="password"></p>
<p><input type="submit" name="btnLogin" value="Login"></p>

<?php require("footer.inc.php"); ?>

Open in new window


main.php
<?php 
$login_required = true;
require("header.inc.php"); 
?>

Content of main.php

<?php require("footer.inc.php"); ?>

Open in new window


Also, just a note - I have not tested any of the above and am in a bit of a hurry at the moment, so there's a chance I missed a quote or a semicolon somewhere, but the principle should be accurate.
0
Nikhil DangeWeb Developer InternAuthor Commented:
THIS IS CODE PLEASE HELP, Issues with sessions

<?php
session_start();
$message="";
if(count($_POST)>0) {
$con = mysqli_connect(localhost","username","password","database_name") or die('Unable To connect');
$result = mysqli_query($con,"SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
if(is_array($row)) {
$_SESSION["id"] = $row['id'];
$_SESSION["username"] = $row['username'];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["username"])) {
  die('Redirecting to main.php');
  //header("Location:main.php");
}
else {
   die('Session username is not set');
}
?>
   
<body>

<div class="header">
<nav class="navbar navbar-inverse colorgraph1">
 
</nav>
</div>

<form  method="post" name="Login_Form">      
<div class="colorgraph"><br><br><br>
<font face="Lato" size="8">Login</font><br><br><br>
<input type="text" class="form-control" name="username" placeholder="Username" required>
 <input type="password" class="form-control" name="password" placeholder="Password" required><br><br>
<button class="colorgraph3" name="login" id="login">
<font face="Lato" size="5" color="f7fdca">Login</font></button><br><br>
</div>
</form>
0
gr8gonzoConsultantCommented:
Change:
$message = "Invalid Username or Password!";

to:
$message = "Invalid Username or Password! " . mysqli_error ($con);
0
Nikhil DangeWeb Developer InternAuthor Commented:
not working
0
Nikhil DangeWeb Developer InternAuthor Commented:
What happen for this redirection and session
0
Julian HansenCommented:
$result = mysqli_query($con,"SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");

Open in new window

This is very dangerous code
1. You are including your $_POST directly in your query string opening yourself to an SQL injection attached
2. Your password is not hashed or salted.
3. You don't check the $result value return from the mysqli_query.

I suspect the problem is your database connection - when you moved to your new host you did not set it up correctly or the credentials are wrong.

Follow Gr8gonzo's advice and show us what the mysqli_error($con) shows us after the mysqli_query.
0
Julian HansenCommented:
not working
Gr8gonzo gave you a suggestion that should have given us an error message explaining why your data is not being populated.
You need to tell us what you see. Not working is not useful to us - we need information to help you solve this problem - you are our eyes - we need you to tell us as much as you can about what is happening with your code.

The problem is
Your query is not returning a record for the username and password given this means
1. There is a problem with your data (username / password are blank or wrong)
2. There is a problem with your database - for some reason your connection to the database is failing
3. There is a problem with your query

To find out which it is - we need you to tell us what is happening on your end.

Following the last suggestion from Gr8gonzo you should have the following on the screen
Invalid Username or Password! [FOLLOWED BY AN ERROR MESSAGE FROM MYSQL]

Open in new window

This is what we need to see.
0
Nikhil DangeWeb Developer InternAuthor Commented:
not give any error any error using this mysqli_error ($con); , and not redirecting to page
0
Julian HansenCommented:
Please post your code - it is not possible to even guess what is happening without a point of reference.
0
Nikhil DangeWeb Developer InternAuthor Commented:
<?php
session_start();
$message="";
if(count($_POST)>0) {
$con = mysqli_connect('localhost','root','','admin') or die('Unable To connect');
$result = mysqli_query($con,"SELECT * FROM table WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
if(is_array($row)) {
$_SESSION["username"] = $row[username];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["username"])) {
header("Location: main.php");
}
?>
<html>
<head>
<title>User Login</title>
</head>
<body>
<form name="frmUser" method="post" action="" align="center">
<div class="message"><?php if($message!="") { echo $message; } ?></div>
<h3 align="center">Enter Login Details</h3>
Username:<br>
<input type="text" name="name">
<br>
Password:<br>
<input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="reset">
</form>
</body>
</html>
0
Nikhil DangeWeb Developer InternAuthor Commented:
$row = mysqli_fetch_array($result);

this code is not wrking .
0
Julian HansenCommented:
Please echo out your query so we can see what it is trying to do
echo "SELECT * FROM table WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'";

Open in new window

Show us what that gives.
0
Nikhil DangeWeb Developer InternAuthor Commented:
SELECT * FROM login WHERE username = '' and password = '1234'
this is print on output
0
Julian HansenCommented:
 WHERE username = ''

Open in new window

The username is blank - that is your problem. Now we go back to see why your username is blank - where is it coming from.
Based on your code from here
$_POST["username"]

Open in new window

It appears the username POST is not being sent through.

First step is to see what actually IS being sent by the browser. To do that we dump the POST to the screen so we can see it.

At the start of your script do this
echo "<pre>" . print_r($_POST, true) . "</pre>";

Open in new window

Tell us what this dumps to the screen - paste it here.
0
Nikhil DangeWeb Developer InternAuthor Commented:
I get this output there was comma problem but I rectify that,
 SELECT * FROM login WHERE username='ABCD' and password = '1234'

Using this echo "<pre>" . print_r($_POST, true) . "</pre>";
I get below output

Array
(
    [username] => ABCD
    [password] => 1234
    [submit] => Submit
)
0
Julian HansenCommented:
Ok now that the Query is being populated again - remove the print_r() and try again.
0
gr8gonzoConsultantCommented:
Underneath your query line:
$result = mysqli_query($con,"SELECT ....");

Add these 2 lines:
if($result === false) { echo "Query failed: " . mysqli_error ($con); die(); }
if($result->num_rows == 0) { echo "No rows returned"; die(); }

Then test again and let us know what the output is.
0
Nikhil DangeWeb Developer InternAuthor Commented:
After proper username and password redirect me on same page, but when I entered wrong id and password  print message as "No rows returned"
0
Julian HansenCommented:
but when I entered wrong id and password  print message as "No rows returned"
What were you expecting to happen?
0
Nikhil DangeWeb Developer InternAuthor Commented:
After login, main.php should be open
0
Julian HansenCommented:
Yes but you are supplying invalid credentials - that is not going to find any valid records. Redirection to main.php happens when you successfully login - i.e. you FIND a matching record in the database for the credentials supplied.

If you enter invalid credentials - no record - therefore no redirect.

What is it you want to happen when you enter incorrect username / password?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.