<?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.
Related
for some reason my login script in php keeps returning invalid results, I'm using PHPMYADMIN to handle the database and mysqli to connect however whenever I submit the data though a HTML form the values always return false even if the correct username and password combo is working.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysql_connect("localhost","cnathanielwcol","","login");
if(! $con){die('Connection Failed'.mysql_error());}
$result = mysqli_query("SELECT * FROM login");
$row = mysql_fetch_array($result);
var_dump($row);
if ($row["username"]==$username) {
echo "Correct Username<br>";
} else {
echo "Wrong Username<br>";
}
if ($row["password"]==$password) {
echo "Correct Password<br>";
} else {
echo "Wrong Password<br>";
}
echo "<br><br>Username Submited Via HTML: <b>" . $username . "</b>";
echo "<br>Password Submited Via HTML: <b>" . $password . "</b>";
?>
MySQL is deprecated from new version of PHP use
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
Firstly, you need to select a single row, not all the rows in your table, you'd do that by specifying a WHERE clause, currently, you are trying to compare an array of values to a string which should be throwing an error if error reporting is enabled.
Secondly, you are mixing to different APIs, mysql_* is not mysqli_*.
Thirdly, it doesn't seems as though you are hashing your passwords, please, do so.
Fourthly, make use of prepared statements, it seems as though you are still learning so it would be best to start using them now.
Reading Material
OWASP's Password Storage Cheat Sheet
OWASP's PHP Security Cheat Sheet
Could you use mysqli_* please? You might be having a problem with your html form maybe
Change
$con = mysql_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
With
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
Your are trying to fetch the data with mysqli and your database connection is established by mysql
your full code:
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysqli_connect("localhost","cnathanielwcol","","login") or die('connection is not establised'.mysqli_error($con));
$result = mysqli_query($con,"SELECT * FROM login WHERE username='$username' AND password='$password'");
$rowCheck=mysqli_num_rows($result);
if ($rowCheck>0) {
// fetch all data
//start session
echo "you are logged in ";
}
else{
echo 'username or password did not match';
}
Use hash password.your code is not safe.
I am mostly confused about the new php 5.5, I apologize for any inconvenience.
I am trying to get information from whomever logs in, so for example if I log in with an email, I'd like the website to get my first name and do a "Welcome, Shinji!".
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn , 'session_start');
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysqli_query($conn , "SELECT * FROM `info_table` WHERE '$user' = `user` AND '$pass'=`password`") or die(mysqli_error($conn));
$rows = mysqli_num_rows($query);
if($rows == 1){
#$query2 = mysqli_query($conn , "INSERT INTO `who_logged` (`name`) VALUES ('$user')") or die(mysqli_error($conn));
#$rows = mysqli_num_rows($query);
session_start();
$_SESSION['username'] = $_POST['user']; // store username
$_SESSION['password'] = $_POST['pass']; // store password
$query2 = mysqli_query($conn ,"SELECT `name` FROM `info_table` WHERE '$user' = `user`") or die(mysqli_error($conn));
$result = mysqli_num_rows($query2);
while ($row = mysql_fetch_assoc($result)) {
$_SESSION['name'] = $row['name'];//I thought to try setting the name to the Session variable, but does not work
}
header('Location: next_page.php');
exit();
}else{
echo "Wrong username or password.";
}
I tried to set the name to a session variable, but if there is a more efficient way please say so! (This current code works, except the name setting to session.
You have your column(s) and values mixed up in order.
It's column first, then the value and not the other way around.
Change both:
WHERE '$user' = `user` AND '$pass'=`password`
to:
WHERE `user` = '$user' AND `password`='$pass'
Plus, you're mixing MySQL APIs. Those different APIs do not intermix with each other.
Change mysql_fetch_assoc to mysqli_fetch_assoc
I noticed you are using sessions; make sure session_start(); is indeed loaded.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also, add or die(mysqli_error($conn)) to mysqli_query()
Your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
EDIT:
Try the following instead and it will get you started. Please read my footnotes concerning the use/storage of plain text passwords.
Sidenote: I removed $_SESSION['password'] = $pass; // store password
do not do this, it's insecure.
Plus, do not put anything "above" the PHP below, such as HTML etc., otherwise, you will receive a warning about headers already sent.
<?php
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'session_start');
$user = stripslashes($_POST['user']);
$user = mysqli_real_escape_string($conn,$_POST['user']);
$pass = stripslashes($_POST['pass']);
$pass = mysqli_real_escape_string($conn,$_POST['pass']);
$query = mysqli_query($conn , "SELECT * FROM `info_table`
WHERE `user` = '$user' AND `password`='$pass'")
or die(mysqli_error($conn));
$num_rows = mysqli_num_rows($query);
if($num_rows > 0){
session_start();
// it's not really needed
// we are pulling it from $row['user'] in the while loop
// and setting it to $_SESSION['username']
// $_SESSION['username'] = $user; // store username
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['username'] = $row['user'];
}
// for testing only. Do not use with header
// echo $_SESSION['username'];
header('Location: next_page.php');
exit();
}
// do not place any echos here, only the else statement
else{
echo "Wrong username or password.";
}
next_page.php
<?php
session_start();
if(isset($_SESSION['username'])){
echo $_SESSION['username'];
}
else{
echo "Not logged in.";
}
Footnotes
It is highly recommended that you do not store passwords in plain text.
Visit the following Website:
http://daveismyname.com/login-and-registration-system-with-php-bp
It contains a full registration/login/verification system as well as using PDO with prepared statements and PHP's password_hash() function, which is highly recommended.
Since you are using PHP 5.5, then you will benefit from these features.
I have no idea what's going on. I usually have simple sign in pages like this done very quickly but this one isn't working and I cannot spot the error.
<?php
$con=mysql_connect("db_server","db_user","db_pass","db");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$query="SELECT username FROM users ";
//$query.="WHERE `username`=".$username;
//$query.=" AND `password`=".$password;
echo "query=".$query."<br/>";
$result = mysql_query($query, $con);
echo "result=".$result."<br/>";
if($result){
$row = mysql_fetch_assoc($result);
$data = $row['username'];
echo "data=".$data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>
im using mysql_* instead of mysqli_* as the server im running it on is 5.2; not sure if that is relevant but I was getting an unrecognized function error originally.
There is only one entry in the database. As I said, I use the regular SQL code through phpmyadmin and i get the results i need.
Also not sure if relevant. I'm echoing $result and nothing comes out. Isnt it supposed to echo "false"?
You have a major error in your logic, for one. If there is an error connecting to MySQL, you print the error, but yet proceed to query the broken connection - you are also not selecting a database.
Also, this approach is for PHP4. Unless you are stuck in PHP4 on this project, moving into the PHP5 world would be a good idea.
I recommend looking into PDO:
http://www.php.net/manual/en/book.pdo.php
As for not getting errors, check your error_reporting and display_errors settings in your .ini
Try this one.
<?php
$con=mysql_connect("db_server","db_user","db_pass");
mysql_select_db("db");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$query=mysql_query("SELECT username FROM users");
if($query){
$row = mysql_fetch_assoc($query);
$data = $row['username'];
echo $data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>
I converted my login page to use PDO but now it's not working. I've run through all kinds of code examples and I can't figure out where I'm going wrong. This looks perfect to me. Also error reporting is fully enabled and yet I don't get any errors. I just get the browser error for the page being "incorrectly configured". FYI, this is a SQL db
//Code
<?php
require ("../Android/connect_db.php");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query_unpw = $db->prepare("
SELECT member_mast.company_name
FROM member_mast
WHERE username = ?
AND password = ?
");
//$username = $_POST['username'];
//$password = $_POST['password'];
$username = 'abc';
$password = 'abc';
$name = "name";
$query_unpw->bindValue(1, $username, PDO::PARAM_STR);
$query_unpw->bindValue(2, $password, PDO::PARAM_STR);
$query_unpw->execute();
$count = $query_unpw->rowCount();
if ($count > 0) {
while ($row = $query_unpw->$fetch(PDO::FETCH_ASSOC)) {
$name = $row['company_name'];
}
echo $name;
} else {
echo "Username/Password is invalid";
}
} catch(PDOException $e) {
die($e->getMessage());
}
?>
Now the only thing I've been able to figure out after commenting out different pieces of code is that if I comment out the username and password, like this
//$username = 'abc';
//$password = 'abc';
Then the page loads and just gives me my else echo of "Username/Password is invalid". However I don't think I'm using them wrong and I know they are correct. So the obvious question is am I blind, what's wrong here? The bonus question is, since I will be using _POST for these variables when this works, am I properly sanitizing the user inputs? Still really new to PDO and I want to make sure I'm doing this right. Thanks for the help!
Problem is here:
$query_unpw->$fetch
It must be:
$query_unpw->fetch()
It's a method, so skip that $ sign.
I suggest you to use ini_set('display_errors', "On") while developing.
In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.