SQL signup feature $_POST method being annoying - php

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.

Related

PHP form not inserting values into DB

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.-

Entries to the database automatically after reload the web site

( 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.

Error trying to UPDATE php/mysql code for changing to a new password

As described in the title, I am running into an SQL injection error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
How do I fix this? Provided below is my php code and html code
PHP:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] = mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM members WHERE username='{$_SESSION['username']}' AND pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1'])."' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
else $err[]='Wrong Password To Start With!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML:
<form action="" method="post">
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1" value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1" id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register" style="margin-left: 382px;" />
</form>
I have it working where a user is able to change/update their password, however, when they click the Change button on the form, they are directed to that error message I posted above, and if they click the refresh button, only then they are redirected back to their profile and the changes have been made. So my main question at hand is, how do I get this to fully work without that mysql error message? Any help would be much appreciated!
A few things wrong here, more than can be put in a comment. I'm sorry, I can't see exactly what your error is, but if you follow point #1, it'll go away.
Don't use the mysql library. It is deprecated, and has been removed (finally!) in PHP 5.5. It is only working for you at the moment, because your version of PHP is out of date. You should either be using PDO or MySQLi. Check out this article for information on PDO: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
Don't put any variable that's not generated in the script you're looking at into your query, this includes SESSION variables. You just need one flaw in your application, and the user can inject data into the SESSION. Treat every variable as dirty. If you know that it isn't - 100% for certain - then treat it as dirty. If you use prepared statements with PDO or MySQLi, this isn't a problem.
You should reference users by their ID, not username. Much faster and safer.
Never ever ever ever store passwords raw or simply encrypted (like with plain md5()) in the database. At the very least, you can encrypt with something like: crypt($password, '$2a$07$sillystring' . sha1($password) . '$') and verify by recrpyting the password and see if it matches. That's a very basic, more secure way of doing it. There are many articles written on password salting that go more in depth and are worth checking out.
Except for what Connor said, you have a serious problem here:
if($row['username'])
{
$querynewpass =
mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
The first inner line already performs the mysql_query and returns a resource, which is assigned to $querynewpass.
You're resending the result (a resource) to another query, as if it was a string containing the SQL command you want to perform.
This is the function's specification:
resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
This is the correct usage of mysql_query (which is deprecated as people mentioned):
if($row['username'])
{
$querynewpass =
"UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'";
$result = mysql_query($querynewpass) or die(mysql_error());
}
This code snippet could help to you
$pass1 = md5(mysql_real_escape_string($_POST['password1']));
$newpass = md5(mysql_real_escape_string($_POST['passwordnew1']));
$username = mysql_real_escape_string($_SESSION['username'])
$query = "SELECT id,username FROM members WHERE username = '$username' AND pass = '$pass1'";
$result = mysql_query($query); //that could also use , mysql_query($query,$yourconnection);
if(mysql_num_rows($result)>0)
{
$updatequery = "UPDATE members SET pass='$newpass' WHERE username='$username'";
$updateresult = mysql_query($updatequery) or die(mysql_error());
}
Please note that mysql library is deprecated in after php ver 5.5.0

can't update values in mysql using html and php

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.

PHP, question about searching and updating a record

I have a question, I am new to PHP and I have been working on some exercises. The one I am currently working on is to create a simple form that will search a database (first name, last name). The returned results should then be populated into another form. This way, if I want to update the record, all I have to do is change the value of the populated form and hit Update. I have create the database no problem.
The following is the code. (Please don't laugh, I'm very new...I am sure there are much more efficient ways of doing this, but I'm just playing around right now)
Here is the form:
<form action="" method="post">
<strong>Search for name</strong><br>
<label for="fname">First Name</label>
<input type="text" name="fname">
<label for="lname">Last Name</label>
<input type="text" name="lname">
<input type="submit" name="submit" value="Search">
</form>
And here is the PHP:
if( isset( $_POST['submit'] ) ){
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
if ( $first_name == NULL || $last_name == NULL ) {
echo "please enter search record";
}
else {
$query = "SELECT first_name, last_name FROM formdata WHERE first_name LIKE '%$first_name%' OR last_name LIKE '%$last_name%'";
$result = mysqli_query( $conn, $query );
$result_array = mysqli_fetch_row( $result );
$fname_value = $result_array[0];
$lname_value = $result_array[1];
echo "
<form action='' method='post'>\n
<label for='fname_u'>First Name</label>\n
<input type='text' name='fname_u' value='$fname_value'>\n
<label for='lname_u'>Last Name</label>\n
<input type='text' name='lname_u' value='$lname_value'>\n
<input type='submit' name='update' value='Update'>\n
</form>";
}
}
if( isset( $_POST['update'] ) ) {
$first_name_u = ( $_POST['fname_u'] );
$last_name_u = ( $_POST['lname_u'] );
$query_update = "UPDATE formdata SET first_name = '$first_name_u', last_name = '$last_name_u' WHERE first_name = '$fname_value';";
echo $query_update; // this is just for testing
}
This code seems to work and do what I want, all the way up to when I submit the updated information. I can't figure out how to carry over the value of the $fname_value variable to the if( isset( $_POST['update'] ) ) conditional. I am thinking I can't because they are two different POSTS? I really don't know...I just need to find a way to get value of the retrieved form data and use for the WHERE clause.
Again, I'm very new and just getting my feet wet with this kind of stuff ... Any help would be great
Thanks
I think you have a typo in your code. Your POST data is saved to the variable $first_name, but when you query SQL you are using $first_name_r instead of $first_name.
I'm thinking the typo is the answer, but I have to point out one deadly mistake you've made, and that is that you're piping user-supplied input directly into an SQL query. This opens your code to a slew of malicious attacks called SQL injection attacks. I'm not trying to be preachy, but it's very important that you read and understand that article, especially the part about Mitigation at the bottom.
I would suggest you use something like this instead:
$query = 'SELECT first_name, last_name '.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = mysqli_prepare($dbh, $query);
mysqli_stmt_bind_param($sth, "s", '%'.$first_name.'%');
mysqli_stmt_bind_param($sth, "s", '%'.$last_name.'%');
$result = mysqli_execute($sth);
I know it's a bit longer and more complicated, but trust me, it will save you a world of headache. The sooner you learn about this and get it deeply ingrained in your psyche that you can never, ever, ever write a query that passes unsanitized input straight to the database, the happier we all will be (and the longer you will get to keep your job eventually. ;).
Sorry if I'm coming on strong, but in my opinion, the single most important lesson you need to pick up early in developing database-driven web sites is that you really need to be proficient at spotting injection vulnerabilities to the point where it's automatic and when you see it, you think, "Ooh! Noooo! Don't do that!!!"
Above answer found your isssue, but on a sidenote:
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
Do not do this. That my friend is the most common security vulnerability for php applications.
The most 2 most important things to remember when scripting is
Filter input, and
2: Escape output.
See this write-up for more details ..
In your case, the input values are not filtered, or checked for malicious/improper values.
Here is another primer on this page to see a few tips and how to address filtering.
Keep it up, those exercises are a fine way of picking up chops.
Happy coding friend.
Okay, re-reading your post, I think I see what you're trying to do and where you're having difficulty. Normally, you won't have two separate pages for one identical form like this. Typically, you'll code it more along these lines, and please keep in mind that I'm winging this off the top of my head, not actually testing it, so minor corrections and/or tweakage may be required:
<?php
$fname_value = '';
$lname_value = '';
if (isset($_POST['submit']) && $_POST['submit'] === 'Search') {
if (isset($_POST['fname']) && isset($_POST['lname'])) {
// We are processing a submitted form, not displaying a brand new one
// from scratch. Code any post-validation steps.
// Fetch the user information from the database. You'll need to define
// the $host, $user, $password, and $dbname variables above, or
// substitute literal strings with real information in here.
$dbh = new mysqli($host, $user, $password, $dbname);
$sql = 'SELECT first_name, last_name'.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = $dbh->prepare($sql); // Use parameters to avoid injection!
$sth->bind_param('s', $_POST['fname']);
$sth->bind_param('s', $_POST['lname']);
if ($sth->execute()) {
$result = $sth->get_result();
if (($row = $result->fetch_assoc()) != NULL) {
// Set the default values displayed in the text edit fields.
$fname_value = $row['first_name'];
$lname_value = $row['last_name'];
}
}
// Whatever other processing you want to do if this is a submitted
// form instead of displaying the page from scratch.
}
}
?>
<html>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<strong>Search for name</strong><br />
<label for="fname">First Name</label>
<input type="text" name="fname" value="<?= htmlentities($fname_value) ?>">
<label for="lname">Last Name</label>
<input type="text" name="lname" value="<?= htmlentities($lname_value) ?>">
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>

Categories