Annoyingly my log in check script is not redirecting where I tell it to.
I know it hits the if statements correctly because I put in echos to check it did.
It is blatantly skipping to header as during the first circumstance it echos "- blanks" as it should then also "Did it even get this far?"
So on that basis I know it hits the header - its just plain ignoring it and I can not for the life of me fathom why.
Im sure its simple and I'm missing something ridiculously obvious but I just cant see it.
Any suggestions?
// makes sure they filled it in
if($_POST['frmLogin-username'] == "" || $_POST['frmLogin-password'] == ""){
echo " - blanks";
header('Location: ?page=landing&action=login&message=1');
echo "Did it even get this far?";
die;
}
else{
// checks it against the database
$query = mysql_query("SELECT * FROM shops WHERE shopUsername = '".$_POST['frmLogin-username']."'");
//Gives error if user dosen't exist
$count = mysql_num_rows($query);
if ($count == "0"){
echo " - no user";
header('Location: ?page=landing&action=login&message=2');
die;
}
else{
while($row = mysql_fetch_array( $query )){
//gives error if the password is wrong
if ($_POST['frmLogin-password'] != $row['shopPassword']){
echo " - wrong pass";
header('Location: ?page=landing&action=login&message=3');
die;
}
else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie(shopusername, $_POST['frmLogin-username'], $hour);
setcookie(shopid, $row['shopId'], $hour);
//then redirect them to the shop panel
header("Location: ?page=shop");
die;
}
}
}
}
EDIT: The issue was to do with the way I load all my pages within index.php by calling includes which I am now investigating
I have moves this process page to its own php file and it now works fine
First of all: you can not send headers after having output anything using echo like Sam said in his comment.
Secondly, to send a redirect, the URL after the Location: must be absolute, like http://localhost/page/to/redirect/to.php.
EDIT
Corbin actually beat me to my answer for about 10 seconds ;-)
The issue was to do with the way I load all my pages within index.php by calling includes which I am now investigating I have moved this process page to its own php file and it now works fine
You can use window.location, just echo it within PHP.
Related
I am coding an online quizzer using PHP. Whenever the answerer of the quiz choose the correct answer, the code will automatically +1 to his overall score.
To do that, I used $_SESSION['score']=0; to first set the score to zero and $_SESSION['score']++; whenever the answerer gets the answer correct for each question.
However, I have no idea why the score is not adding up despite the answerers answering the questions correctly.
When the answerer answers the question correctly, the score is still 0 for some reason and I have no idea why. May I know what went wrong? Thank you.
Things I have tried:
1.Changing $_SESSION['score']++; to $_SESSION['score']+1;
2.Changing:
if(!isset($_SESSION['score'])){
$_SESSION['score']=0;
}
to just
$_SESSION['score']=0;
3.Changing
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}
to just:
if($correct_choice = $selected_choice){
$_SESSION['score']++;
}
Below is the code for process.php:
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
if(!isset($_SESSION['score'])){
$_SESSION['score']=0;
}
if(isset($_POST['submit'])){
$number=$_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
/*
* Get total questions
*/
$query="SELECT* FROM questions";
$results= mysqli_query($con,$query);
$total=$results->num_rows;
/*
* Get correct choice
*/
$query = "SELECT* FROM `choices` WHERE question_number = $number AND is_correct=1";
//Get result
$results= mysqli_query($con,$query);
//Get row
$row=$results->fetch_assoc();
//Set Correct choices
$correct_choice=$row['id'];
//Compare choice made with correct choice
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}
//Check if last question
if($number == $total){
header("Location: final.php");
exit();
} else {
header("Location: question.php?n=".$next);
}
}
Just tried something:
if($correct_choice == $selected_choice){
echo "same";
} else{
echo "not same";
}
Even though $correct_choice and $selected_choice are both equals to 1, the code still returns as "not same"?
You are opening and closing a lot of PHP tags - unnecessarily. If you have error reporting on, and being displayed on screen, it would likely be saying 'headers already sent'. That, is likely the issue.
Since the process.php file is all php - just open the <?php tag once - and don't even bother to close it at the end - unless you are explicitly outputting something (which is bad practice anyway for a larger program, better to use a small framework, and separate templates).
Make sure that your code does not output anything to the browser before session_start() is called.
you can find more information about $_SESSION superglobal here.
To use cookie-based sessions, session_start() must be called before
outputing anything to the browser.
I've tried doing my research and it doesn't look like I'm coming up successful. I made sure there is no content being printed out to the screen before my header tags.
This page is taking information given from the form in the previous login page and using that information to determine which page the user should be redirected to. Unfortunately, it doesn't look like any of my header tags are redirecting to anything, it just stays on this php page.
To debug, I have echo'd each scenario (logged in, out, wrong pw) and each scenario works, but obviously when I echo'd the redirect wouldn't work. I just wanted to test that the information was being transmitted correctly.
Can anyone else help and give me an outsider's perspective?
<?php
session_start();
include('dbconnect.php');
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$query = "SELECT password FROM artists WHERE email='$email'";
$passwordMatch = mysqli_query($db, $query);
$row = mysqli_fetch_array($passwordMatch);
if($row[0] == $password){
$query = "SELECT active FROM artists WHERE email = '$email'";
$active = mysqli_query($db, $query);
$active = mysqli_fetch_array($active);
$active = $active[0];
if ( $active == 0 ){
header('Location: validate.php');
}
else{
header('Location: artistHome.php'); //redirect to user home page and update session
$_SESSION['user']= $email;
unset($_SESSION['error']);
}
}
else{
header("Location: login.php");
$_SESSION['error']= 'Invalid Password';
}
?>
There were about thousands of posts like this one over here.Get rid of php closing tag ?> and whitespaces, html, blank lines before php opening tag <?php. Also check if there is no output before :
header("Location:");
Like print,var_dump, echo and so on.
Also check your if condition, maybe you are just skipping it.
If you include,include_once,require_once or require check all the things above in the included files too.
To narrow a circle of the things to correct look into your php error_log and provide us with error description.
header("Location: login.php"); will always fail if anything is returned to the browser before it. That includes whitespace, or even errors PHP are returning. Make sure nothing is being returned before the header function is used.
So i'm basically messing around with my own cms type system at the moment and running into some problems with php sessions. Below is a rough explanation on what i have,
All the SQL is working fine as if i remove the sessions i get no login errors (unless i put in incorrect credentials),
$query = "SELECT * FROM `test` WHERE username='$user' AND password='$pass_md'";
$result = mysql_query($query) or die("Error: " . mysql_error());
$rows = mysql_num_rows($result);
$data = mysql_fetch_assoc($result);
if($rows == 1){
$_SESSION['expire'] = time() + (10 * 60);
$_SESSION['id'] = $data['id'];
header("Location: admin.php");
}
else {
header("Location: ulogin.php?login=failed");
}
So in admin.php i have this,
<?php
session_start();
if(!(isset($_SESSION['id']))){
header("Location: ulogin.php");
}
?>
My issue is it is logging me in and then passing me straight back to ulogin.php so i'm assuming i have an empty session however i am inserting the user id into the session.
Any help would be greatly appreciated, i'm probably missing something pretty obvious, i'm not the most advanced php developer so yeh, need some more eyes on it.
Thanks
Found the issue, because i was using 2 seperate login pages (One for the frontend and one for the backend) i was missing;
<?php
session_start();
?>
from one of my login pages, sorted now, thanks all for the comments that actually made me triple check that!
I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php
I am hosting a website from a local computer (using MAMP Pro on a Mac), and need to switch the hosting to another local Mac. I have copied across all of the files for my website, and the MySQL tables, and checked that the server and MySQL are running OK. Everything seems to be fine, except that the login system is returning "Invalid User" when I try to log in, even though I am entering the correct user info (I have tried a few users just to be sure).
The log.php that handles the login looks like this:
<?
session_name("MyLogin");
session_start();
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","root","password"); // your MySQL connection data
$db = mysql_select_db("nick"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/may.php"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
I have temporarily removed the password in the above code.
I wonder what steps I can take to troubleshoot this issue, and would be grateful for any help.
Thanks,
Nick
A few common techniques when I encounter this issue.
Output the generated SQL and test it by hand - echo $query;
See if mysql_error() outputs anything after you run your queries.
Use var_dump() and print_r() on your data objects to ensure they are as expected.
Comment out your redirects and exit() lines so you can determine where the script is breaking.
Fix or comment back with anything determined by the above.
Your code does a query to find a user with the given username, and then checks if the number of rows with that username is exactly 1.
The only way you could see the 'Invalid User' error is if there are 0 users with that username or more than 1 user with that username.
Have a look at the contents of the table and check which of these is the case (I recommend http://sequelpro.com for viewing database contents on a Mac). You can also use sequel pro to test your queries.