I'm having an issue with a form I have created (Test purposes only, I am aware it's vulnerable to SQL Injection)
Basically, the form does not insert into the DB, yet it seems to be returning true on the script.
The code is as follows:
form.php
<form action="create.php" method="post">
<p>Username: <input type="text" name="username" />
</p>
<p>Password: <input type="password" name="password" />
</p>
<p><input type="submit" value="Create" name= "cre" />
</p>
</form>
create.php
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['cre'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if($registerquery = true)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
?>
I get the success message, but as I stated, the values do not get inserted into the DB.
Any help would be good.
This defines a query, but does NOT run it:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
The this is NOT "testing" for success. It's simply seeing the variable to true:
if($registerquery = true)
= is assignment, == is for equality testing.
You have to query the database. Try this:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if ($mysqli->query($registerquery))
{
// success.
}
else
{
// failed.
}
Here is the documentation: http://php.net/manual/en/mysqli.query.php
You missed the step where you actually hand the SQL query to the database.
$mysqli->query($registerquery);
has to be run before it will be inserted.
You can also change your if statement to the following
if ($mysqli->query($registerquery))
Also, you're currently using a single =, which is setting $registerquery instead of checking its value.
All you are doing here:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if($registerquery = true)
is setting a string and then later setting the string to true. This is always going to return true. There are two problems with this:
You need to execute the SQL statement that you have stored in the string for anything to happen in the database.
You are not really checking the return value ("=="), but rather using "=", which simply sets the variable. A very common mistake.
Additionally, you should probably no longer use the mysqli built in functions, since they will soon be deprecated. I would recommend switching to PDO before moving any further.
Formally, You should do something like this:
if(isset($_POST['cre'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
$stmt=$mysqli->prepare($registerquery);
if($stmt->execute())
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
$stmt->close();
}
Also, you could call only mysqli_query
if($mysqli->query($registerquery)){
....
}
It would be enough. The first call is better if you need to bind parameters and make several calls to the same query with different values.
Regards.-
Related
I'm having a bit of trouble with register information.
It's supposed to go to a database called "mon" and to a table called "user".This table contains the information "'id','name',and 'pass'".The 'id' is based off of an auto increment system,so doesn't need to be defined in the register page.
No errors are reported,just a reload of the page.But,when visiting the table using phpMyAdmin,it shows that a new row wasn't created.I need help on this because I am fairly new to PHP and don't know much of the kinks of it.
Code:
Pastebin because stackoverflow is acting weird with my code even though I spaced it.
register.php:
<?php
require_once 'connect.php';
if(!empty($_POST)) {
if(isset($_POST['username'], $_POST['password'], $_POST['desc'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password)) {
$insert = $db->prepare("INSERT INTO 'user' ('name', 'pass') VALUES (?, ?)");
$insert->bind_param('ss', $username, $password);
}
}
}
?>
<html>
<head>
<?php
require_once 'style.php';
?>
<title>si | Registering an Account</title>
</head>
<body>
<?php
require_once 'header.php';
?>
<div id="page">
<h2>Register an Account on Si</h2>
<form action="" method="post">
<input type="text" name="username" placeholder="Username" autocomplete="off">
<input type="password" name="password" placeholder="Password" autocomplete="off">
<button>Register</button>
</form>
</div>
</body>
</html>
connect.php:
<?php
$db = new mysqli('127.0.0.1', 'root', '');
if($db->connect_errno) {
echo "<p id='gotem'>Something has gone wrong.Tell J to fix it.</p>";
}
?>
Any help on this,the creation of a session that marks login,and the redirecting to the index page with the session on is very appreciated.
In conjunction with the other answers given, you are using regular quotes around your table and columns, which are invalid identifier qualifiers.
("INSERT INTO 'user' ('name', 'pass')
^ ^ ^ ^ ^ ^
Which should either be removed
("INSERT INTO user (name, pass)
or using ticks which resemble a quote, but is in fact NOT a quote; those are two different animals altogether.
("INSERT INTO `user` (`name`, `pass`)
Reference on identifier qualifiers for MySQL:
http://dev.mysql.com/doc/en/identifier-qualifiers.html
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or crypt, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
First of all you forgot to add your database name and password in your mysqli instance
<?php
$db = new mysqli('127.0.0.1', 'root', 'your_password_for_the_user_root','yout_database_name');
if($db->connect_errno) {
echo "<p id='gotem'>Something has gone wrong.Tell J to fix it.</p>";
}
?>
Then in your register.php file you have added a post index which will not be set($_POST['desc']), that's why your code inside your if statement will never be execute since your form does not contain an input name desc.I think its better remove it and please do not forget to execute your prepared statement. The code might be like this.
UPDATED CHANGE ' TO `
if(!empty($_POST)) {
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password)) {
$insert = $db->prepare("INSERT INTO `user` (`name`, `pass`) VALUES (?, ?)");
$insert->bind_param('ss', $username, $password);
if (!$insert->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
}
}
Adding an attribute type of your button might also be helpful
<form action="" method="post">
<input type="text" name="username" placeholder="Username" autocomplete="off">
<input type="password" name="password" placeholder="Password" autocomplete="off">
<button type="submit">Register</button>
</form>
in your file , line 6
if(isset($_POST['username'], $_POST['password'], $_POST['desc'])) {
you dont post $_POST['desc'] check this.
NOTE: Better way is , have else for all of your if , to see what happend
EDIT:
use $insert->execute();
after
$insert->bind_param('ss', $username, $password);
Line no. 6
I think you have added extra parameter 'desc' to isset statement which is not used anywhere.
Change this line
if(isset($_POST['username'], $_POST['password'], $_POST['desc'])) {
To following
if(isset($_POST['username'], $_POST['password'])) {
Add following code.
You have bind the parameter to to sql query but not yet executed.
Add the following code just after $insert->bind_param('ss', $username, $password);
$insert->execute();
Creating Session
To create session you need to store session value in session variable. You can do this by storing newly registred user id in session variable. Add following code just after $insert->execute();
$userid = mysqli_insert_id($db); // get newly registred userid
$_SESSION['userid'] = $userid // store the registred userid in session.
Redirect to Index Page
Redirection of page done using header function in php
Add following code.
header("Location: index.php");
On Index page
To get access to session and session variable. Add following code at very first line.
session_start();
$userid = $_SESSION['userid'];
if(isset($userid) && !empty($userid)) {
echo "User is logged In using user id:".$userid;
} else {
echo "User is not logged In"
}
Ok, this is just for a school project so it doesn't need incredible security so i just need help with this signup feature for an sql database:
<h1>Signup:</h1><br><form method="post">Username: <input type="text" name="username"><br>Password: <input type="password" name="password"><br>Confirm Password: <input type="password" name="cpassword"><br><input type="submit"></form>
<?php
$user = $_POST['username'];
$pass = crypt($_POST['password'], '$1a');
$cpass = crypt($_POST['cpassword'], '$1a');
if($pass == $cpass) {
$query = "INSERT INTO users (uName, pWord) VALUES ('$user', '$pass')";
}
else
echo "<script type='text/javascript'>alert('Password is different');</script>";
?>
The problem i actually have is i am doing pretty much the same thing with the login and the $_POST method in there is stopping me from being able to do it here, how do i refer to a specific $_POST method?
You forgot to actually execute the query. You're just assigning a string to a variable.
( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.
I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.
I am trying to make a form using html and php to update mysql database. the database updates (autoincrements) the keys, but it does not add any of the strings to the values. i have searched people with similar problems but because their codes are different than mine I cannot understand it (i am a noob with php and mysql) I think my problem is in the way that i use the html to get the values but I could be wrong
<form action=submitform.php method=GET>
Name:<input type="text" name="cuName" size=20 maxlength=20><br>
Password:<input type="password" name="password" size=20 maxlength=45><br>
Account:<input type="text" name="account" size=20 maxlength=45><br>
Phone:<input type="tel" name="phone" size=10 maxlength=10><br>
Email:<input type="text" name="email" size=20 maxlength=45><br>
<input type=submit>
</form>
and my php is
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')");
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
thanks in advance for any help
Your code is relying on REGISTER_GLOBALS to be turned on; it is usually turned off for security reasons.
You should replace $cuName with $_GET['cuName'] to get the values that are sent from the form.
Additionally, you should escape any value that is going to the database otherwise you may be exposing yourself to an SQL injection vulnerability.
Cleaning up your code for both these scenarios, results in something like this:
<?php
if (!mysql_connect(localhost, myUsername, "myPassword")) {
print 'There was an error connecting to the database'.mysql_error();
exit();
}
if (!mysql_select_db(myDatabaseName)) {
print 'Could not select db. The error was: '.mysql_error();
exit();
}
$query = "INSERT INTO Customer (`cuName`, `password`, `account`,`phone`,`email`)";
$query .= "VALUES (";
$query .= "'".mysql_real_escape_string($_GET['cuName'])."','";
$query .= mysql_real_escape_string($_GET['password'])."','";
$query .= mysql_real_escape_string($_GET['phone'])."','";
$query .= mysql_real_escape_string($_GET['email'])."'";
if (!mysql_query($query)) {
print 'There was an error inserting '.$query.'. Error was '.mysql_error();
} else {
echo $_GET['cuName']." thank you for reserving!";
}
print $_GET['cuName'];
?>
I also added some error checking. You should always check results of functions that rely on external systems (such as databases) because you never know what is the status of the database (it could be down, not working, etc.) So you should always check and print any error messages.
You don't define any of your GET values anywhere. $cuName, etc are not defined.
Each value needs to be associated to the $_GET. IE,
$cuName = $_GET['cuName']
But you also need to make sure you don't insert data that hasn't been cleaned to prevent SQL injection. An example of this is:
$cuName = mysql_real_escape_string($_GET['cuName']);
So, try this:
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
//Define Variables
$cuName = mysql_real_escape_string($_GET['cuName']);
$password = mysql_real_escape_string($_GET['password']);
$account = mysql_real_escape_string($_GET['account']);
$phone = mysql_real_escape_string($_GET['phone']);
$email = mysql_real_escape_string($_GET['email']);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')") or die (mysql_error());
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
Better to use:
$cuname = $_GET['cuname'];
like this....
Because your form method is on "GET",and my advise is to POST data than GET.