PHP error when using mysql related functions - php

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.

Related

PHP - Access Denied while passing parameters through URL

I made a php script which'll echo an image if the correct password is entered; so that, nobody can access the images stored on my server directly, thus, making my server more secure. Now, for the php script I used GET method to generate a mysql_query to my database in order to check if the email and password entered by the user are associated with a relevant account and then echo the image from a folder on my server. Now, in order to pass the parameters while runtime, I'm adding them in the URL like this:
http://<mywebserver>/get_image.php/?email=<email>&password=<password>&file_name=<image-file-name>
But, something's wrong with this whole setup, and I'm getting the following error:
Warning: mysql_query() [function.mysql-query]: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO) in
/home/uXXXXXXXXX/public_html/get_image.php on line 11
Warning: mysql_query() [function.mysql-query]: A link to the server
could not be established in /home/uXXXXXXXXX/public_html/get_image.php
on line 11 Error getting data: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO)
Here is my php script, get_image.php:
<?php
$file_path = "/ProfilePics/";
if(isset($_GET['email']) && isset($_GET['password']) && isset($_GET['file_name'])) {
$id = "\"" . $_GET['email'] . "\"";
$typed_password = "\"" . $_GET['password'] . "\"";
$file = $_GET['file_name'];
$result = mysql_query("SELECT * FROM students WHERE email = $id AND password = $typed_password") or die ("Error getting data: " . mysql_error()); //line 11
if(!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$user = array();
$user["email"] = $result["email"];
$user["password"] = $result["password"];
$pass = "\"" . $user["password"] . "\"";
if($pass == $typed_password) {
$img_path = $file_path . $file;
echo '<img src="' . $img_path . '" name = "cover" />';
} else {
echo "Incorrect password";
}
} else {
echo "Unable to find user";
}
} else {
echo "Unable to find user";
}
} else {
echo "Required field(s) is missing";
}
?>
I agree, that there are lots of other questions already on stackoverflow stating similar problems. But, I didn't find the solution(s) to those questions applicable for my code. So, any help on this will be highly appreciated. Thank you for your time!
This is because you have not connected your file get_image.php to your MySQL database. Do so as follows:
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
Simply replace the information above with the correct information.
You don't seem to be connecting to the database before you try to send queries to it.
It should like something like this:
$conn = new mysqli($servername, $username, $password, $dbname);
Taken from the example here:
http://www.w3schools.com/php/php_mysql_select.asp
Furthermore, if you care, you should consider using PDO or some other method of preventing SQL injection attacks.
SQL Injection:
https://en.wikipedia.org/wiki/SQL_injection
Information on PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
setup a database connection first:
$con = mysql_connect('server','username','password');
$rst = mysql_query('select...', $con);
remember that kind of library to access mysql is outdated.
imagine someone logging in with this password:
password = '"; DROP TABLE students;'
or something crafted better.
There are different libraries like PDO or MYSQLI that take cares of this for you.
in newer releases of php standard mysql libis deprecated and removed

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.

Comparing hash causing issues

I have a site that I am storing the username and hashed password in a table. I am trying to compair this information (username and hashed password) to the login information passed from my login site. Unfortunately this keeps crashing. If someone could point me in the right direction as to what I am doing wrong I would appreciate it. Below is the code I am using to check the login. It may be something very simple as I am still pretty new to php.
<?php
$myServer = "server.domain.com";
$myUser = "readaccess";
$myPass = "password";
$myDB = "database";
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
//declare the SQL statement that will query the database
$query = "SELECT password, salt ";
$query. = "FROM dbo.members ";
$query. = "WHERE username = '$myusername' ";
$result = mssql_query($query)
or die('A error occured: ' . mssql_get_last_message());
// SQL_num_row is counting table row
$count=mssql_num_rows($result);
if($count) < 1) //no such user exists
{
header('Location: main_login.php');
}
$userData = mssql_fetch_array($result, MSSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $mypassword) );
if($hash != $userData['password']) //incorrect password
{
header('Location: main_login.php');
}
else {
header('Location: index.php');
}
?>
I think the problem is this line
$result = mssql_query($query)
or die('A error occured: ' . mssql_get_last_message());
The proper way to check failure is
$result = mssql_query($query, $dbhandle);
if(!$result)
die('A error occured: ' . mssql_get_last_message());
Note that this goes for the mssql_connect and mssql_select_db statements as well.
Note that you need to provide the database resource to the mssql_query function.
Also, most people find it more readable if you use .= without a space between them. I don't think it produces a parse error, but it make a lot of sense to keep the whitespace out of the operand. (You wouldn't do $counter+ +; even if it were legal.)
Note for asking future questions, always include whatever error message you're seeing and, if it is referencing a line number, point out that line in your code sample. In this case, I don't think your problem has anything to do with hashing or sql, as it's entirely a parse/syntax error.

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 help needed no error being outputed

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.

Categories