I'm learning about making my site more secure and am using mysqli's escape function to sanitize input going into SQL queries and am using htmlspecialchars() on input coming from the database (or get/post requests) echoing out onto the page.
But, any text coming from the database to display to the user looks bad because certain characters are escaped with slashes and it shows <br /> or \r\n instead of doing a line break. I can strip the slashes, of course, but shouldn't the mysqli string escape function change the escaped characters back once it is put into the database?
Am I not supposed to use htmlspecialchars to sanitize output being displayed to the user? Or should this not be happening (in which case there must be something weird going on to the data going in)?
I still want line breaks so I'm having to do a string replace. I made the function below as a replacement for just htmlspecialchars(). But I'm not seeing anything about having to do this online anywhere so I'm afraid maybe I'm doing something wrong. :-/
function display($data) {
$new = str_replace('\r\n',"<br />",$data);
$new = str_replace('\n',"<br />",$new);
$new = str_replace('\r',"<br />",$new);
$new = stripslashes($new);
$newer = htmlspecialchars($new);
$search = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '\r\n', '<br />');
$replace = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '<br />', '<br />');
$newest = str_replace($search, $replace, $newer);
return $newest;
}
Here's what I'm using to sanitize the input going into the database:
function escape($data) {
global $conn;
connect();
$data = stripslashes($data);
$data = $conn->real_escape_string($data);
$conn->close();
$data = str_replace(chr(0), '', $data);
return $data;
}
function sanitize($data) {
$data = trim($data);
$data = strip_tags($data);
$data = escape($data);
$data = htmlspecialchars($data);
return $data;
}
Related
I have a function for clean an input (delete trim, special caractere and number) in specific file and an index who i call this function.
// In index.php
$input = format_input($_POST['name']);
// In inc/function.php
function format_input($input){
$pattern = '/[^a-zA-ZÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ\-\'\s]/';
$output = preg_replace($pattern, "", $input);
$output = trim($output);
$output = ucfirst(strtolower($output));
return $output;
}
if i use this function in my index, the encoding is OK, but if i use a call to this in another file, i have black losange on my regex.
the file are in utf-8 both, i don't understand why doesn't work !
Try this:
$output = ucfirst(mb_strtolower($output,'utf-8'));
instead of:
$output = ucfirst(strtolower($output));
http://php.net/manual/en/function.mb-strtolower.php
I'm building a contact form with PHP that sends the content via mail. I just have a couple of questions that I don't find a solution for on my own.
The first must be simple, but I can't get it why I don't get any line breaks in this code:
$contactForm = $form_name . "\n";
$contactForm .= $form_email . "\n";
$contactForm .= $form_message . "\n";
And my second question is how I can have swedish letters like åäö instead of these strange letters: öäå
I'm using PHPMailer and I have set it to swedish with this line of code,
$mail->setLanguage('se', '/optional/path/to/language/directory/');
EDIT!! I missed to change the path for the language folder in the line above! Have fixed that now!
$mail->setLanguage('se', '/language/');
but it seems like this isn't the problem. I guess it must be some problem with UTF-8 or is it the PHP-code that sanitize the variables?
I'm using this to sanitize the input values:
// Security - call function
$form_name = check_input($_POST['name']);
$form_email = check_input($_POST['email']);
$form_message = check_input($_POST['message']);
// Function to check input
function check_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = strip_tags($data);
return $data;
}
Preciate some help!
I use functions (check(removeTags($data))) to save the text in mysql database:
function check($data){
if (get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
$data =addcslashes( mysql_real_escape_string($data) , "%_" );
return $data;
}
function removeTags($data){
$data=trim($data);
$data=strip_tags($data);
return $data;
}
I use this function to display text above was saved to the user.
function output($data){
return htmlspecialchars($data,ENT_QUOTES,"UTF-8");
}
But Unwanted character are added to the text.replace newline('<br/>') with "\r\n".
I use stripslashes but it didn't worked ( replace '\r\n' with 'nr' ).
I use str_replace("\r\n", "<br />",$data) but it didn't worked too.
how can i remove '\r\n' ?
edit
see this outputting \r\n after text is decoded - PHP .
but user input is not encoded with that function ( like encode ),user input language is persian (Arabic).
For remove all new line characters from string use:
function check($data) {
if (get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
// this will remove all \n\r from output what you asked in question
$data = str_replace(array("\r", "\n"), '', $data);
// in case you want new line in place of \n\r use line below
// $data = nl2br($data);
$data = addcslashes(mysql_real_escape_string($data) , "%_");
return $data;
}
...
Make sure you use this on clean user input. Before addslashes or other escaping methods. After escaping EOL characters became "\\r\\n" and str_replace will not work on them.
Sanitising some user input;
function html_mysql_sanitise($data) {
if(get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
$data = htmlentities($data, ENT_QUOTES);
$data = htmlspecialchars($data, ENT_QUOTES);
return mysql_real_escape_string($data);
}
$_POST['data'] = html_mysql_sanitise($_POST['data']);
echo $_POST['data'];
echo html_entity_decode(htmlspecialchars_decode($_POST['data']));
echo html_entity_decode($_POST['data'], ENT_NOQUOTES);
echo htmlspecialchars_decode($_POST['data'], ENT_NOQUOTES);
$_POST['data'] is set to;
test<d#'!;ta>
The output of this is;
test<d#'!;ta>
test
test<d#'!;ta>
test<d#'!;ta>
Why do the last two produce the same result, and the 2nd one is part of the posted data? Since the last two seem to produce the desired result, which should I use?
Thank you.
Why re-invent the wheel... use this:
http://htmlpurifier.org/docs
Or this:
http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/index.php
Both good at exactly what you want to do.
I am having trouble with NSProcessInfo's arguments property. I am creating a command line tool that needs to decode base64 code that it has been passed from the internet using a PHP script, along with some other arguments. The data is passed fine, but for some reason. [[NSProcessInfo processInfo] arguments] returns 21 arguments, even though I pass just one base64 string.
Here's the objective-c side of it:
NSArray *arguments = [[NSProcessInfo processInfo] arguments];
if ([[arguments objectAtIndex:1] isEqualToString:#"-s"])
{
if ([arguments objectAtIndex:2] == nil)
{
printf("Error: No data\n");
[pool drain];
return 0;
}
NSString*data = [arguments objectAtIndex:2];
if ([data length] == 0)
{
printf("Error: No data\n");
[pool drain];
return 0;
}
NSString*password = #"";
if ([[arguments objectAtIndex:3] isEqualToString:#"-p"])
{
if ([arguments objectAtIndex:4] == nil)
{
printf("Error: No password\n");
[pool drain];
return 0;
}
else
{
password = [NSString stringWithString:[arguments lastObject]];
}
}
NSLog(#"Args: %i\n\n",[arguments count]); //returns 21? I expect 3.
The base64 code is a bit long, so I've put it here. Does anyone know why this code returns this many arguments? It's supposed to be just one string?
Edit: I am stripping whitespaces in my PHP script. See here:
<?php
$url = $_GET['data'];
$query = "/Library/WebServer/email/emailsender -s";
$password = "-p somePassword";
$commandStr = trim("$query $url $password");
$commandStr = removeNewLines($commandStr);
echo $commandStr;
$output = shell_exec($commandStr);
echo "<pre>Output: $output</pre>";
function removeNewLines($string) {
$string = str_replace( "\t", ' ', $string );
$string = str_replace( "\n", ' ', $string );
$string = str_replace( "\r", ' ', $string );
$string = str_replace( "\0", ' ', $string );
$string = str_replace( "\x0B", ' ', $string );
return $string;
}
?>
When you send arguments to a program through the command-line, each argument is separated by a whitespace character. This means that if you post a string that contains spaces, your program will interpret it as many arguments. To prevent this behavior, you need to quote your strings.
When I display the Base64 string on your pastie page as "raw" I see a lot of spaces in it. So most likely the arguments is correct and your PHP script is calling the Objective-C program the wrong way. An easy fix might be to just strip out any whitespace before passing the string, or properly escape it.