Okay. So I made a form. If I put in mysql_real_escape_string on my variable $usrname (yes its spelled right) that was retrieved from the form, it returns my other variable, $verify as false. Take a look:
<html>
<body>
<?php
session_start();
include("mainmenu.php");
$usrname = $_POST['usrname'];
$password = sha1($_POST['password']);
$con = mysql_connect("localhost", "root", "Y0U_C#NT_H#NDLE_THE_TRUTH!");
if(!$con){
die("Unable to establish connection with host. We apologize for any inconvienience.");
}
mysql_select_db("users", $con) or die("Can't connect to database.");
$select = "SELECT * FROM `data` WHERE usrname = '$usrname' and
password = '$password'";
$query = mysql_query($select);
$verify = mysql_num_rows($query);
if($verify==1){
$_SESSION["valid_user"] = $usrname;
header("location:index.php");
}
else{
echo "Wrong username or password. Please check that CAPS LOCK is off.";
echo "<br/>";
echo "Back to login";
}
mysql_close($con);
?>
</body>
If I put the mysql_real_escape_string in either my registration form or login form, it returns $verify as false. What's wrong?
Please make sure "Magic Quotes" is off in the PHP settings. How to disable it is explained here.
Related
Im trying to create a login for my website and i need to store emails, usernames, passwords, ect in a database i have created already using phpMyAdmin. I have gone through article after article and nothing seems to be working. i have my connect.php like this:
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
mysql_connect($hostname, $username, $password) or die("Cannot connect to server");
mysql_select_db($databaseName) or die("Cannot select database");
?>
And my main.php like this:
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
?>
And i have created a simple form in my html like this:
<html>
<head></head>
<body>
<form>
<input type = "submit" action = "main.php" method = "post" value = "Login">
</form>
</body>
</html>
After submitting the form it says cannot connect to server. I am new to php and mysql and i dont understand what each parameter in the mysql_connect is, and i dont know what they do therefore im not sure what im supposed to enter in but everyone i keep reading about seems to be inputing random values? I could use a brief explanation on that, because i am stuck at connecting and cant even get past this point sadly enough. Also i have been reading that mysql_connect is deprecated and isnt valid anymore but i dont understand what im supposed to use as an alternative. I know its mysqli but thats it and im unclear of the syntax.
mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "start<br/>";
try {
$mysqli= new mysqli('localhost', 'myusername', 'mypassword', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
If you need to know how to create users, what the heck the hostname is, how to grant access (often useful after the connect :>), just ask.
Try this code in 'connect.php'
<?php
error_reporting(0);
$con=mysql_connect('localhost','root','');// here 'root' is your username and "" is password
if(!$con)
{
echo 'not connect';die;
}
mysql_select_db('dbname',$con);// here 'dbname' is your database name
?>
And also try following code to include sql connection in your other php file(main.php)
<?php
include 'connect.php';
$sql = "SELECT * FROM myUsers";
$result=mysql_query($sql);
?>
Let me convert it to mysqli for you and maybe that will fix the problem. Also, make sure the username, password, and database name are correct.
Try this code. At very least, it will provide a better error message for debugging.
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
$con = mysqli_connect($hostname, $username, $password, $databaseName) or die(mysqli_error($con));
?>
Main.php
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysqli_query($con,$sql);
?>
The following code redirects to a blank page instead to a .php file.
What have I tried?
I try to use the header() function to redirect the user to another .php file, if the user exists in the MYSQL database, and the password is equal to the one in the MYSQL database.
What is my current code?
<?php
session_start();
$verbindung = mysql_connect( "localhost", "******" , "*****" ); mysql_select_db( "m7_studios_de" );
$username = $_POST["username"];
$passwort = $_POST["password"];
$ergebnis = mysql_query("SELECT * FROM accounts WHERE username = '$username' LIMIT 1");
while($row = mysqli_fetch_object($ergebnis))
if($row->password == $passwort){
$_SESSION["username"] = $username;
header("Location: http://www.m7-studios.de/overview.php");
exit;
}
else{
header( "Location: http://www.m7-studios.de/");
exit;
}
?>
1) Don't output any whitespace before your header() call or it won't work. You are outputting whitespace between the first and second blocks of php
2) Don't mix mysql and mysqli functions - you are using mysqli_fetch_object. In fact don't use mysql functions at all, they are deprecated
3) Use parameterised queries to protect yourself against SQL injection attacks.
It looks like you're mixing mysql_ (in your connection) with mysqli_(fetching rows). You need to use one or the other throughout. I'd suggest mysqli_ since mysql_ is deprecated.
Maybe this should work
Username must be unique + case sensitive
Password should be hashed
Code redirects to the login page with GET error=loginfailed if login fails
<?php
$verbindung = mysql_connect( "localhost", "******" , "*****" );
mysql_select_db( "m7_studios_de" );
$username = $_POST["username"];
$passwort = $_POST["password"];
$abfrage = "SELECT username FROM accounts WHERE username='$username' AND password='$password' LIMIT 1";
$result = mysql_query($abfrage);
if(mysql_num_rows($result)==1) {
$_SESSION["username"] = $username;
header("Location: http://foo.com/logged_in.php");
die();
} else {
header("Location: http://foo.com/index?error=loginfailed");
die();
}
?>
I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.
I'm trying to get my config.php file to work but everytime i use it with my login.php it just gives me a white page rather than continuing through my login.php file towards my members.php page. I put my connection info into my login.php script and it works properly listed below is what i been trying to do.
config.php
<?php
$con = mysql_connect("mysql","DBUSER","DBPASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DBNAME", $con);
/* WHAT I ORIGINALLY WANTED TO USE
$localhost = "mysql";
$dbuser = "DBUSER";
$dbpass = "DBPASS";
$dbname = "DBNAME";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
*/
?>
login.php
<?php
// I ALSO USED includes"config.php";
require("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM member WHERE username = '$username' AND password = '$password'");
$data = mysql_fetch_assoc($query);
if(mysql_num_rows($query)){
session_start();
$_SESSION['username'] = $data['username'];
header("Location: members.php");
exit;
}
header("Location: index.php");
?>
I'm new to PHP so don't laugh at my code please thanks for the help!
On top of your code turn on errors:
ini_set("display_errors","On");
and make sure you can see your mysql errors:
$query = mysql_query(...) or die("Error: ".mysql_error());
And one last thing: although mysql_* functions are being deprecated, if you use them always escape your data before you use it in your query; you can be victim of SQL injection.
try to use:
include "config.php";
it should be include not includes
I made a custom login script, and it works just fine. However, after it redirects to the homepage, the $_SESSION['username'] value is changed to 'root', no matter what value it had before hand. which 'root' is the username for my database login.
I have to type all of this in by hand, so it might have an obvious error or two-
main_login.php (php include_once on sidebar.php which is included on every page)
<?php
if(!isset ($_SESSION["username"])){
?>
<!-- Simple login form action="checklogin.php" method="post"-->
<?php
}else{
?>
<!-- Table to display welcome user, and logout link -->
checklogin.php:
session_start();
$db_name = "database";
$tbl_name = "users";
mysql_connect("localhost","root","password") or die("Cannot connect to SQL server");
mysql_select_db("$db_name")or die("Cannot select database.");
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$password = md5($password);
$sql = "SELECT * FROM $tbl_name WHERE username = '$username' and password = '$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}
else{
echo "<script type='text/javascript'>\n";
echo "setTimeout('redirect();',2000);\n";
echo "function redirect(){\n";
echo "window.location = 'index.php';\n";
echo "}\n";
echo "</script>\n";
echo "Wrong Username or Password";
login_success.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:index.php");
}else{
session_regenerate_id();
}
// Apply permissions - problem existed before all of this code
mysql_connect("localhost","root","password") or die("Cannot connect to database.");
mysql_select_db("database") or die("Cannot select database.");
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_num_rows($result);
mysql_close();
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
?>
<html>
<head>
<script type="text/javascripnt">
setTimeout("redirect();",4000);
function redirect(){
window.location = "index.php";
}
</script>
</head>
<body>
Login Successful.
<?php echo "Welcome ".$_SESSION["username"].".";
var_dump($_SESSION); // var_dump reveals that $_SESSION['username'] is still the login name.
?>
</body>
</html>
Once it goes through that whole process, everything is good. However, when it redirects to index.php, $_SESSION['username'] is now 'root'.
I'm asking to see if anyone has any idea why that might be happening (So I can understand the problem and prevent it in the future), and a fix to implement.
Thanks everyone.
The answer is very simple:
There is some code in your application which changes $_SESSION['username'] value to 'root'.
you have to investigate your code and find that place. Not a big deal
this part seems weird:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_num_rows($result);
mysql_close();
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
try this:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($result);
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
msql_close();
Why are you setting the $_SESSION['username'] variable again on login_success.php You're setting the variables on check_login.php, correct?
Here is what I would do
On login_success.php print out your session variables to see whats going on. I can almost gaurantee something is happening with your sql query. Set a condition to make sure you're actually getting results.
print_r($_SESSION);
if(!$_SESSION['username']) die('no session user name');
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($result);
if(mysql_num_rows($result) == 1){
$_SESSION['username'] = mysql_result($result,0,'username'); //why do you need this?
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
mysql_close();
}
else die('no user found');
Also on your checklogin page change the if statement to look for an actual variable in $_SESSION['username'] not just if it is set, I try to stay away from isset().
For the love of god don't store plain text passwords, it doesn't cost anything to implement a secure password hashing scheme. Its super easy to leverage php's crypt() function, also check this out for an open source secure method. http://www.openwall.com/phpass/
Well,
Your comment sense is probably right, you are setting it to root without realizing it. I just realized, after 2 hours of troubleshooting, that's what I was doing!
No matter what I tried, $_SESSION['username'] was changing from a real username to 'root'.
I finally realized that $_SESSION['username'] was NOT actually changing anywhere, but $username was. Here is why:
<?php
if(!empty($_SESSION['username'])){
$username = $_SESSION['username'];
require_once '../includes/connect_to_db.php';
echo $_SESSION['username']. ' is correct but '. $username. 'is not.';
}
?>
Finally we see in the required file connect_to_db.php:
<?php
$host="localhost"; // Host name
$username="root"; // mysql username
$password=""; // mysql password
$db_name="BH_web_DB"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect: ". mysql_error());
mysql_select_db("$db_name")or die("cannot select DB");
?>
Simple fix:
$db_username="root"; // mysql username
So I was in fact setting it too root =) hope this helps another.
I was having the same issue, turns out I didn't session start on the page where it displays 'root'.
if (!session_id()) session_start();
This helped!