I know this is duplicate with this question. but I received the same error. I searched a lot for similar questions like : PHP not working on HTML file, PHP script not working in HTML file, Cannot run a simple PHP file on the server and many more but could not find any solution.
I created a very simple login html file, then I wrote the php scripts to do the login action in a separate php file. (in the same folder with html file). My problem is that when I type localhost/filename.php in browser, it returned me nothing. (I mean an empty html page without any error messege). Also, when I press the login button in my html login form, it asked me to save file while I expected to run the php file.
I checked the error log, this is the error:
script '/var/www/connectivity.php' not found or unable to stat [Wed
May 07 17:51:28 2014] [notice] caught SIGTERM, shutting down [Wed May
07 17:51:29 2014] [notice] Apache/2.2.22 (Ubuntu)
PHP/5.3.10-1ubuntu3.11 with Suhosin-Patch configured -- resuming
normal operations [Wed May 07 19:25:34 2014] [error] [client
127.0.0.1] PHP Warning: mysql_connect(): Access denied for user 'root'#'localhost' (using password: NO) in /var/www/connectivity.php
on line 7
this is the php script:
<?php
$host="localhost";
$user="root";
$pass="xxxxx";
$db="test";
$con=mysql_connect($host,$user,$pass) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($db,$con) or die("Failed to connect to MySQL: " . mysql_error());
if(isset($_POST['userId'])){
$userId = $_POST['userId'];
$password = $_POST['password'];
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'" or die(mysql_error());
$res = mysql_fetch_array($sql) or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
exit();
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
exit();
}
}
?>
could someone kindly help me to solve it?
Thanks
where is your mysql_query()?
I think you should add the mysql_query() and try again.
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'";
$query=mysql_query($sql) or die(mysql_error()); **// You didn't add this line**
$res = mysql_fetch_array($query) or die(mysql_error());
your all other code goes here.................. hop your problem is fixed
There are a few issues with the code presented above. The first issue with nothing appearing on the screen is most likely due to PHP throwing errors and crashing OR that you don't have userId set in the HTTP Header for POST data. To make sure you are sending the POST data to the server, you can check the Developer tools of your web browser or on the top of the PHP script use the following code.
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
As for the PHP errors, the first one I notice is that you fail to use the function mysql_query($sql) and you directly insert the SQL variable into mysql_fetch_array(). This is not the proper way to do this.
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'";
$res = mysql_query($sql);
if(!$res) {
// Failed to perform SQL Query
echo 'Mysql Query Failed';
exit();
}
$row = mysql_fetch_array($res);
if(mysql_num_rows($res) > 0) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
exit();
}else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
exit();
}
The other PHP issue is you don't check if $_POST['password'] isset, which you do check for the userId. This is a simple fix by changing one line of code.
if(isset($_POST['userId'])) {
// Changes To
if(isset($_POST['userId'],$_POST['password'])) {
My next note are security features you should really follow. The first main issue is your lack of parsing variables before inserting them into your SQL variable. Never insert variables that users can modify directly into your query. If you stick with the mysql_ functions, you will want to first run the command mysql_real_escape_string() on all variables you pass.
$userId = mysql_real_escape_string($userId);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM User where userId = '$userId' AND password = '$password'";
The next security issue is that you are not encrypting passwords. Alwasy encrypt passwords with unique salts for each user. When the user changes their password the salt should also change.
$salt = generate_salt(); // You need to create this function. Generate a lot of random characters.
$password = hash('sha512',$password.$salt);
Using the above method, you do not want to use mysql_real_escape_string() on the password variable until after you generate it. If you do use it before hashing the password, the user will most likely have trouble logging in in the future since the password may not match.
The next fatal flaw in your code is that you are using the mysql_ functions which is now unsupported and deprecated. As you can see from the quote on the PHP website for all the mysql_ functions.
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
I highly suggest PDO as apposed to MySQLi, but it is just personal preference.
Related
This is the code for my log in forum. The problem with it is that it only accepts as correct credentials the first username and password (basically only the first row) any ideas as to how i could change it ?!
<?php
session_start();
include_once("connect.php");
$token = "";
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
$sql = "SELECT * FROM authme";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
if(isset($_POST['realname']))
$username = $_POST['realname'];
if($result->num_rows>1){
if(mysqli_num_rows($result)>1){
$_SESSION['uid'] = $row['id'];
$_SESSION['realname'] = $row['realname'];
}
$password = '$SHA$'.substr($row['password'],5,16).'$'.hash('sha256', hash('sha256',$_POST['password']).substr($row['password'],5,16));
if($password == $row['password'] ){
header("Location: index.php");
exit();
}
else {
echo "INVALID INFORMATION, PLEASE RETURN!";
// header("location: index.php");
session_destroy();
exit();
}
}
}
}
?>
?
I decided to try to make a log in forum that uses a database which encrypts the passwords it receives through a register form. This code only takes as correct the first username and password i give in and its not enough, as you could imagine.
Welcome to programming with PHP. I'm going to try to share a few principles that may help you solve your problem.
1.) One of the best features in PHP is the print_r() function. Using this function you can output almost anything to text in the browser. So in this case you may want to insert a print_r($result) immediately following this line "$result = mysqli_query($con, $sql) or die(mysqli_error($con));". This will output the results of the query that PHP is receiving. This can be used to help you troubleshoot and determine why your code isn't working. Once you're done troubleshooting delete that line.
2.) You seem to have multiple checks for the number of rows inside the while loop. I'm not sure why you have thoose there, but you may want to check if those are causing your trouble by using echo or print to display to values in the browser for troubleshooting. Once you're done troubleshooting delete that line.
3.) Another overall concept for the data you are querying. It is inefficient to send a query that gets the entire table and returns it to the program, that then loops through every row looking for the data. Instead you should write an SQL query to return only the row of data the you want. Make sure you do use prepared statements.
4.) Your coding standards could use some improvement, if you clearly tabbed your statements it would be easier to read. Consider reading PSR-2. For example this code seems to be missing {}'s.
if(isset($_POST['realname']))
$username = $_POST['realname'];
Can someone please explain to me why I keep getting the following error when I use the mysqli_num_rows() function?
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Here is my php script:
<?php
//stores user input as variable
$username = $_POST['username'];
$password = $_POST['password'];
//selects from users table
$sql = "SELECT * FROM Members WHERE username='$username' and password='$password'";
$results = mysqli_query($con,$sql);
$count = mysqli_num_rows($results);
/*//starts session and sets cookie if count is true
if($count>=1)
{
session_start();
$_SESSION['username'] = ' ';
$_SESSION['password'] = ' ';
header("location: index.html");
}
//returns message if user input does not match database
else
{
echo "Invalid username or password";
}*/
?>
I get this error at the mysqli_num_rows() function everything before it works fine. I am using Plesk on a Godaddy server by the way.
You need to learn how to read php and mysqli errors
You need to learn how to use mysqli properly
You don't heed this function at all
How to get mysqli error in different environments? for the first
and How can I prevent SQL injection in PHP? for the second
just fetch your data and use it as a flag for the last
As far as I can see there is no function as mysqli_num_rows().
Is the $con variable declared elsewhere? I don't see it being declared. Also, you are subject to injection attacks with this current code. Make sure you escape your parameters before using this publicly.
This is for an Android application and I am using web-services written in php. I have 3 php scripts - dbconnect.php(this has all the db variables), login.php(this validates the user credentials and open a session) and showCases.php(which will return a list of tickets from the userID variable obtained from the login.php script)
However, for some reason I have: "Access denied for user 'ODBC'#'localhost' (using password: NO)" when I am requesting information showCases.php. I am not quite sure if the session is being used correctly.
Here is the login.php script:
//Displaying the error if sql query is incorrect
if(!$result){
die(mysql_error());
}else{
$row = mysql_fetch_assoc($result);
$first_name = $row['first_name'];
$id = $row['id'];
}
//If found, number of rows must be 1
if($num_rows==0){
$success = 0;
}else{
//creating session
session_start();
session_register("$username");
session_register("$password");
$success = 1;
}
$arr = array(
array('username' => $username, 'id'=>$id,'success'=>$success, 'first_name'=>$first_name));
#array('success'=> $success));
echo json_encode((array('Username'=>$arr)));
mysql_close();
?>
The script would return the username array to the android application for it to process the validation. Upon validation, the android application would request tickets from this php script.
session_start();
#require('dbconnect.php');
require_once('login.php');
$response=array();
$response['infos'] = array();
//execute the SQL query and return records
$result = mysql_query("SELECT cases.id, cases.account_id.... casesvisibility.user_id = '$id'......";
//Displaying the error if sql query is incorrect
if(!$result){
die(mysql_error());
}
$num_rows = mysql_num_rows($result);
$arr = array();
if($num_rows!=0){
while ($row = mysql_fetch_assoc($result)) {
$arr['cases_id']=$row['cases.id'];
$infos[]=$arr;
}
}else{
#$arr['existingCases']=$row['0'];
$arr['cases_id']=0;
$infos[]=$arr;
}
#Echoing a JSONArray
print(json_encode(array('Cases'=>$infos)));
//close the connection
mysql_close();
?>
I am not too sure this is well-written code for the functionality I want it to achieve. When I call this script from android application, I first get the JSON_array from the login script and it tells me:
{"Username":[{"username":"","id":null,"success":0,"first_name":null}]}id is
Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'#'localhost' (using password: NO) in E:\wamp\www\mobile.dcl.mu\webserver\showCases.php on line 18
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in E:\wamp\www\mobile.dcl.mu\webserver\showCases.php on line 18
Access denied for user 'ODBC'#'localhost' (using password: NO)
I understand that I'm trying to use a variable from another php script.
Can you help me some this issue please?
Thank you
Where you create $num_rows? Probably you want to put this code in top login.php:
//Displaying the error if sql query is incorrect
if(!$result){
die(mysql_error());
}else{
$num_rows = mysql_num_rows($result);
if ($num_rows) {
$row = mysql_fetch_assoc($result);
$first_name = $row['first_name'];
$id = $row['id'];
}
}
I think you are mixing up session and db connection (if I understand your code snippets correctly).
Keep in mind, that for the server, each request is a completely new process. You can share variables via session, but you can not share process bound resources like the db connection.
as your server is telling you, on the second request there is no password and maybe even the wrong (default?) db user given.
So, what you need to do is simply this:
Provide the db connection information in every possible execution path. i.e. if your android app calls http://your.server/showCases.php directly, include dbconnect.php in showCases.php, too.
I think you had it once:
in your second script you have this line:
#require('dbconnect.php');
try uncommenting this again, it may bring you a step closer to your goals.
P.S. the pure mysql_* functions are deprecated, read the php.net docu (or other questions here) for the security concerns regarding these functions. Upgrade your scripts to use PDO or mysqli
Most likely issue with your database connection call, you are either not providing correct username and or password. i suspect missing password . check your database connection
$db_host = "localhost"; // database host
$db_name = "test"; // database name
$db_login = "root"; // database user
$db_pass= "*****"; // database password
$db = mysql_connect($db_host, $db_login, $db_pass);
mysql_select_db($db_name,$db);
this is just sample code to indicate what i am referring to. Also, make sure you include this db connection file on each php file. There are various ways to make db connection available to different php files( where sql calls gets make)
I am using my admin panel login script where i have created a global.php file with code including this:-
<?php
$Global['host']="localhost";
$Global['username']="username";
$Global['password']="*******";
$Global['database']="database_name";
$Global['baseurl']='www.somesite.com/work/';
$connhandle=mysql_connect($Global['host'],$Global['username'],$Global['password'])or die('can\'t establish connection with mysql database');
$dbSelect=mysql_select_db($Global['database'],$connhandle) or die('could not connect to the database');
?>
and for calling the script on clock i m using a redirect.php file which include code as follows:-
<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['password'] = $_POST['pass'];
$_SESSION['aid'] = 0;
include 'global.php';
$admin_themes=mysql_fetch_object(mysql_query("select * from admin where id='1'"));
$ruser = $admin_themes->username;
$rpass = $admin_themes->password;
if ($_SESSION['username'] == $ruser && $_SESSION['password'] == $rpass) {
$_SESSION['aid'] = 1;
header("location:../index.php");
}
else {
header("location:../admin_login.php?passcheck");
}
?>
no this scripts in working absolutely fine when i run this using my xampp server on local. but when i upload it to my online server the redirect script show me this error:-
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'username'#'localhost' (using password: YES) in /home/..../public_html/work/h_cms/configuration/global.php on line 9
can't establish connection with mysql database
any suggestion why its not showing on online server i have used the correct username and pass of my database i have checked it 5 times. But still not find where is the problem.
username#localhost is clearly not the correct username based on the error message. if you're subscribing to a hosting provider, you may want to check with them the correct username for your mysql account.
also, you might want to try using your domain name instead of localhost.
Your database username, password or hostname is not correct. You need to check what the correct details are and update your code accordingly.
Be aware afterwards you might need to create the necessary database and tables again so your app can run.
EDITThanks to the comments below it has been figured out that the problem lies with the md5, without everything works as it should.
But how do i implent the md5 then?
I am having some troubles with the following code below to login.
The database and register system are already working.
The problem lies that it does not find any result at all in the query.
IF the count is > 0 it should redirect the user to a secured page.
But this only works if i write count >= 0, but this should be > 0 , only if the user name and password is found he should be directed to the secure (startpage) of the site after login.
For example root (username) root (password) already exists but i cannot seem to properly login with it.
<?php
session_start();
if (!empty($_POST["send"]))
{
$username = ($_POST["username"]);
$password = (md5($_POST["password"]));
$count = 0;
$con = mysql_connect("localhost" , "root", "");
mysql_select_db("testdb", $con);
$result = mysql_query("SELECT name, password FROM user WHERE name = '".$username."' AND password = '".$password."' ")
or die("Error select statement");
$count = mysql_num_rows($result);
if($count > 0) // always goes the to else, only works with >=0 but then the data is not found in the database, hence incorrect
{
$row = mysql_fetch_array($result);
$_SESSION["username"] = $row["name"];
header("Location: StartPage.php");
}
else
{
echo "Wrong login data, please try again";
}
mysql_close($con);
}
?>
The best thing you can do in such situations is trying to find out where the problem lies.
So, you could proceed by steps and do the following:
1) start your script with a print_r($_POST), to see what variables are passed by post (by absurd, the problem might even be related to the 'send' guard parameter you have ..IE a form being sent through get)
2) Assign your query to a variable (...and don't forget to escape parameters!) and print it to screen; and then exec it on mysql (or phpmyadmin) to see what results they give.
As a side note, as someone already pointed out, this code might be subject to SQL-injection, so you might consider using prepared statements; see here: quick intro
Your login code is good.
But you also need to use md5() function BEFORE storing the password in the database. So when you are inserting the user record in the DB , apply the md5() to the password , save in the DB. Now when you will try to find the record on login, it will match correctly.
You should rewrite this with mysqli or PDO and using a newer hash function as well as a salt. MD5 is very widely used and is a target for crackers.