Simple PHP not working - php

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);

Related

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."'";

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.

Mysql result to set session variable

I want to use the result of a mysql query to set a session variable however at present I am struggling to make it set.
My code I have is:
<?php
ob_start("ob_gzhandler");
?>
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
I am then testing the session variables with:
<?php
session_start();
echo "Login Status is:".$_SESSION['logged_in'];
echo "<br/>";
echo "Auth status is level:".$_SESSION['auth_lvl'];
?>
On my testing page the session logged in works fine displaying the correct information however the auth lvl variable displays nothing.
I can only assume that I am not calling the information correctly that I am setting the variable with in the first place.
Any help would be appreciated.
Alan.
Something I have notice and I have been trying the suggestions is that if I set a definative rather than trying to retreive a value from the database that value will return on my test page. i.e.
$_SESSION['auth_lvl'] = 'test';
This tells me it is the way in which I am pulling the data from the database and trying to set it as $_SESSION['auth_lvl'] that is causing the problem.
Found the problem.
the code read:
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['Auth_lvl'];
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
Because I had used mysqli on this code I had not notice that on the //ADD THIS SET OF LINES piece of code that an 'i' was missing. When I changed the code to:
$data = mysqli_fetch_assoc( $result );
Everything fired into life.
Thanks for your help guys.
I can't see anywhere that you have assigned $Auth_lvl with a value, so when you do:
$_SESSION['auth_lvl'] = $Auth_lvl;
It's presumably getting assigned null.
I'm not seeing where you are setting $Auth_lvl. After you check for the results being there, and rows, you're going straight to setting a session variable against an empty variable.
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['auth_lvl']'
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
Then with your logged_in session variable, you're setting it as a boolean, true, and then trying to echo it out as normal text.
if ( $_SESSION['logged_in'] ) { echo "Login status is: True"; }
I hope that helps.
-Dan

PHP seems to be refusing to connect to MySQL

<?php
function redirect_to_index_with_error(){
echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
function go_to_home(){
echo '<meta http-equiv="refresh" content="0;url=home.php">';
}
$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";
mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing
mysql_select_db("mcp") or die(mysql_error());
$results = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($results) == 0){
redirect_to_index_with_error();
exit();
}
$userID = null;
$name = null;
$school = null;
$mod = null;
while($user = mysql_fetch_array($results)){
$userID = $user['ID'];
$name = $user['Name'];
$school = $user['School'];
if($user['Mod'] == '1')
$mod = true;
else
$mod = false;
}
if(!isset($_SESSION))
session_start();
//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;
go_to_home();
exit();
?>
PHP echos everything up until "connected". It's not even showing a mysql error. I've had this code work flawlessly on Windows with WAMP, but not on Mac with MAMP. I've verified that the servers are running, so I can't tell what the problem is. I'm using PHP 5.3.6.
Your connection needs to be established before you call mysql_real_escape_string()
So move mysql_connect("localhost","root","") or die(mysql_error()); to the top.
Move the mysql_connect() statement above everything else.
// put this at the TOP
mysql_connect("localhost:3306","root","") or die(mysql_error());
Just as everyone else mentioned, see this note:
http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes
Also, you should see errors, in development, at least.
See: error_reporting()
you have to call mysql_real_escape_string() after connect.
otherwise this function returns an empty string and your query fails.
though it raises an error but it seems you haven't seen that.
So, you ought to either turn displaying errors on or peek error logs - it's impossible to program without ability to see error messages
Also, you have to improve your formal logic.
To make a statement like "PHP seems to be refusing to connect to MySQL" youi have to verify it first. Connect is just a single line and returns a value.
You can verify this value and make a certain conclusion.
But running whole code of several dozens of lines and making statements about just one makes no sense.

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