Solution:
I tinkered around with kcdwayne's test (using test.php and register.php) and determined that the issue resided in using the file name "db.php." I renamed it to "datab.php" and it appears to be working wherever it is being used. Interesting. Thank you for your answers!
Original Post:
I have one file - checkuser.php - that is POST'd to from a login form to verify a user's credentials. username and password are given. Through an external file - db.php - I am trying to establish a connection to the MySQL database. The setup:
checkuser.php:
session_start();
error_reporting(E_ALL);
ini_set( 'display_errors','1');
require "db.php";
db.php:
$con = mysqli_connect("server", "user", "pass", "db");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
... later in checkuser.php:
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysqli_query($con, "SELECT * FROM userdata WHERE username='$username' AND password='$password' AND activation='true'");
And thus, here lies my problem:
Notice: Undefined variable: con in /path/to/checkuser.php on line 23
checkuser.php and db.php are in the same folder; the MySQL connection can easily be established if the code in db.php is moved into checkuser.php itself.
What am I doing wrong?
checkuser.php:
<?php
session_start();
error_reporting(E_ALL);
ini_set( 'display_errors','1');
require "db.php";
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
echo "<font color='white'>Please enter ALL of the information! <br />";
include 'login.php';
exit();
}
$password = md5($password);
$sql = mysqli_query($con, "SELECT * FROM userdata WHERE username='$username' AND password='$password' AND activation='true'");
$login_check = mysqli_num_rows($sql);
if($login_check > 0) {
while($row = mysqli_fetch_assoc($sql)) {
... set some $_SESSION variables ...
}
}
?>
db.php:
<?php
$con = mysqli_connect("server", "user", "password", "database");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
If db.php is included/required on checkuser.php, the variable should be there, provided that:
$con is not scoped inside of a block where checkuser.php does not have access to.
The place you're requesting it can receive it (i.e., it's passed as an argument into the function or it's not wrapped in a scope that does not have access to $con.
Try this:
make a file called test.php, and in it, place
$var = 'this is my test var';
then make a file in the same folder called register.php, and put only
require('test.php');
echo $var;
If it works, your problem's either in scope or it just isn't loading the db.php.
Related
I'm making a web app where the user logs in and is able to access the profile and take a quiz. I've got most of it working the only problem is, is that it seems to 'forget' which user is signed in. By this I mean I can't access any of the variables from when the user logs in session.
For example, I have a $_SESSION['username'] = $username; which returns unidentified variable when I try to use the variable $username in a different session or page. Also, I haven't terminated my login session.
Right now I'm trying to store the results of my quiz to a database along with the user's username but it only stores the score and not the username.
Below is my code.
authenticate.php file (This contains the variables regarding usernames)
<?php
session_start();
// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $con->prepare('SELECT username, password FROM users WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the st_account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($username, $password);
$stmt->fetch();
// st_account exists, now we verify the password.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['username'] = $username;
include_once 'homepage.php';
// echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect username and/or password!';
}
} else {
echo 'Incorrect username and/or password!';
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
?>
final.php file
<php include "process.php"?>
lines 24 - 44
<main>
<div class="container">
<h2>You are Done!</h2>
<p>Congrats! You have completed the test</p>
<p>Final score: <?php echo $_SESSION['score']; ?></p>
<?php echo $score; ?>
Take Test Again
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$query = "INSERT INTO `results`(`username`,`score`) VALUES ($username, $score)";
mysqli_query($con, $query);
?>
<?php session_destroy(); ?>
</div>
I don't know if it's necessary to include process.php but I thought it might be helpful to show where the $score variable comes from.
process.php file (this isn't the whole file.)
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
//Check to see if score is set_error_handler
if (!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
}
$score = $_SESSION['score'];
}
?>
Sorry if I've made a really simple stupid error, don't hate me, I'm still pretty bad at coding.
Put your session_start(); at the very top of your code, for example, at the very top of your final.php file rather than in your process.php file.
E.g.;
<?php
session_start();
include 'database.php';
?>
A simple solution that you can try
session_start();
We have to add this on the top of php file, or else php throw exceptions like 'headers already sent' or 'can’t start the session' etc.
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);
?>
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!
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.