I have a login.html in which the form is defined as follows:
<form method="post" action= "do_authorize.php" name="lform">
<span class="style1">First Initial Plus Last Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
My do_authorize is as follows:
<?php
session_start();
require('../databaseConnectionFileFolder/dbconnection.php');
$user = $_POST["user"];
var_dump($user);
$_SESSION['username']=$user;
var_dump($user);
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
var_dump($sql);
$result=#mysql_query($sql,$connection) or die("couldn't execute query");
$num=mysql_numrows($result);
if ($num != 0) {
/*$cookie_name="$user";
$cookie_value="ok";
$cookie_expire=time()+86400;
$cookie_domain=".columbia.edu";
setcookie($cookie_name, $cookie_value, $cookie_expire, "/", $cookie_domain, 0);
*/
print "<script>";
print "self.location='somethingelse.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
My dbconnection.php file is as follows:
<?php
$db_server = "localhost";
$db_name = "DailyExerciseDB";
$db_user = "abc5"; //the database username
//$db_password = "123"; // the database user pasword
$connection=#mysql_connect($db_server,$db_user) or die("Could Not Connect to the Database : ". mysql_error());
var_dump($connection);
$db=#mysql_select_db($db_name, $connection) or die("Could Not Select the Database". mysqli_connect_error());
//var_dump($db);
?>
My Questions:
1) I keep on getting Could Not Select the Database, why does the warning/error message corresponding to . mysqli_connect_error() doesn't get printed on the browser?
2) I have manually entered the user with username abc5 in the database and still it's not able to connect.Does anyone know why?
3) Even if I don't enter anything in the login.html and press login button, the following files gets executed, how can I take user entered into account while verifying with database? I believe since its hardcoded right now abc5, all files are getting executed.
4) var_dump($connection); prints resource(4, mysql link)
mysql_connect() has a third parameter which I'm not seeing you use: the password. Consider the following line:
mysql_connect($db_server, $db_username, $db_password);
Also, you should probably be using mysqli extension instead of the mysql extension (mysql is deprecated in PHP 5.5.0).
I also see you're mixing the mysql and mysqli functions in your code. This is the reason why mysqli_connect_error() shows nothing.
Related
I will describe my problem in two parts (previous problem and current problem).
Previous Problem:
Initially, on page3.php, I wasn't able to retrieve the username using the session variable and hiding //require('../myDBFolder/db.php'); solved the problem and I was able to see the username on that page.
Current Problem:
Since, I have commented out the line //require('../myDBFolder/db.php');, I am not able to access the other variables defined in db.php like $connection variable and hence I am trying to figure out how to make sure I have $connection variable available in page3.php.
A Quick explanation of the working of files is in the following order:
User submits username from page1.html, page2.php does the authorization work with db.php as required file and upon successful authorization, it directs the user to page3.php.
Please consider my files below:
page1.html
<form method="post" action= "page2.php" name="lform">
<span class="style1">User Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
db.php
<?php
session_start();
$user = $_POST["user"];
$_SESSION['username']=$user;
$db_server = "localhost";
$db_name = "PracticeDB";
$db_user = $user;
$table_name_data = "collegestudents";
$connection = mysqli_connect($db_server,$db_user,$db_password) or trigger_error("Could Not Connect to the Database : ". mysqli_connect_error(), E_USER_ERROR);
$db = mysqli_select_db($connection , $db_name) or trigger_error("Could Not Select the Database : " . $db_name . ':' .mysqli_error($connection));
?>
page2.php
<?php
session_start();
require('../myDBFolder/db.php');
$user = $_POST["user"];
$_SESSION['username'] = $user;
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
$result=mysqli_query($connection,$sql) or trigger_error("Couldn't Execute Query in page2.php: ". mysqli_error($sql));
$num = mysqli_num_rows($result);
if ($num != 0) {
print "<script>";
print "self.location='page3.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
page3.php
<?php
session_start();
//require('../myDBFolder/db.php');
$user = $_SESSION['username'];
$sql = "SELECT * FROM $table_name_data WHERE username = '$user'";
$result = mysqli_query($connection,$sql) or trigger_error("Could Not Execute the Query ! : ". mysqli_error($connection));
?>
Troubleshooting Steps:
1) I have tried to include require('../myDBFolder/db.php'); in page3.php file and it solves the problem of $connection parameter but I don't see username coming onto that page via session for some reason and also by including //require('../myDBFolder/db.php'); in page3.php I will be making db connection twice as I have already done that in page2.php and haven't closed it.
2) Another thing, I was looking at some of the threads discussed before like this one, it seems like storing $connection in a session variable is not a good idea.
Just to point in a direction:
Change this
$user = $_POST["user"];
$_SESSION['username'] = $user;
to
if(isset($_POST["user"])){
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
So, only update the SESSION if POST is given.
By the way, it is not good practise to give each user an db user account.
Your SQL check if a user is in the database, but your connectin also uses this username!? Rething that..
If you only use one db_user you can move the session username setting stuff completly from the db.php and move it to a better place (e.g. session.php).
the error of you dont see the username if you require db.php is :
in your db.php first thing to do is to put the username in the session so when you call it from the page3 you the code put blank in the session
this code
$user = $_POST["user"];
$_SESSION['username'] = $user;
There is two solution for that :
1 - put connection in one file and the session put in the other file
$user = $_POST["user"];
$_SESSION['username'] = $user;
in different file of connection
2 - the second is you put if condition before this code like this
if(!empty($_POST["user"])) {
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
try it .
EDIT: I found the problem. The connection problem was located on the other page I was redirecting to, which had the wrong credentials, I'm an idiot.
This is my first time asking a quesiton in here, so bear with me.
I wanted to test to see whether or not I am able to insert data into my MySQL database through my .php page. Although I seemingly can't connect to my database, even though the username, password and so on are all correct. I use the same credentials, when I log on to the local instance trough MySQL Workbench.
The error i get in my browser says this:
Connection failed: Access denied for user 'root'#'localhost' (using password: YES)
Also this is my first time coding php, so the code is probably littered with errors, feel free to point them out.
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function prepareInput($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "praktikdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//---------------------------------------
$username1 = $password1 = "";
$errUsername = $errPassword = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["username"])){
$errUsername = "Username is required";
}
else{
$username1 = prepareInput($_POST["username"]);
}
if(empty($_POST["password"])){
$errPassword = "Password is required";
}
else{
$password1 = prepareInput($_POST["password"]);
}
$sql = "INSERT INTO users (username, password) VALUES('$username1', '$password1')";
$result = $conn->query($sql);
if(!$result) die("Something went wrong". $conn->error);
$result->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Registration</title>
</head>
<body>
<form action="login.php" method="post">
Username: <input type="text" name="username">
<span class="error"> <?php echo $errUsername?></span>
<br>
Password: <input type="text" name="password">
<span class="error"> <?php echo $errPassword?></span>
<br>
<input type="submit" name="btnRegister" name="Register"/>
</form>
</body>
</html>
Your code is giving you a credentials problem (detected by your "Check connection" piece of your code), and that is derived of the users configuration in your MySQL Workbench. You need to configure the user you will use for your PHP connection to MySQL, along with the password, and the server the user connecting will be limited to (in this case is the localhost), and the privileges your user will have.
Also, and this is just for connecting to your database (for now consider that you won't execute a SQL query in your code), you can check if the connection it's ok with just your username, the password and the server name.
<?php
/* $servername, $username and $password goes here */
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error) {
die("Connection failed:" $conn->connect_error);
}
echo "Connection successful";
?>
I am quite new to PHP, and still have long way to go. Probably, it is a logic failure or maybe I just dont know how exactly PHP works.
Anyway, The code I submited is from my admin control panel. I am trying to make a page to connect to db than show all db names and select one of them from radio buttons. And when pressed submit again to show tables.After showing table the next step will be to edit,add update them etc. I am not there yet. Because I could not make mysql_select_db to work. It gives error.
The error is;
Notice: Undefined variable: connect in /public_html/php/insert_delete_update_amend/mydata03.php on line 94
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /public_html/php/insert_delete_update_amend/mydata03.php on line 94
Could not connect to db
Any help will be much appreciated.
P.S.: Also when the first form is submitted,first form disappears and second one appears and so on.
<?php
// form variables
$DisplayDBinfoForm = true;
$DisplayDBform = false;
if (isset($_POST['db_info_submit'])) { //when user presses db info submit button
//select which form to hide or appear
$DisplayDBinfoForm = false;
$DisplayDBform = true;
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
echo "<p><b>connected successfully</b></p>\n";
}
if($DisplayDBinfoForm) {
?>
<form name="dbinfo" method="POST" action="mydata03.php" onsubmit="return validateForm();">
Host Name: <input type="text" name="db_name" /><br />
<br />
DB User Name <input type="text" name="db_user_name" /><br />
<br />
DB User Password: <input type="text" name="db_user_password" /><br />
<br />
<input type="submit" name="db_info_submit"value="Login"><br />
</form>
<?php
}
if($DisplayDBform) {
?>
<form name="delete_table" id="delete_table" action="mydata03.php" method="post">
<table width="30%" border="1">
<tbody>
<?php
$query = "SHOW DATABASES";
$resultSet = mysql_query($query);
while($database = mysql_fetch_array($resultSet)) { // go through each row that was returned in $result
$dbname = $database[0];
echo "<tr><th>Database Name</th>
<th>Select</th>
</tr>
<tr>
<td>$dbname</td>
<td><input name=\"radDB\" id=\"radDB\" type=\"radio\" value=\"$dbname\"</td>
</tr>\n";
}
?>
</tbody>
</table>
<p>
<input name="btnSelectDB" type="submit" value="Select" />
</form>
</p>
<?php
}
if(isset($_POST['btnSelectDB'])) {
$DisplayDBinfoForm = false; // hide form
$DisplayDBform = false; // hide form
$db_name = $_REQUEST["radDB"]; // the db na,e
echo "The " . $db_name . " is selected\n";
$select_db = mysql_select_db($db_name,$connect);
if(!$select_db) die("Could not connect to db". mysql_error());
echo "<b>connected successfully to db</b>";
}
?>
First off, don't use mysql_* functions. That time has passed. Instead, use mysqli_* or PDO.
With that said, it appears that the initial connection to the database server complete fine, as your code doesn't crap out on you at:
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
Although at the later stage, when trying to connect to an actual database: $select_db = mysql_select_db($db_name,$connect); it does.
This leaves me to believe that the variable in which you set the database name $db_name = $_REQUEST["radDB"]; is not pulling the data in correctly.
try
$connect = mysql_connect($hostname,$db_user_name,$db_user_password) or die("Could not connect");
if( $connect)
echo "<p><b>connected successfully</b></p>\n";
}
also check that the
if( isset($_POST['db_name'] ) && isset($_POST['db_user_name']) && isset($_POST['db_user_password']){
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
}
Use of this extension(MYSQL_*) is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used
Good Read
PDO Tutorial for MySQL Developers
The problem you have is that the database is only opened ($connect=) if you have done a post with 'db_info_submit', but you can still run line 94 if you have posted 'btnSelectDB'.
Simplest solution is to open the database outside the if ($_POST) statement at the top, in case it's needed below. Or wrap in either of the conditions required to open it (code shown below)
<?php
// form variables
$DisplayDBinfoForm = true;
$DisplayDBform = false;
if (isset($_POST['db_info_submit']) || isset($_POST['btnSelectDB'])) {
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
echo "<p><b>connected successfully</b></p>\n";
}
}
if (isset($_POST['db_info_submit'])) { //when user presses db info submit button
//select which form to hide or appear
$DisplayDBinfoForm = false;
$DisplayDBform = true;
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
}
if($DisplayDBinfoForm) {
?>
....
<?php
}
if(isset($_POST['btnSelectDB'])) {
$DisplayDBinfoForm = false; // hide form
$DisplayDBform = false; // hide form
$db_name = $_REQUEST["radDB"]; // the db na,e
echo "The " . $db_name . " is selected\n";
$select_db = mysql_select_db($db_name,$connect);
if(!$select_db) die("Could not connect to db". mysql_error());
echo "<b>connected successfully to db</b>";
}
?>
This isn't a direct answer, but it's the answer that's goign to help you the most.
If you have a function in your script that begins "myslq_" (except for 1 - mysql_real_esacape_string) then you're following an old example and are using code that is going to be depreciated. As you're just learning PHP and MySQL, get into the habits of using the more modern functions, either mysqli_ or PDO
I am trying something very basic yet it is failing to work for some reason! well basically I am trying to create a new username and password for my site. It is only for testing. When I submit the request, I get this:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'santoshs'#'localhost' (using password: NO) in /home/khali197/public_html/test/enroll.php on line 27
I have no idea who is santoshs that is showing here # localhost. From home it shows someone different. What could it be?
I've got the following code to try achieve my objective...all pretty simple really:
<?php
class ServerConnection{
function connect(){
$mysqli = new mysqli("localhost", "dsdssd_admin", "sddsdsd",
"khadsdsli197_dsd");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" .
$mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
//echo $mysqli->host_info . "\n";
}
}
?>
the register.php form:
<form name="register" action="enroll.php" method="post">
Username: <input type="text" name="username" maxlength="30" />
Password: <input type="password" name="pass1" />
Password Again: <input type="password" name="pass2" />
<input type="submit" value="Register" />
</form>
and the form to handle that, i.e. enroll.php:
<?php
include("ServerConnection.php");
//retrieve our data from POST
$username = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 != $pass2)
header('Location: register_form.php');
if(strlen($username) > 30)
header('Location: register_form.php');
$hash = hash('sha256', $pass1);
//creates a 3 character sequence
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$connection = new ServerConnection();
$connection->connect();
$username = mysql_real_escape_string($username);
$query = "INSERT INTO users ( username, password, salt )
VALUES ( '$username' , '$hash' , '$salt' );";
mysql_query($query);
mysql_close();
header('Location: index.php');
?>
Any help here would be highly appreciated! Thanks in advance
MySQL is not MySQLi. If you're using the MySQLi extension, don't use the mysql_real_escape_string function. They're two entirely different database drivers.
When you call the mysql_real_escape_string() function it searches for earlier mysql connection opened, NOT mysqli connection. If it can not find it tries to open a new connection with system login user. If your system username is santoshs then this is the reason.
The solution would be to change the ServerConnection class to use mysql extension or use the mysqli extension in enrole.php
That you're seeing the error when calling mysql_real_escape_string() implies you've not trapping the error at mysql_connect() - so even before considering what the user is, it's evident that the code which is running is not the code you've shown us.
Try adding some error detection at mysql_connect() in ServerConnection.php and check the permissions for the user santoshs
I looked at previos Undefined error questions to see if I could find help for my question, but I can't seem to fix it for my problem.
So when I try to log in a user I get an error that says Undefined index:
No sure why Im getting this message on my login.php page
I have a database and a table called users with data inserted
this is what I use to connect to the database
conn.php
<?php
session_start();
$dbhost = "127.0.0.1"; // my database
$dbname = "fxdme";
$dbuser = "root";
$dbpass = "";
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) or die("MySQL Error: " . mysqli_error("Cant Connect"));
?>
the login script
login.php
<?php include 'template/header.php';?>
<form action="login.php" method="POST">
User Name: <input type="text" name="username" />
Password: <input type="password" name="password"/>
<input class="submit" name="submit" type="submit" value="Log In"/>
</form>
<?php
$result=$mysqli->query('SELECT * FROM users WHERE username = "' .
$_POST['username'] . '" AND password = "' . $_POST['password'] . '"');
//set session user
$row = $result->fetch_assoc();
$_SESSION['user_id'] = $row['id'];
if ($_SESSION['user_id']) {
echo "You are logged in, $session_username. <a href='logout.php'>Log out</a>"; }
else {
echo " cant log in";
}
?>
// Index page
My index page
index.php
//in the template header is where Im calling my conn file
<?php include 'template/header.php'; ?>
<?php
if (isset($_GET['invalid'])) {
echo "<tr><td colspan='2' align='right'>Invalid login.</td></tr>";
}
?>
Im trying to get the error fixed so I'm not worried about sql injections at the moment. I just want to be able to login and and worry about the other stuff later.
You will find that $_POST["username"] will return invalid index if username is not in the post variables.
I usually create a set of variables to hold the my post variables so I can do validation and normalisation of the data first
So before your query statement
$username=(isset($_POST) && isset($_POST["username"]) ? $_POST["username"] : "";
$password=(isset($_POST) && isset($_POST["password"]) ? $_POST["password"] : "";
then use $username and $password in your query. You could event turn the previous statements into a function call passing in the variable name to check.
function getPostVar($name) {
return (isset($_POST) && isset($_POST[$name]) ? $_POST[$name] : "";
}
$username=getPostVar("username");
$password=getPostVar("password");
Obviously your code is ripe for sql injection with at username of ' union select * from users --
There is not anything in your code to make a query string in URL to fetch by $_GET. How can you have an index when you don't have anything ?
For what you said, you must use a header('location:index.php?invalid=1'); if the user can not log in to your system.
Might not be the same issue for you but I had this same error when converting to mysqli and my fetch statement looked the same as yours.
try changing.
$row = $result->fetch_assoc();
to
$row = $result->fetch_array(MYSQLI_ASSOC));