Php Redirect to a webpage (html) - php

I've seen the use of header in the php to redirect to a page.
I've used the method in the code below and the a redirect error as given below the code.
I need to know what went wrong with the code.
Here is the code (php) :
<?php
/**
* Created by PhpStorm.
* User: Priyabrata
* Date: 3/18/14
* Time: 8:58 PM
*/
function connect_to_db($uid, $pass){
$con=mysqli_connect("localhost", "root", "12345", "MyDB");
if (mysqli_connect_errno()){
echo "Failed to establish link!!";
}else{
echo mysqli_connect_error();
}
$result=mysqli_query($con, "SELECT `pwd` from `login_table` where `uid` = "."'".$uid."'");
if (!$result){
echo "Error!!";
exit();
}
while($xx = mysqli_fetch_array($result)){
if ($xx['pwd'] == hash("MD5", $pass)){
header("location:../Html/Login-Existing-Users1_success.htm");
exit();
}else{
echo "Invalid Login Credentials!!";
exit();
}
}
mysqli_close($con);
}
function validate_credentials(){
if ((isset($_POST["username"]))&&(isset($_POST["password"]))){
$uid = $_POST["username"];
$pwd = $_POST["password"];
if (($uid == "")||($pwd == "")){
echo "Please enter User name and password";
}else{
//Check user name and password
connect_to_db($uid, $pwd);
}
}else{
echo "Please enter User name and password";
}
}
validate_credentials();
Here is the error I get, instead of a redirect when uploaded to the server:
Warning: Cannot modify header information - headers already sent by (output started at /home/opticfhb/public_html/helpvssupport.net/login.php:19) in /home/opticfhb/public_html/helpvssupport.net/login.php on line 27
Additional Info : This works perfectly in my local machine and creates the problem in the server.

You can't call header() after you've already echoed any output. HTTP requests contain header information and data. Any output is part of the data, and data comes after all the headers have already been sent.
PHP has a function called headers_sent to check whether or not the headers have already been sent or not. You might consider writing a function that issues the Location header if they haven't been, or echo out some simple redirect HTML if they have -- perhaps by including this tag in the <head>:
<meta http-equiv="refresh" content="0;http://www.website.com/redirect/url" />

Related

Login / Logout Session Issue

I am creating some kind of a login/registration system right now. Registration form, email confirmation and login is already working. I now have problems with my sessions. Please keep in mind that this project is just a test project. I know that I should use PDO but for this testing purposes I need to find out why it is not working they way I did it.
Here is my login.php PHP code:
<?php include ('inc/database.php');
if (isset($_POST['submit'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwort'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwort'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM user WHERE email='$Email' AND password='$Password' AND activation IS NULL";
$result_check_credentials = mysqli_query($connect, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (#mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
//Assign the result of this query to SESSION Global Variable
header("Location: index.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
} // End of the main Submit conditional.
?>
Here is the beginning of my protected index.php
<?php
ob_start();
session_start();
if(!isset($_SESSION['email'])){
header("Location: login.php");
}
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
.....
There must be a problem with my session and I do not know why. Is it wrong to use the email as session? Am I using the email as session? What other options do I have?
Problem is right now, that if I click on Login, nothing happens. I will be redirected to login.php instead of index.php!
Any suggestions?
As Fred -ii- already mentioned in comments above, your $_SESSION['email'] is never set, and therefor you are re-directed to your login-page every time.
It's also worth noting that when using header("Location: ...");, you can not have any output prior to the header! Otherwise the header will fail. Output is generally any HTML, echo, whitespace (see this SO).
So, once you make sure that your header("Location: index.php"); actually works, move on to fixing your $_SESSION.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC); does not set $_SESSION['email'] (as already stated by Fred -ii-). To fix this, you need to fix your results from the database.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
The code above will return the row "email" from the result in the database, and set it to the session of "email", which later is checked when you are trying to access index.php.
A couple of side-pointers (not really your current problem, but a few tips to make your code better).
You should use exit; after using header("Location: ..."); (See this SO)
You are not hashing your password, so it's stored in plain-text in your database (big no-no)
Indenting your code properly makes it a lot easier to read, and in turn easier to troubleshoot
If you do the above, and it still doesn't work, we'd need some more information to help troubleshoot further (like what happens when you're logging in (is it as expected?), what results are returned, and so forth).
try to change,
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
to
$results = mysqli_fetch_row($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email']=$results['email'];
and try to check your "activation" field in database for null while login...

Redirecting to another page, using variables from the first one

I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();

Code not working while trying to pull user login data from form in php

I created a registration form that works fine in php for a project I am undertaking. I attempt to use another form, a login form in which to pull the username and password data from the user to verify it against the database. However I am getting parsing errors and other errors. I haven't started validation yet as I haven't got the basics in this ready.
I don't think I'm going about this the right way or if it's just a silly mistake.
<EDIT Remove Important Info>
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
if (isset($_SESSION['logged'])){ //already logged in
//$url= 'X'; // any page
exit(); //ends script if user already logged in
} else { //not logged in or submitted
}
$user_name = mysqli_real_escape_string($con,$_POST['username']);
$pass = mysqli_real_escape_string($con,$_POST['password']);
$notify="";
if(isset($_POST['notify_box'])){ $notify = $_POST['notify_box'];
$query=mysqli_query($con,"SELECT * FROM `websiteusers` WHERE username ='$user_name' AND password ='$pass'");
$count = $mysqli_num_rows($query); //checks db
$row = mysqli_fetch_array($query);
if($count==0){ //db empty
echo "Sorry, password and username not in db. Click here to try again.";
}
else{ // pw and un match, user login success
$_SESSION['logged']=1; //start session
$_Session['username']=$user_name; //session data
}
// } // opening brace for this was not found
mysqli_close($con);
exit();
} // opening brace for this was not found
?>
And here is a jsFiddle of my HTML form
Edit
I found this in your form
<input name="user_name" type="varchar" >
which should be
<input name="user_name" type="text">
Also, use this
$pass = mysqli_real_escape_string($con,$_POST['pass']);
instead of
$pass = mysqli_real_escape_string($con,$_POST['password']);
yet I'm unsure about the password line, since you were using md5 and now just plain text.
You may have to set it back to:
$pass=md5($_POST['pass']);
There are a few issues with your code.
You have a missing quote at the end of '$user_name
WHERE username ='$user_name
Which needs to be changed to:
WHERE username ='$user_name'
as well as a missing semi-colon at the end of your query. $query=mysqli_query("SELECT....
And this (for one thing) $username=form($_POST['user_name']); is invalid, since form would be considered a function.
Use $username=$_POST['user_name']; or better yet:
$username=mysqli_real_escape_string($con,$_POST['user_name']);
A missing semi-colon at the end of $password=md5($_POST['pass'])
A missing $con at the beginning of the query.
Which is included in the complete rewrite below.
Line rewrite:
$query=mysqli_query($con, "SELECT * FROM `websiteusers` WHERE username ='$user_name' AND password ='$pass'" );
Plus, I noticed you're storing passwords using md5. It's no longer recommended to use this. Do look into using PHP's password function
Complete rewrite:
N.B.: The $url variable has not been defined anywhere else, so I'm unsure of its functionality. Plus there were two unused ending braces } at the end of your code, so I commented those out, along with the exit();
You may also be closing your DB connection prematurely with the placement of mysqli_close($con); should you be faced with another error message. I left it in place, but commented out and then moved at the end of the script.
Please give this a try, hoping things will fall into place as they should.
<?php
// Create connection
$con=mysqli_connect("X","X","X","X");
session_start(); //starts users session
// Check connection
if (!$con) {
die('Connect Error: ' . mysqli_connect_errno());
}
//echo "1 record added";
if (isset($_SESSION['logged'])){ //already logged in
$url= 'http://danu6.it.nuigalway.ie/sm4business/browse.html'; // any page
exit(); //ends script if user already logged in
} else { //not logged in or submitted
$username=mysqli_real_escape_string($con,$_POST['user_name']);
$pass=md5($_POST['pass']);
} // mysqli_close($con); // may be being closed prematurely.
$query=mysqli_query($con,"SELECT * FROM `websiteusers` WHERE username ='$user_name' AND password ='$pass'");
$r = $mysqli_num_rows($query); //checks db
$row = mysqli_fetch_array($query);
if($r==0){ //db empty
echo "Sorry, password and username not in db. Click here to try again.";
}
else{ // pw and un match, user login success
$_SESSION['logged']=1; //start session
$_Session['username']=$user_name; //session data
}
// } // opening brace for this was not found
// exit();
// } // opening brace for this was not found
mysqli_close($con); // moved here
?>
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
make it this as
//Check connection
if (mysqli_connect_errno()) { echo "Failed to
connect to MySQL: " . mysqli_connect_error(); }
Parsing errors are typically a simple mistype. If you put a ; in the wrong place, or don't put it at all... etc.
Try using the edits made by Grant Palin in your code, and see if this fixes your issue.

POST variable to another page while redirecting - php

I am redirecting the user back to login page if the login inputs arenot correct.
$sql = "select * from Driver where username=$username and pwd=$pwd";
$driver = mysql_query($sql);
if(!$driver){
header("Location: http://domain.de/login.php");
exit();
}
can i also pass message like "sorry, username isnot correct" to login page?
i dont want to use session. get isnot the option here
you could do it like
header("Location: http://domain.de/login.php?error=username");
and do on the other page
if ($_GET['error'] == 'username') {
echo 'Sorry, username is not correct!';
}
EDIT:
Watch out for SQL injection also
You may add get paramet to location header or save message flag in session. Like this:
$sql = "select * from Driver where username=$username and pwd=$pwd";
$driver = mysql_query($sql);
if(!$driver){
header("Location: http://domain.de/login.php?wasredirect=1");
exit();
}
//////// In login.php
if (isset($_GET['wasredirect'])) {
echo "sorry, username isnot correct";
}
Or this:
$sql = "select * from Driver where username=$username and pwd=$pwd";
$driver = mysql_query($sql);
if(!$driver){
header("Location: http://domain.de/login.php");
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['redirect'] = true;
exit();
}
//////// In login.php
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['redirect'] = true;
if (isset($_SESSION['redirect']) &&$_SESSION['redirect'] ) {
echo "sorry, username isnot correct";
unset($_SESSION['redirect']);
}
I think the best solution is to load that login.php page as a part (the view) of the current script (the controller) and set a variable with the value of the message. Something like:
if(!$driver){
$message = "Sorry, username isnot correct";
}
else {
$message = "Whatever";
}
include('login.php');
$message will be available for you inside login.php script.
For simply giving away a message, you can add it to the URL.
header("Location: http://domain.de/login.php?e=1234");
I recommend using error codes instead of full-length messages for better flexibility.
Note, how ever, that doing it right would require to implement a MVC pattern and then internally load the routing of the error page. But that might be too much for a small script.
I know you donĀ“t ant feedback to your query. No need to worry, unless you are clueless about what SQL injection means.
Best regard
Zsolt
Change the query to:
$sql = "select * from `Driver` where `username`='$username' and `pwd`='$pwd'";
Note the backticks and single quotes

PHP code included in HTML won't update

I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.

Categories