php/mysql help needed no error being outputed - php

can some assist me with my code, everything looks correct checked each line at least 10 times. I've even hardcode in the user/pass for the query and still nothing.
<?php
include "database.php";
$sql = "SELECT UserName, Password, Language, Editor FROM admin_login WHERE UserName='".$_POST['username']."' AND Password='".$_POST['pwd']."'";
$result = #mysql_query($sql);
$line = #mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0) {
#unsuccessful login
header('Location: index.php' );
} else {
#login successful, setting up session
ob_clean();
session_start();
$_SESSION['user'] = $line['UserName'];
$_SESSION['pass'] = $line['Password'];
$_SESSION['lang'] = $line['Language'];
$_SESSION['editor'] = $line['Editor'];
#send to editor page
if ($_SESSION['lang'] == 'List') {
header('Location: list.php');
exit;
#send to announcer page
} else if ($_SESSION['lang'] == 'Order') {
header('Location: order.php');
exit;
}
}
?>

remove the # from the function mysql_query and from mysql_fetch_assoc and you will have the errors displayed.

Here's my version:
<?php
include 'database.php';
$sql = "SELECT `UserName`, `Password`, `Language`, `Editor` FROM `admin_login` WHERE `UserName` = '" . mysql_real_escape_string($_POST['username']) . "' AND `Password` = '" . mysql_real_escape_string($_POST['pwd']) . "' LIMIT 1;";
$result = mysql_query($sql);
if ($result === false)
{
// Unsuccessful Login
header('Location: index.php');
}
$user = mysql_fetch_assoc($result);
$_SESSION['user'] = $user;
if ($user['Language'] == 'List')
{
header('Location: list.php');
exit;
}
elseif ($user['Language'] == 'Order')
{
header('Location: order.php');
exit;
}
?>
If it still shows some errors copy/paste them here, if no errors are displayed and code still don't works then show us your database scheme and a database.php file.

Some steps to follow:
Add MySQL error reporting such as (to the end of your SQL statement):
or die ("Query failed: " . mysql_error() . " Actual query: " . $query)
Remove the # symbols -- these suppress errors.
Run your query on the command line with your favorite SQL tool (phpMyAdmin, Navicat, Command line, etc) to see if it results in an error

As already stated, remove all the # prefixes from functions. That suppresses all the errors.
Additionally, add the following two lines to the start of your script:
error_reporting(E_ALL);
ini_set('display_errors','1');

Your error report of PHP may be set to off. Please make it on or otherwise put ini_set('display_errors','1'); in the top of the php page where you are having this problem.

Related

Unreliable reading of $_SESSION data

I have two PHP files that I have abstracted below:
FILE 1: login.php
<?
ob_start();
session_start();
$q = "SELECT user_id, user_first_name, user_priv, user_reg_date, user_pref, user_last_login FROM Users WHERE (user_email='$e' AND user_pass=SHA1('$p')) AND user_active IS NULL";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 1) { // A match was made.
// Register the values & redirect:
$_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC);
session_write_close();
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
FILE 2: CustomIndex.php
<?
ob_start();
session_start();
if (empty($_SESSION['user_first_name'])) {
if(isset($_GET['custom2'])){
$url = BASE_URL . '/index.php'; // Define the URL.
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
sleep(5);
$url = BASE_URL . "/CustomIndex.php?custom2=1";
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
if(isset($_SESSION['user_first_name'])){
// …program code…
}
?>
When FILE 1 (login.php) is executed, then maybe 10% of the time the "if (empty($_SESSION['user_first_name']))" statement in FILE 2 (CustomIndesx.php) is true, and instead of being executed, the client is redirected to index.php, as if the $_SESSION variables had not been set.
However, after that happens, if I run FILE 2 (CustomIndesx.php) directly, it reads the $_SESSION data and executes properly.
I added all that code after "SLEEP" to simulate running CustomIndesx.php manually, but except for delaying the redirect by 5 second, nothing changed.
Can anyone suggest a reason for this random behavior, and how to eliminate it?
1) An important thing is: session_start() must be the first code line in both pages. If not, the session is closed after finished running each page script.
See what happened in
PHP _Session variable no longer persistate
PHP session for tracking unique page views
2) Then, in login.php code part:
session_write_close();
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
You are writing in session with session_write_close() and closing it. Then, in the CustomIndex.php you are trying to open it again. It seems that it's not the same session id opened. So, try to delete session_write_close(); line and test again.
Good luck!
EDIT 1:
Login.php:
<?php
session_start();
$q = "SELECT user_id, user_first_name, user_priv, user_reg_date, user_pref, user_last_login FROM Users WHERE (user_email='$e' AND user_pass=SHA1('$p')) AND user_active IS NULL";
$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) > 0) {
$_SESSION = mysqli_fetch_array($r, MYSQLI_ASSOC);
mysqli_close($dbc);
$url = BASE_URL . '/CustomIndex.php';
header("Location: $url");
exit();
}
?>
CustomIndex.php:
<?php
session_start();
if (!isset($_SESSION['user_first_name']) || empty($_SESSION['user_first_name'])) {
echo 'SESSION USER_FIRST_NAME IS NOT SET!';
} else {
echo 'SESSION USER_FIRST_NAME IS OK: ' . $_SESSION['user_first_name'];
}
?>

Redirect Issue for referral system when fetching URL data

I have created a script for users to invite a friend using a email address, the email address and a randomly generated 10 character string 'inviteCode' is sent to a table called 'referrals'.
The invited person then receives an email with a URL link that contains their email and their unique inviteCode; http://website.com/register.php?email=email&inviteCode=1234567890
When the user clicks on the link the page register.php should then check the URL and if they data is valid in the 'referrals' table. If so then I have an include line to add the register form, if not then they are redirected. The point is nobody can access register.php unless they have been invited and sent a link.
At the moment the page keeps redirecting to index.php;
Register.php script:
<?php
include 'config.php';
if (isset($_GET['email'],$_GET['inviteCode'])) {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
echo 'lol';
}
else
{
echo 'no';
exit;
}
}
else
{
echo 'problem'; //Page not accessible if neither email nor referral entered
}
?>
I replaced the first if statement with:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else
And I receive a blank page with no errors. I believe there may be something wrong with the email and invite code not being set.
Any help on this would be much appreciated (Y) thanks.
You should really be looking at handling the errors first. Try something like this:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='$email' AND inviteCode='$inviteCode'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
include'register-form.php';
} else {
die(header('Location: index.php'));
}
}
Breakdown
The if block checks to see if GET[email] or GET[inviteCode] are not set. if that is the case, kill the app with die() and redirect the user to index.php.
The second change is this line:
if ($query->num_rows > 0) {
That will check to ensure the rows returned are more than 0 (meaning there are actually rows returned.) Because you were just testing the presence of the $query->num_rows before.
Another Note:
Turn on error reporting, it will help you emensly during debugging:
ini_set('display_errors', 1);
error_reporting(E_ALL);
You could alternatively change your sql query to select the COUNT(id) and check if that is greater than 0, but that seems like overkill for what you're trying to do.
Do this to find out if anything is being returned by your query:
Start by making sure that the connection to your database is succeeding:
$mysqli = new Mysqli(/* your connection */);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$email = $mysqli->real_escape_string($_GET['email']);
Add that then let us know the results afterward, also provide specific error messages.
To debug your num_rows, replace this:
$query = $mysqli->query($sql);
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
With this:
$query = $mysqli->query($sql);
$count = $query->num_rows;
print $count;
exit;
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
If it shows 0, I have a suspicion it is because your sql statement needs to be concatenated.
"SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";

Simple PHP not working

I am creating a ajax notification and this is part of my system allowing a user to favorite, or archive, that notification. The problem is that this php code below won't work and there is no error in the queries because the or die returns nothing. What is returned is just error. That is all it is echoing. I know the javascript is correct and sending the correct information because I have checked the network tab to see. Are there any major errors that I am missing?
<?php
require_once('.conf.php');
$notid = mysql_real_escape_string($get['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($get['action']);
if ($action == 'add') {
$insert = mysql_query("UPDATE updates SET object_fav = 1 WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'success';
} elseif($action == 'sub') {
$remove = mysql_query("UPDATE updates SET object_fav = 0 WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'remove';
} else {
echo 'error';
}
?>
PHP has no default array called $get. Perhaps you intend to use the $_GET superglobal.
$action = mysql_real_escape_string($_GET['action']);
$notid = mysql_real_escape_string($_GET['notification_id']);
It prints error when $action is not matched in your if/else chain, because the variable isn't correctly set.
Be sure that you are developing with display_errors turned on, and error_reporting(E_ALL);. The undefined variable $get would display warnings on screen.
ini_set('display_errors', 1);
error_reporting(E_ALL);

PHP MYSQL connection with query inside IF statement

SOLVED:
There is a conlict with my declaring of variables. It turns out i declare a $password in my connect_database, but also in my account script meaning the $password is always set and therefore always skips pas the if's to the end...and since this is work in progress it's the same simple password as my account login...
ORIGINAL:
I have a problem with queries inside if statements in PHP. I'm doing an account update script.
I require the connection to the database at the top and then depending on the result from the POST, I do diffrent queries in some if statements.
If it runs passed all IF statements it runs a query at the end.
If it's caught by any of the if's, a query is made and I want the script to redirect with a message code and terminate the code with an exit.
The problem is the script will not exit after an if execution is made. It does the query but it runs all the way to the end - no redirect and exit...
I found a workaround which requires the database to be required inside the if statements and then again at the bottom instead of only at the top, but my initial idea was to just include it at the top and use the connection in the if statement and again at the bottom.
Can anyone explain why one works and the other doesn't?
It's not a big deal. I just don't understand why...
Thanks a lot
This doesnt work (Require database outside of the IF statement):
<?php
session_start();
if(!isset($_SESSION["user"])) {
header("location: ../../../login/login_form.php");
exit;
}
$user = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$id = $_SESSION['user_id'];
//Display if user and email is blank - try again---------------
if($user==NULL || $email==NULL){
header('location: ../../../index.php?show=account&message=1');
exit;
}
require_once('../../connect_database.php');
//Check if password is blank - meaning only updating user and email -----
if ($password==NULL){
$query = "UPDATE user SET user='$user', email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
header('location: ../../../index.php?show=account&message=0');
mysql_close();
exit;
}
//Display if password less than 8 characers----------------
if(strlen($password)<8 && $password!=NULL){
header('location: ../../../index.php?show=account&message=2');
mysql_close();
exit;
}
//Run this if everything is to be changed incl. password-------
$query = "UPDATE user SET user='$user', password=md5('$password'), email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
mysql_close();
header('location: ../../../index.php?show=account&message=0');
?>
This works (Require database inside of the IF statement and then again at the bottom):
<?php
session_start();
if(!isset($_SESSION["user"])) {
header("location: ../../../login/login_form.php");
exit;
}
$user = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$id = $_SESSION['user_id'];
//Display if user and email is blank - try again---------
if($user==NULL || $email==NULL){
header('location: ../../../index.php?show=account&message=1');
exit;
}
//Check if password is blank - meaning only updating user and email ----
if ($password==NULL){
require_once('../../connect_database.php');
$query = "UPDATE user SET user='$user', email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
header('location: ../../../index.php?show=account&message=0');
mysql_close();
exit;
}
//Display if password less than 8 characers------------------
if(strlen($password)<8 && $password!=NULL){
header('location: ../../../index.php?show=account&message=2');
exit;
}
//Run this if everything is to be changed incl. password----------
require_once('../../connect_database.php');
$query = "UPDATE user SET user='$user', password=md5('$password'), email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
mysql_close();
header('location: ../../../index.php?show=account&message=0');
?>
The problem is the script will not exit after an if execution is made.
you are wrong. exit operator is plain and simple and always work.
How do you know the query was executed? Any debug output you've got?
Thre are many issues with your code but at least make it less repetitive and moire consistent
<?php
session_start();
if(!isset($_SESSION["user"])) {
header("location: ../../../login/login_form.php");
exit;
}
$user = $_POST['user'];
$password = $_POST['password'];
$email = $_POST['email'];
$id = $_SESSION['user_id'];
//Display if user and email is blank - try again---------------
if (!$user || !$email) {
$message=1;
}
//Display if password less than 8 characers----------------
elseif ($password && strlen($password)<8){
$message=2;
} else {
require_once('../../connect_database.php');
$user = mysql_real_escape_string($user);
$email = mysql_real_escape_string($email);
if ($password) {
$password = "password='".md5($password)."',";
}
$query = "UPDATE user SET user='$user',$password email='$email' WHERE id=".$id;
mysql_query($query) or trigger_error(mysql_error());
$message = 0;
}
header("location: ../../../index.php?show=account&message=$message");
Also note
you cannot use mysql_real_escape_string before connect
using relative paths (all those dots) considered bad practice, especially with location
I believe that location is case sensitive. Try changing it to
header("Location:../../../index.php?show=account&message=0");
Ok here is what i suggest :
Replace all exit with die()
And if that doesn't work try replacing all the Location headers with this :
<script>
window.location='/path/to/your/redirection';
</script>
Let me know if that helps in any way :)

PHP error when using mysql related functions

I have another script that I can't figure out what is wrong with it. I attempted to use the
error_reporting(E_ALL);
to report the errors, but it doesn't report anything. Anyway, here is the code I'm having trouble with.
<?php
error_reporting(E_ALL);
$username = $_POST['user'];
$email = $_POST['email'];
$password = md5($_POST['pass']);
$currname = $_COOKIE['ZBrownTechnologyCorporationBeta'];
$con = mysql_connect("HOST", "USER", "PASS");
if (!$con) {
die('Unable to connect: '.mysql_error());
}
mysql_select_database("zach_blogin", $con);
if(empty($password)) {
$nothing = "nothing";
} else {
mysql_query("UPDATE members SET password = '$password' WHERE username = '$currname'");
}
mysql_query("UPDATE members SET Email = '$email' WHERE username = '$currname'");
if($username==$currname) {
$nothing = "nothing";
} else {
$query = ("SELECT username from members WHERE username = '$username'");
$result = mysql_query($query);
if (!$result) {
header("Location: " . $_SERVER['HTTP_HOST'] . "/public_html/Beta/account.php?invalid");
exit;
}
}
mysql_query("UPDATE members SET username = '$username' WHERE username = '$currname'");
header("Location: ". $_SERVER['HTTP_HOST'] . "/public_html/Beta/main_login.php?update");
?>
I have looked over this code for a while now. Can't seem to get the error reporting to work, so here I am again. Thanks to everyone who has helped, and who will help!
By Request of #Klinky:
When attempting to use this page (named myinfo.php ) in Opera, it displays the default message indicating that it is not able to find the page and/or the server. In Internet Explorer 8, it displays a 500 Internal Server Error.
Here are the server specs:
OS: Linux
HTTP: Apache v2.0.63
PHP: 5.3.3
MySQL: 5.0.91-community
I looked in the logs, and this is the error message:
[Sat Sep 25 21:34:08 2010] [error] [client 68.52.52.190] PHP Fatal error: Call to undefined function mysql_select_database() in /home/zach/public_html/Beta/myinfo.php on line 12, referer: http://zbrowntechnology.com/Beta/account.php
The only thing is, the database I tried to select does exist!
All your UPDATE queries are missing table name:
UPDATE TABLE_NAME SET .....
^^^^^
missing
I would suggest, every time you call mysql_query() check its return value. If its false, the query execution failed and you can get the cause of failure by calling mysql_error()
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
More errors:
You need to enclose strings in single quotes in a query:
mysql_query("UPDATE members SET password = '$password'....
^ ^
missing
Do it everywhere you are using a string in the query.
There is no builtin function name mysql_select_database. I guess you meant mysql_select_db
Change
mysql_select_database("zach_blogin", $con);
to
mysql_select_db("zach_blogin", $con);
Try setting the full URL for snippet:
header("Location: account.php?invalid");
HTTP spec says you should use the full url when doing a redirect. Though many browsers support a relative path. Try:
header('Location: ' . $_SERVER['HTTP_HOST'] . '/project-path/account.php?invalid');
REPLACE /project-path/ with the full path to where your .php files are.

Categories