validating data in PHP - php

I have a form like below and I want to get some input from the user. My goal is to validate the data before submitting into database. My question is how do I do this ?
<form action="../actions/insertcomment.php" method="post">
<p class ="ctitle">Leave a Comment:</p>
<p><label for="postid"><b>PostID:</b></label>
<input type="text" id="postid" name="postid" maxlength="5" /> <br/>
<label for="name"><b>Name:</b></label>
<input type="text" id="name" name="name" maxlength="25" /> <br/>
<label for="email"><b>Email:</b></label>
<input type="text" id="email" name="email" maxlength="50" /> <br/>
<label for="website"><b>Website:</b></label>
<input type="text" id="website" name="website" maxlength="25" /> <br/>
<label for="content"><b>Comment:</b></label>
<textarea id="content" name="content" cols="10" rows="4" maxlength="100"></textarea> <br/>
<input type="submit" value="Submit Comment" name="submit_comment" /> <br/>
</p>
</form>
and my insercomment.php is as follows:
<html>
<link rel = "stylesheet" type = "text/css"
href = "../common/style.css" />
<?php
include("../common/dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
//$postid= $_GET['id'];
if($_POST) {
$postid= $_POST['postid'];
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
$postid = htmlspecialchars($postid);
$users_name = htmlspecialchars($users_name);
$users_email = htmlspecialchars($users_email);
$users_website = htmlspecialchars($users_website);
$users_comment = htmlspecialchars($users_comment);
$sSql = "INSERT INTO comments
( post_id,name, email, website,content)
VALUES ( $postid, '$users_name',
'$users_email', '$users_website', '$users_comment' )";
//echo $sSql;
mysql_query($sSql);
//$update=mysql_affected_rows();
//echo "<h2>$update Record Inserted</h2><br />";
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
Here I am not using " method="post"> Any code or example for this kind is appreciated.

The best way would be to check if the data is valid, befor the sql statement.
Pseudocude:
$data1 = $_POST['xyz']; //text
$data2 = $_POST['abc']; //number
...
errors = array
if(data1 is not text) errors[] = data1 must be text
if(data2 is not number) errors[] = data2 must be number
...
if(count(errors) > 0) return errors
else
do the sql insert
return "thank you message"

You should certainly sanitize your inputs to prevent injection:
$postid= mysql_real_escape_string($_POST['postid']);
This will make all your inputs safe to insert into the database.

My experience says that you should check your input with if-else statement before doing an insert to DB. The most important thing is to use prepared statement. Don't pass raw strings like that. Always use prepared statement for your forms.
Refer this: Best way to prevent SQL Injection

You can use filter_input to validate data in php. You can read more about it here:
filter_input in php
Here's an example on how to use it to validate an email:
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
Where INPUT_POST is the method, email is the name of the field ($_POST['email']) and FILTER_VALIDATE_EMAIL is the validation option.
You might want to consider using prepared statements in mysqli or pdo to make your application more secure.
To check if a variable has a value you can use the function empty:
if(!empty($_POST['email']){
//do stuff
}
You can also add client-side validation. A good library is the liveValidation which as the name suggests validates user input as they type so that the user won't have to wait for the page to refresh before they get feedback whether their form has been successfully submitted or not.

I suggest you use sanitize the strings for SQL injections using mysql_real_escape_string(). Validate using if else statements. Fore example
if ($_POST['name']...)
{
echo "fill in those fields!";
}
else
{
do stuff...
}
By the way you should be using a PDO prepared statement and not echoing HTML with PHP.

You can do like this :-
if(isset($_POST))
{
if($_POST['postid']!="" && $_POST['name']!="" &&.....)
{
//do your insertion here
}
else
echo "oops !! Something is missing";
}

Related

Can't send data from a user form to a database in PHP

I'm creating a simple sign-up form program in PHP, which basically reads input from a form and send them to a database. I'm having some problems reading the data from the data form:
This is the CSS part with the form:
<form class="signup-form" action="include/signup.inc.php" method="POST">
<input type="text" name="first" placeholder="Firstname">
<input type="text" name="last" placeholder="Lastname">
<input type="text" name="email" placeholder="E-Mail">
<input type="text" name="uid" placeholder="Username">
<input type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Sign Up</button>
</form>
And this is the part supposed to send everything from my database:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || ($pwd)) {
//header("Location: ../signup.php?signup=empty");
echo "empty";
exit();
} else {
//Other conditions...
Basically the first condition should check IF the user is trying to input an empty field. If a field is empty, just redirect the page to ../signup.php?signup=empty (the 'echo empty' line is just for debugging purposes). The problem is that it will always detect an empty field, even if i fill all of them, as if the script is having problems reading data from the forms. I hope my explanation was clear, every advice is very welcome!
Edit: Someone else pointed out that you forgot empty() around $pwd. That might be the problem as well.
Have you tried to print out what $first or your other variables are? I suspect that mysqli_real_escape_string is returning null and that's why your if statement is saying they're empty.
I would also check $_POST['form_item'], where 'form_item' is each of your inputs, just to see if they're being sent properly.
But like I said, I suspect it's the real escape string function that's returning null. Check out the documentation if that's whats happening.

PHP form validation submitting blank data

I am trying to create a page to allow users to edit their details using PHP, which validates the content before being submitted.
I want to allow users to update their username, first and second name and email address.
The validation consists of:
<?php
if(preg_match("/^[0-9a-zA-Z_]{3,}$/", $_POST["username"]) == 0)
$error_username = '<li>Usernames may contain only digits, upper and lower case letters and underscores</li>';
if(preg_match("/^[A-Za-z]+$/", $_POST["fname"]) == 0)
$error_fname = '<li>First Name may contain upper and lower case letters</li>';
if(preg_match("/^[A-Za-z]+$/", $_POST["sname"]) == 0)
$error_sname = '<li>Second Name may contain upper and lower case letters</li>';
if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\#\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["email"]) == 0)
$error_email = '<li>Email Addresses must have a valid email address format</li>';
else header("Location: edit.php");
?>
And to display the errors:
<ul>
<?php if(isset($error_username)) echo $error_username; ?>
<?php if(isset($error_fname)) echo $error_fname; ?>
<?php if(isset($error_sname)) echo $error_sname; ?>
<?php if(isset($error_email)) echo $error_email; ?>
</ul>
The form that I have is:
<form name="edit_account" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input class="form_field" name="username" type="text" value="<?php echo $_POST["username"]; ?>" placeholder="Username">
<input class="form_field" name="fname" type="text" value="<?php echo $_POST["fname"]; ?>" placeholder="First Name">
<input class="form_field" name="sname" type="text" value="<?php echo $_POST["sname"]; ?>" placeholder="Second Name">
<input class="form_field" name="email" type="text" value="<?php echo $_POST["email"]; ?>" placeholder="Email Address">
<input type="submit" name="Submit" value="Update Account">
</form>
Providing that all requirements of the validation are met, the user is taken to edit.php and then redirected to a success page:
<?php
$sql = $mysqli;
$id = htmlentities($_SESSION['user_id']);
$username = $sql->real_escape_string($_POST['username']);
$fname = $sql->real_escape_string($_POST['fname']);
$sname = $sql->real_escape_string($_POST['sname']);
$email = $sql->real_escape_string($_POST['email']);
$query = ("
UPDATE users
SET
username='$username',
fname='$fname',
sname='$sname',
email='$email'
WHERE id='$id'") ;
$sql->query($query) or die($query.'<br />'.$sql->error);
header ('Location: success.php');
?>
When I attempt to run this code, the updating fields are submitted into the database as blanks - However, without the validation, the users submitted details are successfully entered.
Can someone please point out what is causing the form to submit as a blank. Thanks.
It looks like you are redirecting to edit.php (which contains database insertion code) from the validation script. The issue is that the $_POST variable is reset when you redirect.
I would include('path/to/edit.php') the edit.php script rather than redirect to it. If that isn't possible, I would save the $_POST data in a $_SESSION variable.
Hope this helps
You're posting them to the validation page, but losing them when you redirect to the edit.php page. Store the information in session variables before going to edit.php, like this:
$_SESSION['username'] = $_POST["username"];
// other variables also
On the edit.php, instead of pulling from $_POST, pull from $_SESSION.
Side Notes
Don't forget session_start() at the top of each page. Also, you should look into prepared statements when using user input.

PHP Form with required fields

I want to creat a form which can connect to mysql and can insert records which I have done. But now I want to make some fields mandatory, username and car for example. Also showing the error field as required or "name cannot have numbers". Stuff like that. I am unable to figure it out.
Some help please:
I have index.html
<form action="insert.php" method="post">
Nume: <input type="text" name="name"><span class="error">* <?php echo $error;?></span><br>
Prenume: <input type="text" name="prenume"><br>
Masina: <input type="radio" name="masina" value="vito"> (Vito)
<input type="radio" name="masina" value="skoda"> (Skoda)
<input type="radio" name="masina" value="skoda2"> (Skoda)
<input type="radio" name="masina" value="audi"> (Audi)<br><br>
Data: <input type="date" name="data"/><br>
Ora: <input type="time" name="ora"/><br>
Destinatie:<input type="text" name="destinatie"><br>
KM la iesire: <input type="text" name="kmiesire"><br>
KM la intrare: <input type="text" name="kmintrare"><br>
<input type="submit">
and Insert.php
<?php
include "connect.php";
$order = "INSERT INTO data_employees
(name, prenume, masina, data, ora, destinatie, kmiesire, kmintrare)
VALUES
('$_POST[name]',
'$_POST[prenume]',
'$_POST[masina]','$_POST[data]','$_POST[ora]','$_POST[destinatie]',
'$_POST[kmiesire]','$_POST[kmintrare]'
)";
if (mysqli_query($con,$order)){
header('Location: index.html');
}else{
echo("Input data is fail");
}
?>
you have to check rules before the query...
if(empty($_POST['name'])){
echo "Name Required";
}
elseif(bla bla){
echo "something"
}
else {
// your query....
}
Start checking with ,
if($_POST) {
if(isset($_POST['name'])!='') {
echo 'your error message';
}else if (isset($_POST['prenume'])!='') {
echo 'your error message';
}.....
else
//your insertion code (query)
}
And also you can check with # ,empty like isset .
You have to check that POST values are not empty then there is no injected code to prevent injection attacks.
You should take a look to PDO PHP. It will be more safer than mysql low-level functions and more easy to use.

Is it possible to use $_REQUEST for inserting data in a mysql database?

I already have this code figured out, but the entries a user submits with the submit button aren't going anywhere. Is there any way to fix this, or should I just use the $_POST method?
PHP code:
<?php
include ("dbroutine.php");
function register() {
$connect = db_connect;
if (!$connect)
{
die(mysql_error());
}
$select_db = mysql_select_db(securitzed, $connect);
if (!$select_db) {
die(mysql_error());
}
//Collecting info
$fname = $_REQUEST ['fname'];
$lname = $_REQUEST ['lname'];
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$email = $_REQUEST['email'];
//Here we will check do we have all inputs filled
if(empty($_REQUEST['username'])){
die("Please enter your username!<br>");
}
if(empty($_REQUEST['password'])){
die("Please enter your password!<br>");
}
if(empty($_REQUEST['email'])){
die("Please enter your email!");
}
//Let's check if this username is already in use
$user_check = mysql_query("SELECT username FROM members WHERE username = '".$_REQUEST
['username']."'");
$do_user_check = mysql_num_rows($user_check);
//Now if email is already in use
$email_check = mysql_query("SELECT email FROM members WHERE email= '".$_REQUEST['email']."'");
$do_email_check = mysql_num_rows($email_check);
//Now display errors
if($do_user_check > 0){
die("Username is already in use!<br>");
}
if($do_email_check > 0){
die("Email is already in use!");
}
//If everything is okay let's register this user
$insert = mysql_query("INSERT INTO members (username, password, email)
VALUES ('".$_REQUEST['username']."', '".$_REQUEST['password']."', '".$_REQUEST['email']."', '".$_REQUEST['fname']."', '".$_REQUEST['lname']."')");
if(!$insert){
die("There's little problem: ".mysql_error());
}
}
switch($act){
case "register";
register();
break;
}
HTML code:
<body>
<form method="post">
First Name: <input type="text" name="fname" value="" /> <br />
Last Name: <input type="text" name="lname" value="" /> <br />
E-mail: <input type="email" name="email" value="" /> <br />
Desired Username: <input type="text" name="username" value="" /> <br />
Password: <input type="password" name="password" value="" /> <br />
Confirm Password: <input type="password" name="passwordconf" value="" /> <br />
<input type="submit" value="Submit"/>
</form>
</body>
If I need to add anything, could anyone point it out, if not, I could also add some extra code if needed.
$_REQUEST contains: $_COOKIE, $_GET, and $_POST variables. if you use $_REQUEST you have no guarantee that the data came from the post data, which leads to security holes in your script. I would use $_POST but by using this method you are vulnerable to SQL injections.
$_GET retrieves variables from the querystring, or your URL. $_POST retrieves variables from a POST method, such as (generally) forms. $_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET.
Fix
You have to specify the action in your form as below.
<form action="fetch_data.php" method="post">
<form action="URL">
URL - Where to send the form-data when the form is submitted.
Possible values:
An absolute URL - points to another web site (like
action="http://www.example.com/example.htm")
A relative URL - points to a file within a web site (like action="example.htm")
First, I advice you to read more about variables.
Second, $_REQUEST is a variable like $_POST, $_SESSION, $_GET and so on, which can be stored into your database. So, for your question, Yes you can use $_REQUEST to insert data in a MySQL database
HOWEVER, using it as a substitute for the $_POST variable is not secure at all and not a good practice. Take a look at this to see how the $_POST variable works.
Third, you are using mysql_* functions in your code. please consider using PDO or MYSQLI instead to prevent SQL INJECTION and secure your website better. In addition, MYSQL is dupricated in PHP 5.5 and up. take a look at this tutorial, it shows you how to use PDO instead of MYSQL.
Fourth, you should not be storing passwords directly to databases, you need some form of password hashing. read more about it here
Try using
$fname = $_POST ['fname'];
$lname = $_POST ['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
You could also do following to check request params
var_dump($_POST);
Use ACTION in your HTML form.
Sanitize the data as well from sql injection.
Check if data from $_REQUEST is not empty.

javascript unable to assign hidden input elements from HTML input tag

i am trying to grab the hidden input value from a form i have. The form passes all the elements properly EXCEPT for the HIDDEN elements. I know they are declared because if I choose "view source" on the page it shows me the correct values (basically the user credentials).
<form name="addExperienceForm" id="addExperienceForm" style="display:none;">
Title:<input type="text" name="title" id="title" />
From:<input type="text" name="startDate" id="startDate" />
To:<input type="text" name="endDate" id="endDate" />
Description:<textarea type="message" name="description" id="description"></textarea>
<input type="button" value="Submit" onclick="addUserExp()"/>
<input type="hidden" value="<?=$_SESSION['userID']?>" id="userID" />
<input type="hidden" value="<?=$_SESSION['email']?>" id="email" />
function addUserExp(){
//get info
var title = document.getElementById('title').value;
var startDate = document.getElementById('startDate').value;
var endDate = document.getElementById('endDate').value;
var userID = document.getElementById('userID').value;
var email = document.getElementById('email').value;
var description = document.getElementById('description').value;
//construct POST string with name value pair
var str = "title="+title+"start="+startDate+"end="+endDate+"userID="+userID+"email="+email+"desc="+description;
//establish XMLHTTP object
var req = getXMLHTTP();
if(req){
req.onreadystatechange = function(){
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('addNewExp').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
}
req.open("post", "addExperience.php", true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(str);
}
PHP
<?php
$title = $_POST['title'];
$startDate = $_POST['start'];
$endDate = $_POST['end'];
$userID = $_POST['userID'];
$email = $_POST['email'];
$description = $_POST['desc'];
$sql = "INSERT INTO `user_experience`(`user_id`, `email`, `experience_title`, `experience_desc`, `start_date`, `end_date`)
VALUES ('$userID', '$email', '$title', '$startDate', '$endDate', '$description')";
echo $sql;
?>
I am echoing out the MYSQL statement so you can see that the fields are not being populated. The output of the above produces the following when data is entered into the form:
INSERT INTO `user_experience`(`user_id`, `email`, `experience_title`, `experience_desc`, `start_date`, `end_date`) VALUES ('', '', 'test', 'Feb-2013', 'May-2013', 'test')
There's a few things I can see wrong from the start.
(1) <type="text" name="endDate" id="endDate" />
I'm guessing this should be <input type="text" name="endDate" id="endDate" />.
(2) Your inputs have no name attributes. id attributes are nice for styling and gathering values. However, only name attributes are recognized by a form conducting a submit.
(3) You have no method attribute on your form. By default, the browser will use GET. You however are expecting POST. Either change the PHP to use $_GET instead of $_POST or (the better option) supply the form with a method attribute.
A couple things to be mindful of (and a few pet peeves of mine):
(1) It's always a good idea to specify the method of the form attribute. Browser's should default to GET but just to be clear to anyone who may be following in your foot steps, it would be nice to see clarity.
(2) Please, please, please don't use the PHP <? short tags. One this is not clear, two it's not supported in all installations of PHP as it's based on a PHP .ini file setting and three it's just three more characters you have to add. Let's not be lazy folks.
Hope this helps.
dont build that sql-string yourself, use prepared statements please, would be better for your security ;)
it would be better for compatibility-reasons to use a library for ajax (like jquery)
<?php
$title = $_POST['title'];
$startDate = $_POST['start'];
$endDate = $_POST['end'];
$userID = $_POST['userID'];
$email = $_POST['email'];
$description = $_POST['desc'];
$sql = "INSERT INTO `user_experience`(`user_id`, `email`, `experience_title`, `experience_desc`, `start_date`, `end_date`)
VALUES ('$userID', '$email', '$title', '$startDate', '$endDate', '$description')";
echo $sql;
?>
change all $_POST to $_GET and you should be through.
you need added "name" attr in you form
<input type="hidden" name="userID" value="<?=$_SESSION['userID']?>" id="userID" />
<input type="hidden" name="email" value="<?=$_SESSION['email']?>" id="email" />
you have sql-injection, use:
array_map('mysql_real_escape_string',$_POST);

Categories