The form is ok and it captures all of the information correctly, however, the errors started when I used a function to generate a random string that is used for user activation.
function generateActivationString() {
$randomSalt = '*&(*(JHjhkjnkjn9898';
$uniqId = uniqid(mt_rand(), true);
return md5($randomSalt.$uniqId);
}
if (!get_magic_quotes_gpc()) {
// $_POST['pass'] = addslashes($_POST['pass']);
$username = addslashes($_POST['username']);
$firstname = addslashes($_POST['firstname']);
$surname = addslashes($_POST['surname']);
// $_POST['email'] = addslashes($_POST['email']);
$email = mysql_real_escape_string(addslashes($_POST['email']));
$pass = mysql_real_escape_string(sha1($_POST['pass']));
$activationString = generateActivationString();
}
$insert = "INSERT INTO users (username, password, firstname, surname, email, activation_string)
VALUES ('".strtolower($username)."', '".$pass."', '".strtolower($firstname)."', '".strtolower($surname)."', '".strtolower($email)."', '".$activationString."')";
Here is the echoed insert statement:
INSERT INTO users (username, password, firstname, surname, email, activation_string) VALUES ('', '', '', '', '', '')
I know it has created a new entry as the auto_increment id row is populated however al of the other fields remain empty.
Here is the code from the generateActivationString() so I know that's working too! - 264361eeb6e75d3934ce249a0d05f2c1
Any suggestions are more than welcome and greatly appreciated!
Going strictly by the code above, your variables like $username,$password etc are in the scope of your if block, move them outside of the if.
I don't see you send that query anywhere, maybe that's your problem...
Oh dear. The biggest problem with your statement is that you are not using prepared statement and taking info directly from the POST parameters. This is a recipe for disaster and how most sites get hacked.
Related
I am trying to pass text variables from a form form a previous page and insert it into a SQL table. The problem I'm having is on the line: $sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ($firstName, 'smith')";.
If I were to replace "$firstName" with a basic string like "John", the name and last name would be inserted into the SQL table as intended. But, since I'm trying to insert a text value gathered from a form, I need to be able to use the non-static variables but for some reason that I cannot figure out, doesn't work. From everything I read online, just adding the variable into the parameter should make it work but it just doesn't.
I'm very new to this so I'm sorry if my question is confusing. Also, I am fairly certain that the issue does not lie on the file with the form on it.
Any help would be so awesome. thanks!
Here is the code that I'm having trouble with:
<html>
<?php
$username = $_Post['username'];
$email = $_Post['email'];
$phone = $_Post['number'];
$firstName = $_Post['firstName'];
$lastName = $_Post['lastName'];
$address = $_Post['address'];
$password = $_Post['password'];
$conn = new mysqli('localhost','root','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ($firstName, 'smith')";
$conn->query($sql);
echo $execval;
echo "Registration successfully...";
$conn->close();
}
?>
</html>
To summarize all other answers,
First, you should replace $firstName to '$firstName' because otherwise the text (e.g. "John") will be placed in your query without quotes, like this: INSERT INTO CUSTOMER (fname, lname) VALUES (John, 'smith') This results in an error because it thinks John is some sort of variable.
Second, your code is vulnerable to SQL Injection. This is a very serious vulnerability in your website as attackers can use it to read your entire database, and in this case, even create entries in your database, which can result in attackers being able to completely take over your site by writing files!
More in-depth info here: https://owasp.org/www-community/attacks/SQL_Injection
The important thing is that the user can control the $firstName variable that you use in $sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ('$firstName', 'smith')"; This way the attacker can change the query at that point. He could for example use the payload ', 'a'); DROP TABLE CUSTOMER;-- to delete all information in the CUSTOMER table.
There are multiple ways to prevent this, but the easiest is to use prepared statements. It looks something like this:
$stmt = $dbConnection->prepare("INSERT INTO CUSTOMER (fname, lname) VALUES (?, ?)");
$stmt->bind_param('ss', $param_firstName, $param_lastName);
$param_firstName = $firstName; // New line
$param_lastName = $lastName; // New line
$stmt->execute();
This way you make sure MySQL doesn't interpret any user input as SQL code, but only as values.
Again, more in-depth information here:
https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
If you get user input to insert into a database you should always use "Prepared statements" to prevent "SQL injection" or comparable things.
Check here:
PHP Prepared Statements - w3school
The solution of Aashish gaba should work as well but it's unsecure.
This should work for your code:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$phone = $_POST['number'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$password = $_POST['password'];
$conn = new mysqli('localhost','root','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("INSERT INTO CUSTOMER (fname, lname) VALUES (?, ?)");
$stmt->bind_param("ss",$fname, $lname);
// set parameters and execute
$fname = $firstName;
$lname = $lastName;
$stmt->execute();
echo $execval;
echo "Registration successfully...";
$conn->close();
}
?>
A nice to have of a prepared statement is the fact that they are reusable like:
// set parameters and execute
$fname = "person1_fname";
$lname = "person1_lname";
$stmt->execute();
$fname = "person2_fname";
$lname = "person2_lname";
$stmt->execute();
Also don't forget to use somthing to prevent other injections if you print a value to a user. Like:
echo "Registration successfully for" . htmlspecialchars($_Post['username']);
In addition save the password as hash (with a secure hashfunction) into the database.
As a quick fix you can update your $sql like this:
$sql = "INSERT INTO CUSTOMER (fname, lname) VALUES ('{$firstName}', '{$lastName}')";
But now your code is vulnerable to SQL Injection.
At least you should use mysqli escape function before your $sql statement, like this:
$firstName = $mysqli->real_escape_string($firstName);
$lastName = $mysqli->real_escape_string($lastName);
But I strongly recommend you considering using more advanced options like PDO for the further steps and Production environments.
Remplace $firstName to '$firstName'.
or use prepared request
I created a table in mysql as'cus_info'. It has columns as 'iD' 'NAME' 'PASSWORD' 'eMAIL'. iD column is auto increment. I want to insert a new row to this table when a new customer registered. For that I wrote the following code in PHP
<?php
error_reporting(0);
require "init.php";
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."');";
if(!mysql_query($con, $sql)){
echo '{"message":"Unable to save the data to the database."}';
}
?>
but always I get the message as "unable to save data to the database"
Could you please tell me where I have gone wrong?
Thanks in advanced.
Could you please tell me where I have gone wrong?
In more than one place.
To most directly answer your question, you can use mysql_error() to print the error you're getting from mysql. To even more directly answer it, you have swapped the order of the parameters and you don't need the semicolon to be included in the query. (See example code here.)
You shouldn't be using PHP's "mysql_*" functions, which were deprecated in PHP5.5 and even removed in PHP7. You also should not be passing user input from a form directly into a MySQL database without any cleaning.
First show your $con and then put error_reporting(1) to check if other error occurs.
And finnaly copy and replace in your code.
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."')";
Try This
<?php
error_reporting(0);
require "init.php";
if(isset($_REQUEST["save"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = mysql_query("INSERT INTO `cus_info` (`name`,`password`,`email`) VALUES ('$name','$password','$email')");
$values=mysql_insert_id();
if($values!='')
{
echo '{"message":"Successfully save the data to the database."}';
}
else
{
echo '{"message":"Unable to save the data to the database."}';
}
}
?>
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 validating my form using jquery and after the form is left with no errors, I want to insert the data into the database but for some reasons, it is not working properly. Can you help me find out my mistake. Thanks,
The JQuery is
$.post('register_user.php',
{
'name' : name,
'email' : email,
'password': password
},
function(data) {
if(data == "success"){
alert("success");
} else if(data == "fail"){
alert("fail");
}
});
THE PHP
$name = $_POST['name']; //else assign it a variabl
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT email FROM users WHERE LOWER(email) = '" . $email . "'";
$result = mysql_query($sql) or die("Could not get email: " . mysql_error());
if(mysql_num_rows($result) > 0) {
//email is already taken
}
else {
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')") or die(mysql_error());
$result2 = mysql_result($query);
if((mysql_affected_rows($result2) ==1){
echo 'success';
} else {
echo 'fail';
}
}
I dont have enough rep yet to comment, so I'll have to put this as an answer.
Step 1:
Echo (or print) out what you can.
Add echo inside your logic, like where you have: //email is already taken
Also echo out the POST variables.
If they all look OK, you should try to echo out your queries.
Eg. copy your query line that is like:
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')")
Then paste it and change it to:
echo "INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
Then if this looks bad, it's your query.. You can of course test the output in mysql directly via phpmyadmin or ssh to your server and run the commands through the console (if they give you shell access)
If you manage to get this to work, as some others commented: mysqli or pdo should be your next steps. You also need to do some basic stuff, even though that will take care of mysql injection.
You are still vunerable to XSS and also simply things like whitespace at the end of the email (users often get this, when they copy stuff and insert it into forms).
You can solve some of it by some helper functions you make in PHP, like:
function cleanData($data) {
return strip_tags(trim($data));
}
That was a very simple sample by me, you can also add other parameters to the function, like casing. Then you can switch the casing and do strtolower, strtoupper, ucwords(strtolower(, etc. And you can then simply wrap your variables inside the function :-)
Btw. E-Mail I would check with regular expressions. Also dont let JS / client side code do the input validation, as it's very easy to manipulate the DOM, or even post from an alternative source. You have to think of this data as "dirty", as it's easy to tamper with.
Ok I am making a registry for my website.
First page asks for some personal info
if($error==false) {
$query = pg_query("INSERT INTO chatterlogins(firstName, lastName, gender, password, ageMonth, ageDay, ageYear, email, createDate) VALUES('$firstNameSignup', '$lastNameSignup', '$genderSignup', md5('$passwordSignup'), $monthSignup, $daySignup, $yearSignup, '$emailSignup', now());");
$query = pg_query("INSERT INTO chatterprofileinfo(email, lastLogin) VALUES('$emailSignup', now());");
$userNameSet = $emailSignup;
$_SESSION['$userNameSet'] = $userNameSet;
header('Location: signup_step2.php'.$rdruri);
}
The first query works. The second query works but doesn't save the email...
the session doesn't work but the header works and sends me to the next page
I get no errors even if I comment out header
next page
#session_start();
$conn = pg_connect("host=localhost dbname=brittains_db user=brittains password=XXXX" );
$signinCheck = false;
$checkForm = "";
if(isset($_SESSION['$userName'])) {
$userName = $_SESSION['$userName'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
if(isset($_SESSION['$userNameSet'])) {
$userName = $_SESSION['$userNameSet'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
This is the top starting the session depending on if your logged in or not.
then if I enter in the info here and put it through this
if($error==false) {
$query = pg_query("UPDATE chatterprofileinfo SET aboutSelf='$aboutSelf', hobbies='$hobbies', music='$music', tv='$tv', sports='$sports', lastLogin='now()' WHERE email='$userName'") or exit(pg_last_error());
//header('Location: signup_step3.php'.$rdruri);
}
nothing shows up for on my database from this.
I have no idea where I went wrong
the website is
http://opentech.durhamcollege.ca/~intn2201/brittains/chatter/
For starters, don't put things that aren't strings in single-quotes like that. 'now()' means a literal string "now()"
Also, if you're doing updates to your database you're better of using prepared statements to help prevent against sql injection. In your case, see http://www.php.net/manual/en/function.pg-prepare.php