PHP script not redirecting via header - php

I am looking for some kind of bug in my code which is causing this PHP page to not redirect. I'm looking to see if someone might know the cause of this problem (it may have something to do with the cookies).
inc_vars.php:
<?php
//some of the variables have been omitted.
$pid = 'gbb';
$dbtable ='';
$dbname = '';
$dbuser = '';
$dbpass = '';
$connect = mysql_connect('localhost', $dbuser, $dbpass);
if(!$connect){
header('Location: omitted');
die();
}
mysql_select_db ($dbname, $connect);
$webroot = 'omitted';
$share_page = $webroot . '/share-the-training';
$gift = $webroot . '/free-video?setuser=1199';
$bonus_content = $webroot . '/awesome-bonus';
$share_php = $webroot . '/share.php';
?>
refresh_id.php:
<?php
include_once('inc_vars.php');
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
if(!$results || mysql_num_rows($results)==0){
header('Location: ' . $share_page . '?errorcode=1');
die();
}
$res_arr = mysql_fetch_assoc ($results);
setcookie($pid . "_viral", (string)$res_arr['id'], time() + 3600 * 365);
move_on();
function move_on(){
header ('Location: ' . $share_php);
die();
}
?>
When the person visits refresh_id.php?email=their_email they should redirect to the $share_php page. This is not working.
However, if this scenario happens: refresh_id.php?email=an-email-that-is-not-in-database then the script redirects to $share_page absolutely fine.
I have tried this with and without the gbb_viral cookie in place. I'm not sure why this isn't working. All pages are live and on the internet right now in case you want to look for yourself.
omitted
An email that exists in the database is as follows: acctrafficcop#gmail.com (for those that want to test this)
UPDATE
Stupid mistake with scopes. I simply added global $share_php in the move_on() function and everything is working fine now. Thank you everyone for the heads up on SQL injection, I am switching over to prepared statements right now.

In your move_on function, the variable $share_php does not exist because of variable scope. Therefore your redirect looks like this: Location:. There is no URL in the Location header.
You can pass the variable into the function, or use the global keyword to make it available. Try this:
move_on('/redirect_url');
function move_on($url){
header ('Location: ' . $url);
die();
}
In fact, in refresh_id.php I don't see a variable called $share_php anywhere, so you are redirecting to an empty URL.

You also need to set a status header for the browser to honor the location header. Try adding
header('HTTP/1.1 303 See Other');
Using curl will help you debug. Also, your are setting yourself up for SQL Injection with your SQL query.
Edit: After reading the second answer, it is correct that you aren't passing in a location to your redirection function. This should be fixed as well.
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
Never trust input from users like this. Instead, use a SQL bind. Here's how you would do it with the mysqli library: http://php.net/manual/en/mysqli-stmt.bind-param.php

Related

PHP loading issue "redirected too many times"

localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
My code was working perfectly fine, but today this error occurred not quite sure why. I have cleared browsing data, deleted cookies but nothing works. The rest of my site is functioning well, just this user login page. I am using PHPstorm.
<?php
include_once("db.php");
if (isset($_POST['Login'])) {
$email = $_POST['email'];
$password = $_POST['pwd'];
$path = "home.php";
$select = "SELECT * FROM finalflight.tbl_book
WHERE email='" . $email . "'
AND ContactNo='" . $password . "'";
$query = mysqli_query($conn, $select);
}
if ($row = mysqli_fetch_assoc($query)) {
session_start();
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['BookedBy'];
$_SESSION['ContactNo'] = $row['ContactNo'];
$_SESSION['bookid'] = $row['SrNo'];
$_SESSION['uid'] = session_id();
$path = "home.php";
} else {
$path = "login.php?msg='unable to login'";
}
header("location:$path");
I have attached the error message screenshot. I am intrigued to know why the error has occurred wondering if someone could explain what is actually going on. PHPstorm came up with a redirect link for my page which I copied to clipboard and pasted it into my browser but that didn't seem to work. Is this a programming issue or a web browser issue? I have checked through my code and there doesn't seem to be any errors. I have tried reloading the web browser many times, deleted history nothing seems to work.
Error Message
you are calling header function while page leading that's why too many redirections. call header after post submitted
try this,
<?php
include_once("db.php");
if (isset($_POST['Login'])) {
$email = $_POST['email'];
$password = $_POST['pwd'];
$path = "home.php";
$select = "SELECT * FROM finalflight.tbl_book
WHERE email='" . $email . "'
AND ContactNo='" . $password . "'";
$query = mysqli_query($conn, $select);
if ($row = mysqli_fetch_assoc($query)) {
session_start();
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['BookedBy'];
$_SESSION['ContactNo'] = $row['ContactNo'];
$_SESSION['bookid'] = $row['SrNo'];
$_SESSION['uid'] = session_id();
$path = "home.php";
} else {
$path = "login.php?msg='unable to login'";
}
header("location:$path");
}
Your browser will tell you what is going wrong if you dig a bit deeper. Likely your PHP error logging is trying to tell you about some of the problems too.
At a guess, The code you've shown us is probably working OK, but the page you are redirecting to is sending you back to this page - but you should NEVER REDIRECT TO THIS CODE! Actually, the code you've shown us should be re-written to handle the case where it is retrieved without the required POST vars without going completely pear-shaped.
Use the network monitor in your browser to see where you are getting 302 responses and where they are directing you to. Make sure your error logging is working properly and recording errors.

PHP: Function no query & return

I hope that someone sharp on PHP can help me with problem, that i really don't understand.
I have 2 scripts. 1: test.php 2:functions.php.
I created a little test where i called a functions in functions.php frim test.php and it work fine. I got a return and it was as expected. I also have a third script register.php where i have a query to a database and that work fine.
So I wanted the query to work as a function written in functions.php
Problem: It seems that it won't make the database query! But there is createt a connection
If I move the exactly same query to test.php, it works! Is there some kind of speciel reason for this? I quit new to php, but knows a little about Java, C, JavaScript, Python.
I have checked that my include / require is all in order.
1: test.php:
<?php
require 'includes/functions.php';
$name = 'testuser';
$_ok = 0;
$_ok = check_username ($name);
printf ( 'Navn i database?: ' . $_ok . '<br>' );
?>
2: functions.php:
<?php
require 'includes/db_connect.php';
// Check connection
if (! $mysqli) {
die ( 'mysqli_init_failed' );
}
if (mysqli_connect_errno ()) {
die ( 'Failed to connect to the Database, Sorry..! errorcode: ' .
mysqli_connect_errno() . ' <br>' . 'Error Type: ' . mysqli_connect_error () );
}
if ($debug_mode_c) {
print ('Connection Established: ' . mysqli_get_host_info ( $mysqli ) . '<br>') ;
print ('session_id: ' . session_id ()) . '<br>';
}
// Set HTML-Header to utf-8.
header ( 'Content Type: text/html; charset=UTF-8' );
// Functions
function check_username($_ok) {
$name = 'testuser';
$prep_stmt = "SELECT username FROM customs WHERE username=? LIMIT 1 ";
$stmt = mysqli_prepare($mysqli, $prep_stmt);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name_db);
mysqli_stmt_fetch($stmt);
if ($name == $name_db) {
echo "hello";
mysqli_close ($stmt);
$_ok = 0;
} else {
$name = '';
$_ok = 2;
}
mysqli_free_result($stmt);
mysqli_close($stmt);
return $_ok;
}
Maybe found the reason for no query.
Apparently the include script containing establish connection, is not loaded as the function is called in functions.php.
When the query code is in test.php, that include functions.php, all code is read, also the connection for the database.
But even if include 'db_connect' is inside function, it won't work !?! :-(
There is nothing like noquery() function in PHP. please just check it in the include file of the database connection. you will find a user defined function in your include file of the database connection.

Session Variables not Persisting

I have a few session variables that I am trying to use in my application, however, I am unable to get them to show up on the pages I need them to.
This is the code that sets them (I have manually assigned them values as well, so it isn't the database pull that is the problem):
if ($name != ""){
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;
}
I start that page with a session_start();, as I do on all the pages that will be using the session variables.
When I try to call the session variables on another page, they no longer exist, even if that is the page the one that assigns the values redirects to.
This is how I am trying to call the session variables:
$name = $_SESSION['name'];
$user_id = $_SESSION['id'];
why would it be doing this?
EDIT: To help I'm including the rest of my code for that page. The database connection portions work fine, they are identical to what I use eveyrwhere else.
<?php
session_start();
define('DB_SERVER', '<server>');
define('DB_USER','<db>');
define('DB_PASSWORD' , '<password>');
define('DB_NAME' , '<db-name>');
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database');
$stmt = "Select User.user_id, User.name from User where User.username = '" .
$_POST["username"] . "' AND User.password = '" . $_POST["pwd"] . "';";
if(!$result = $conn->query($stmt)){
die('there was an error retrieving the information');
}
$row = $result->fetch_assoc();
$name = $row['name'];
$user_id = $row['user_id'];
$_SESSION["name"] = $name;
$_SESSION["id"] = $user_id;
if ($name != ""){
$conn->close();
?>
<script type="text/javascript">
<!--
window.location = "store.php"
//-->
</script>
<?php
}
else{
?>
<script type="text/javascript">
<!--
window.location = "register.php"
//-->
</script>
<?php
}
?>
There is only two probabilities:
You did not started session before any output.
The $name is already empty or null.
You have to do the following to debug:
echo $name before the if conditional.
error_reporting(E_ALL); or checkout this question: How to get useful error messages in PHP?
As a debugging technique, try setting the session values ON the page that you're trying to call them. For example, set them on the top of the page and then try outputting them somewhere else below on the page and see if that works. If it does, then it's obvious that the variables aren't being set on the previous page(s).
In PHP you must need to start session using session_start() then only you can user session variables.
And also try to debug, Does your if condition satisfied or not. In your case if your if condition does not satisfied then it is not possible your below code will execute.
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;

Mysql call stops all forms of output php

Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.

Password verification does not login just reloads login page

I'm ripping my noob hair out here. Can't understand why below code isn't working. The page loads alright, but when I try to log in with the username and password that is in my database the page is just reloaded to its original state with the login form, when I'd actually like to see a logout button instead. I've also tried comparing the password without salt and hash with an unhashed, unsalted equivalent in the database. Not working.
The only warnings I get are "It is not safe to rely on the system's timezone settings.", and I don't think those have anything to do with the password verification functionality.
The page starts out like this:
session_start();
error_reporting(-1); ini_set('display_errors', 'On');
Then follows some HTML. Then:
if (isset($_POST['log_out'])) {
session_unset();
session_destroy();
$_SESSION = array();
}
The logout button, when pressed, sets $_POST['log_out']. Then comes a function I got from a book, used to prevent SQL injection:
function mysql_fix_string($string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
$string = htmlspecialchars($string, ENT_QUOTES);
$string = mysql_real_escape_string($string);
return $string;
}
Then comes the password verification part, which should only run if the user has submitted the login form (which posts back to the same page, thus setting $_POST['username'] and $_POST['password']):
if (isset($_POST['username']) && isset($_POST['password'])) {
$salt1 = 'how';
$salt2 = 'pony';
$password = md5($salt1 . $_POST['password'] . $salt2);
$db_hostname = 'xxxxxxxxx';
$db_username = 'xxxxxxxxx';
$db_password = 'xxxxxxxxx';
$db_database = 'xxxxxxxxx';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$username = mysql_fix_string($_POST['username']);
$query = "SELECT password FROM users WHERE name = '" . $username . "'";
$result = mysql_fetch_assoc($query);
$passwordindatabase = $result['password'];
if ($password == $passwordindatabase) {
$_SESSION['logged_in'] = true;
$_SESSION['user'] = $username;
unset($_POST['username']);
unset($_POST['password']);
}
}
A bit further down comes the login form, only shown if ($_SESSION['logged_in'] != true). It posts the values of the input fields username and password to $_SERVER['REQUEST_URI'] (the same page).
Looks to me like you're missing the mysql_query() function which means you aren't actually executing the query.
mysql_query — Send a MySQL query
Do the following and see if it works:
$result = mysql_query($query);
$passwordindatabase = mysql_fetch_assoc($result);
Edit
On a completely different note, you should not use mysql functions since they are quite old fashioned and have mysql_injection vulnerability. I would advice you to start working with PDO as soon as possible, which (if done right) has got no mysql_injection vulerabilities.
The only bit that "smells" about the code you're showing is this:
if ($password == $passwordindatabase) {
I'd prefer to see something like this:
if (strcmp($password, $passwordindatabase) == 0) {
Also we need to see the code where you're actually inserting the values into the users table, because clearly $password and $passwordindatabase aren't matching.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
But, timezone warning is send before.
Set the timezone on php.ini file.
edited..
not only this problem. you must use mysql_query() function on sql request before mysql_fetch_assoc().

Categories