I'm trying to use mysql_real_escape_string() to secure a log in form.
Using this code:
include_once 'access-shared.php';
include_once 'access-databaseconnect.php';
session_start();
$email = mysql_real_escape_string(isset($_POST['email'])) ? mysql_real_escape_string($_POST['email']) : $_SESSION['email'];
$password = mysql_real_escape_string(isset($_POST['password'])) ? mysql_real_escape_string($_POST['password']) : $_SESSION['password'];
Trouble is it throws up an error every time:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'xxx'#'localhost' (using password: NO)
I can't get my head around it, the db user has all permissions and the username details are correct in the access-databaseconnect.php file. It works perfectly without the mysql_real_escape_string around the $_POST but obviously it leaves it open to mySQL injection.
Any help is most appreciated.
EDIT: Here is the contents of the access-databaseconnect.php file:
<?php
$dbhost = 'localhost';
$dbusername = 'xxxx';
$dbpassword = 'xxxx';
function dbConnect($db='') {
global $dbhost, $dbusername, $dbpassword;
$dbcnx = #mysql_connect($dbhost, $dbusername, $dbpassword)
or die('Cannot connect to Database: '.mysql_error());
if ($db!='' and !#mysql_select_db($db))
die('Cannot connect to Database: '.mysql_error());
return $dbcnx;
}
?>
In order to use mysql_real_escape_string(), you must have already established a connection via mysql_connect(). If that does not occur in access-databaseconnect.php, or the connection has not succeeded, you will not be able to call mysql_real_escape_string()
Update
You define the function dbConnect() in access-databaseconnect.php, but you never call it. Create your connection as
$dbcnx = dbConnect($dbname);
An additional note, but not the source of your problem... Do not call mysql_real_escape_string() around the result of your isset() calls. Though it is most likely harmless, it is unnecessary.
$email = mysql_real_escape_string(isset($_POST['email'])) ? mysql_real_escape_string($_POST['email']) : $_SESSION['email'];
// Should be
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : $_SESSION['email'];
Related
I've looked through StackOverflow for an answer to this and have so far come up empty handed. I know some have had a similar issue, but so far none of the responses to the issues have worked.
So I work on two sites, both of which are on the same host with the same PHP Admin set up (different accounts and domains, sites are not affiliated). One of them uses MySqli perfectly, without issues, while the other either gives a database selection failure, localhost access denied with password as "NO" or a blank page when I attempt to replace the MySql with MySqli.
The deprecated code:
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = #mysql_connect($host,$usr,$pwd);
if(!$connection){
die("No connection.");
}
mysql_select_db($dbname,$connection);
The MySqli I am attempting (identical to the site that MySqli works perfectly on):
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = mysqli_connect($host,$usr,$pwd);
if (!$connection) {
die("No connection.");
}
$db_select = mysqli_select_db($connection, $dbname);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
So the PHP error codes did not work at all and it had nothing to do with the local host or port, so I first checked to make sure mysqli_connect was on. Next, I ran a simple test where I echoed a random word before each mysqli command.
echo 'Passed.';
global $c_mysqli;
$conn = new mysqli($host, $usr, $pwd, $dbname);
echo '<br>Passed global mysqli.';
I found that my second pass was not working, and then proceeded to do an error message. An error showed up then. However, nothing I did fixed the issue... then I realized that one of my files, the header file, is the meat and potatoes and if it were to fail then everything else would fail too.
Sure enough, one of my lines of code contained a mysql connection and not mysqli. Long story short, double check and triple check to make sure that all
$statement = mysql_query("STATEMENT");
$query = mysql_fetch_array($statement);
Appear as
$statement = $conn->query("STATEMENT");
$query = mysqli_fetch_array($statement);
I'm using a PHP file stored on my host to connect to a database stored on the same host, this is working fine.
I am using the below to connect to the database (example connection details)
<?php
$db = new PDO('mysql:host=localhost;dbname=myDB', 'myusername', 'mypassword');
My question is; seeing as I have specified the password (and other details) to connect to my server in my PHP file, can't someone with the direct link to my PHP file just download it and open it in a text editor to see those details?
If so, should I be passing the connection details to the php file like this:
<?php
$server = $_POST['server'];
$database = $_POST['database'];
$username = $_POST['username'];
$password = $_POST['password'];
$db = new PDO('mysql:host=$server;dbname=$database', $username, $password);
Expanding a bit on my comment, ideally you want to have this in separate files, one used for global configuration you can then import to your other modules like the example below.
Config.php file:
<?php
$HOST = 'hostname';
$DB = 'dbname';
$USER = 'username';
$PWD = 'password';
... other variables and global config ...
?>
DB Connection File:
<?php
include 'config.php';
$db = new PDO("mysql:host=$HOST;dbname=$DB", $USER, $PWD);
?>
Notice how the string inside the PDO connection is double quoted, because if single quoted, string interpolation won't work.
Your variable $server and $database are not interpreted correctly as you are using single quote '. You need to use double quote " to correctly pass variable values. (Refer for more details What is the difference between single-quoted and double-quoted strings in PHP?) Change your code as below.
<?php
$server = $_POST['server'];
$database = $_POST['database'];
$username = $_POST['username'];
$password = $_POST['password'];
// Replaced ' with "
$db = new PDO("mysql:host=$server;dbname=$database", $username, $password);
Just moved my site to new hosting. On the new server mysql_connect() works fine if called without using classes or inside of the method but not from the _construct. When connecting from the _construct the following error displays:
Access denied for user 'root'#'localhost' (using password: NO)...my configuration defines the user not as root but as USERNAME and does provides a password.
PHP 5.6, MySQL 5.5, Linux
Class File:
function __construct(){
error_reporting(E_ERROR);
$dbhost = 'localhost';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'DATABASENAME';
$this->urlAppPath = "http://www.myurl.com/CD/";
// connect to the database
$this->db = mysql_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . $SQL);
mysql_select_db($dbname);
}
function validatePerson($personID) {
$SQL = "SELECT *,COUNT(*) AS total FROM zen_customers WHERE customers_classware_id = '$personID'";
$result = mysql_query( $SQL ) or die("Could not execute query 1 . ".$SQL." ".mysql_error()." & ". $dbhost ." ".$dbuser ." ".$dbpass." ".$dbname);
}
Call Method File:
require_once('./clsCart.php');
$myclass = new clsCart();
$result2 = $myclass->validatePerson($personID);
Note
If I define and call the connection within the file that I have been trying to call the method...that is instead of calling the method it works. If I define and call the connection within the method it works...but if I define and call the connection within the construct() it does not work...error "Access denied for user 'root'#'localhost' (using password: NO)". This seems to be specific to some servers...regardless of using PHP 5.6 or lower & MySQL 5.6 or lower.
So, if I use :
$dbhost = 'localhost';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'DATABASENAME';
// connect to the database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . $SQL);
mysql_select_db($dbname);
Outside of the class or within the method then it works...but, I should (as I have in the past) be able to connect within the construct().
This seems to be related to a server issue. From the __contruct() only the Database default user information is being recognized. Everywhere else in the applications uses the User created for the database, but the construct will only connect when using the default database user on this server. Other servers are not having this issue, such that any database user with all privileges work.
You have to use mysqli_connect. Please never use mysql_connect it deprecated in PHP 5.5.0 and onwards. If still you face issue please let us know.
Following code for mysqli_connect :
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Definition and Usage
The mysqli_connect() function opens a new connection to the MySQL server.
Syntax
mysqli_connect(host,username,password,dbname,port,socket);
Parameter Description
port Optional. Specifies the port number to attempt to connect to the MySQL server.
socket Optional. Specifies the socket or named pipe to be used.
I am having an issue with connecting my PHP script to the database on my localhost server.
I have posted the code below, it is to enable user registration on the site.
The input boxes appear as they should when I run the code, but nothing updates to the database when I try and complete a sign up.
As a novice with PHP I don't know enough about it to spot any errors I might be making, or what they mean.
Any help on this subject would be appreciated as there is a lot of info about PHP online, but I would rather know what was causing this error in order to prevent it in the future.
Here are the errors appearing in the browser console:
Failed to load resource: the server responded with a status of 404 (Not Found)
ReferenceError: Can't find variable: $
And the UNIX socket code from MAMP (I don't know where this would fit in):
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
And the PHP code:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
if (isset($_POST['register_btn'])) {
session_start();
$username =mysql_real_escape_string($_post['username']);
$email =mysql_real_escape_string($_post['email']);
$password =mysql_real_escape_string($_post['password']);
$password2 =mysql_real_escape_string($_post['password2']);
if ($password == $password2) {
//create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
}else{
$_SESSION['message'] = "Your passwords must match to proceed";
}
}
?>
Where to start? So many problems.
First off, you are using the OLD mysql functions which have been removed entirely in recent versions of PHP. Use the mysqli functions instead. The old functions like mysql_connect and mysql_query have been deprecated. You need to look for all occurrences of mysql_ in this code and think about replacing each command with its new counterpart.
You define this code to connect:
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
and then you don't use the resulting connection -- even check if it worked. You should always check the value returned by mysqli_connect to see if it actually worked or if it returned FALSE. You reconnect again and don't bother checking to see if it worked:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
And in doing so, you redefine $db to something else.
Also, you run a query without checking whether it succeeded or not:
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
You should be checking the result of mysqli_query (not mysql_query as you have in your code) to see what it returned. It should be TRUE if the INSERT query worked.
And after you redirect, you fail to call exit, which means that all the code that follows your redirect attempt may end up actually executing anyway.
I keep getting this whenever I run the below code:
Fatal error: Call to undefined function mysql_connect() in C:\wamp\www\php-academy\113-connect-db.php
<?php
$conn_error ='could not connect';
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
mysql_connect($mysql_host, $mysql_user, $mysql_pass) or die($conn_error);
$mysql_db = 'a_database';
mysql_select_db($mysql_db) or die($conn_error);
echo 'Connected!';
?>
That probably means you don't have the MySQL extension loaded. You can test whether the extension is loaded with extension_loaded("mysql");.
I suspect that this is because the extension is not loaded. I would check your php_info(); to find out.
Once you do your code should work, although I prefer to assign the mysql_connect() to a variable and then call that variable in mysql_select_db() as I have below:
$defHost = 'localhost';
$defUsername = 'username';
$defPassword = 'password';
$defDatabase = 'database_name';
$connect = mysql_connect($defHost, $defUsername, $defPassword) or die();
mysql_select_db($defDatabase, $connect) or die();
The reasons for the error may be the following:
Incorrect access details to server database are specified in configuration file.
There are no read permissions for configuration file. Provide read permissions for the file.