Sanitizing Data sent to Database - php

This is code from my user registration site where data is being sent to the database. My question is if this is the correct and proper way to sanitize the data that is being sent? Also, how can I test it?
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$email = test_input($_POST['email']);
$firstname = test_input($_POST['firstname']);
$lastname = test_input($_POST['lastname']);
$user = test_input($_POST['user']);
$pass = test_input($_POST['pass']);
$passnew = md5($pass);

I guess This post answers all your questions. Moreover you'll get to know when to actually escape or sanitize user input.

Related

How to deal with unencoded URL redirects to my website correctly?

We are using CleverReach to redirect people to our website after they have double opt-in their mail account. We redirect the email as a query parameter to our website, like: example.com/thanks?email=foo#bar.com (by setting up a redirect in the CleverReach backend like example.com/thanks?email={EMAIL}). Apparently, the email parameter doesnt get urlencoded by cleverreach.
Now, in Drupal, if the URL is like so: example.com/thanks?email=hello+world#bar.com and using this code:
$request = \Drupal::request();
$email = $request->query->get('email');
$email is hello world#bar.com. Now, I dont know what the correct processing is here. Obviously, I cant tell CleverReach to urlencode their redirects beforehand. I dont even know if that would be best practice or if I need to imlement something...
The only thing I found out is that $_SERVER['QUERY_STRING'] contains the "real" string, which I can urlencode and then redirect, and then, by reading the query params, urldecode them. But I feel like I am missing some crucial inbuilt functionality.
TL;DR
If a website redirects to my website using not urlencoded query params, how do I read them?
My current approach:
<?php
public function redirectIfIllegalUri() {
$request = \Drupal::request();
$email = $request->query->get('email', '');
$needsRedirect = (false !== strpos($email, ' ') || false !== strpos($email, '#'));
if ($needsRedirect && isset($_SERVER['QUERY_STRING']) && false !== strpos($_SERVER['QUERY_STRING'], 'email=')) {
$sqs = $_SERVER['QUERY_STRING'];
$sqs = htmlspecialchars($sqs);
$sqs = filter_var($sqs, FILTER_SANITIZE_STRING);
$sqs = filter_var($sqs, FILTER_SANITIZE_ENCODED);
$sqs = urldecode($sqs);
$sqs = explode('&', $sqs);
foreach ($sqs as $queryParam) {
if (false === strpos($queryParam, 'email=')) continue;
$values = explode('=', $queryParam);
$email = $values[1];
}
$emailEncoded = urlencode($email);
$query = $request->query->all();
$query['email'] = $emailEncoded;
$refreshUrl = Url::fromRoute('<current>');
$refreshUrl->setOptions([
'query' => $query,
]);
$response = new RedirectResponse($refreshUrl->toString(), 301);
$response->send();
return;
}
}
$request = \Drupal::request();
$email = urldecode($request->query->get('email', false));
drupal request() docs
The problem you are facing is that the + will be treated as a space when you get the value from $_GET global variable.
Currently in PHP doesn't exist a method that returns these values without urldecoding and you need to build a custom function to achieve what you are asking:
A simple function will return not encoded input is by using this function:
function get_params() {
$getData = $_SERVER['QUERY_STRING'];
$getParams = explode('&', $getData);
$getParameters = [];
foreach ($getParams as $getParam) {
$parsed = explode('=', $getParam);
$getParameters[$parsed[0]] = $parsed[1];
}
return $getParameters;
}
This solution can be used if you do not have any other option. By using this function you will always get the data encoded.
If you can encode the value from cleverreach then the best approach is to encode it there.
Encoding the value in cleverreach for email hello+world#bar.com will give you this url example.com/thanks?email=hello%2Bworld%40bar.com and in $_GET you will have the email containing the + sign.

the order of application of Sanitization, Escaping and Validation in php

I’m a beginner and trying to create a user registration form in php. After so much searching and reading (mostly here in stack overflow-the search was so intense - twice they asked me if I’m a robot) I came to know that I have to go through at least three (as far as I know) procedures before inserting the data in to the data base.
1.Sanitization
2.Escaping
3.Validation
My question is, what is the order of application of these procedures – which comes first and which one comes second and third.
For example I found this code online.
<?php
$emailErr = "";
$email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
They trim, remove back slashes and then replacing the html special characters before validate it with filter_var().
But I think the filter_var() should be the first to apply, is that right or I’m a stupid who doesn’t get it right ?
(By the way – as far as I know the backslashes are allowed in an email, if we use stripslashes() wouldn’t that be a problem too?)

Writing .php file using php code

Hi there I'm trying to write a .php file using this code, server replying this error : syntax error, unexpected '0' (T_LNUMBER) in
I wanna know how can I write integer in php file as you can see
$status1 = \''0'\';
This code having problem, anybody please tell me what to do.
<?php
if(isset($_POST['user1'])){
$data = urldecode('%3C').'?php
$user1 = \''.$_POST['user1'].'\';
$pass1 = \''.$_POST['pass1'].'\';
$status1 = \''0'\';
$user2 = \''.$_POST['user2'].'\';
$pass2 = \''.$_POST['pass2'].'\';
$status2 = \''0'\';
$user3 = \''.$_POST['user3'].'\';
$pass3 = \''.$_POST['pass3'].'\';
$status3 = \''0'\';
$user4 = \''.$_POST['user4'].'\';
$pass4 = \''.$_POST['pass4'].'\';
$status4 = \''0'\';
$user5 = \''.$_POST['user5'].'\';
$pass5 = \''.$_POST['pass5'].'\';
$status5 = \''0'\';
$user6 = \''.$_POST['user6'].'\';
$pass6 = \''.$_POST['pass6'].'\';
$status6 = \''0'\';
$user7 = \''.$_POST['user7'].'\';
$pass7 = \''.$_POST['pass7'].'\';
$status7 = \''0'\';
$user8 = \''.$_POST['user8'].'\';
$pass8 = \''.$_POST['pass8'].'\';
$status8 = \''0'\';
$user9 = \''.$_POST['user9'].'\';
$pass9 = \''.$_POST['pass9'].'\';
$status9 = \''0'\';
$user10 = \''.$_POST['user10'].'\';
$pass10 = \''.$_POST['pass10'].'\';
$status10 = \''0'\';
?'.urldecode('%3E');
$fx=fopen('datauser.php','w');
fwrite($fx,$data);
fclose($fx);
if($fx === false) {
header("Location: ./tokensettings.php?save=err");
}
else {
header("Location: ./tokensettings.php?save=success");
}
}
?>
Thank you so much.
Here is how my form looks like.
If you still want to do it your way you need to use the \ correctly for each ' to be included in the string even those in [ ] - not saying the final string produced would actually work but it is based on your code and my best guess at your desired result
<?php
$string1=' \'\'.$_POST[\'user1\']\'\';';
$string1=$string1.'\'\'0\'\';';
echo $string1;
?>
The whole urlencoding stuff is not needed at all, your quoting and escaping is messy and incorrect. and why not simply use file_put_contents? Use HEREDOC to avoid messy escaping.
file_put_contents('datauser.php', <<<CONTENT
<?php
\$user = '{$_POST['user']}';
\$pass = '{$_POST['pass']}';
\$status = '0';
CONTENT
);
but if you really want to use files as data storage, I would encourage you to save it in a data format like xml or json instead of writing php.
// save data to file ($_POST used as example...)
file_put_contents('user.json', json_encode($_POST));
// read data
$data = json_decode(file_get_contents('user.json'));

PHP XSS validation not working

I have written a simple contact form script and am trying to add XSS validation to it using the method described on W3School. Unfortunately it doesn't work as if I enter a "<" in one of the fields and then submit, it comes out as "<" when I receive it via email.
Can anyone suggest what I'm doing wrong?
Data collection section
$name = $co = $email = $tel = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$name = test_input($_REQUEST['name']);
$co = test_input($_REQUEST['company']);
$email = test_input($_REQUEST['email']);
$tel = test_input($_REQUEST['tel']);
$message = test_input($_REQUEST['message']);
}
Data testing function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Many Thanks
Maybe your email client is configured to show the email as HTML. htmlspecialchars will convert < to <
Try to display your email as plain text.

queries regarding PHP mail() 'issues'

So I recently made a basic site for a family members small company. I included a mail form, for enquiries etc.
here is the code i use:
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
?>
now when I try it, it works absoloutely fine. However I have noticed sometimes it is realllllly slow and so we have been receiving blank emails through the form (the user input data is not present), so it appears someone has attempted to use it and given up perhaps because it is taking too long?
I am assuming this is to do with the mail server rather than php mail. But I wanted to see if anyone could highlight potential issues that I could take to the company hosting for her?
many thanks,
check if name and email fields are entered and then proceed with mail function..this reduces getting blank emails.
<?php
if (isset($_POST['name']) && isset($_POST['email'])) //check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Alternatively you can also use array_key_exists()
<?php
if (array_key_exists("name", $_POST) && $_POST["name"] != "" && array_key_exists("email", $_POST) && $_POST["email"] != "")
//check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Actually you are not checking if someone fill the form empty that's why you are getting blank fields
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($data))
{
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
}
?>

Categories