Slash appended to all my posts [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why turning magic_quotes_gpc on in PHP is considered a bad practice?
when i get information from a post form, the html form adds slashes before random characters. for example: hello "george" becomes hello \"george\".
I dont understand at all why this happens, I tried already forbidding slashes in the input tag from javascript but does not work so I need some php or javascript function to remove this from the server. The function must work in html too because i am using these three technologies because i am developing and selling web 2.0 sites.
what is the php function for this and its version for html too?
thanks in advance.
Here I link you to my pages with this problem, maybe you can check why this happens.
http://www.nickersonweb.com/
http://www.preferredmerchantservices.net/

This is an old (deprecated) feature of PHP that automagically escapes some characters in strings from various sources ($_GET, $_POST, $_COOKIE, etc).
The goal was to protect from SQL injection vulnerabilities, but this was not that good.
This can be disabled by setting the magic_quotes_gpc setting to 0 in your php.ini.
If you don't have control over the magic_quotes_gpc setting, you may want to reverse its effect, by using the stripslashes function:
$value = stripslashes($_POST['foo']);
You can do it on all $_POST variables like this:
function stripslashes_r($value) {
if (is_array($value)) return array_map('stripslashes_r', $value);
else return stripslashes($value);
}
if (get_magic_quotes_gpc()) {
$_POST = stripslashes_r($_POST);
}

special characters are escaped. you can remove the backslashes with http://php.net/manual/en/function.stripslashes.php

Related

mysql_real_escape_string for all $_POST [duplicate]

This question already has answers here:
Is is bad practice to use array_walk with mysqli_real_escape_string?
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 1 year ago.
I have a old system without any check for sql injection and I want to add mysqli_real_escape_string() every time user intract with the DB.
All of the system is built under index.php. the page look like that:
if (!isset($_GET['p'])) {
$_GET['p'] = 'main';
}
if (!file_exists($_GET['p'].".php")) {
echo "The page you are looking for isn't exist.";
} else {
if (logs()) {
include($_GET['p'].".php");
}
else {
include('not_register.php');
}
}
I thought of just adding this code in the top oh index.php and I wanted to be sure I'm not messing up with anything so i'm asking here.
foreach ($_POST as $name => $val) {
$_POST[$name] = mysqli_real_escape_string($db, $val);
}
This code running every reload of page will have any negative influence?
thx.
This:
I want to add mysql_real_escape_string() every time user intract with
the DB.
Is a good goal for legacy mysql code that is using mysql_* functions. However, this:
foreach ($_POST as $name => $val) {
$_POST[$name] = mysqli_real_escape_string($db, $val); }
is a different thing. You're not adding it to every time user interacts with DB, you're adding it done every time, before anything else has been done. The function needs a connection to the database, so if you don't have such a connection in a page that uses these variables, you immediately hit into issues. Furthermore, you can break any handling of those variables that might not expect the values to be escaped at this point - they should be escaped for DB usage, so immediately before using them with the database, not before that.
Also, as others have noted, your code is vulnerable to injections with your include pattern. file_exists can be used with network shares, file paths as well as some url wrappers. To quote file_exists manual entry:
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
Even without url wrappers, a malicious user can use your include to directly include some server configs and other files you don't want to be included.
First.
Running this question an a loop will help noone. In fact, you just reinvented a notorious magic quotes feature, that is already removed from the language. For a reason.
Second.
It is NOT good goal for legacy mysql code that is using mysql_* functions. Just because this function has nothing to do with injections at all.
If you have only 25 pages - just review them all and rewrite SQL handling code properly

Is this sufficient security for user input in PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
The ultimate clean/secure function
After reading up on PHP security I have the feeling that anything I code is always insecure. So to combat the security issues of user input I have created a function that allows me to escape and strip user input for any usage situation.
I would just like to know if this is in fact secure and if I could make it more secure. Also what kind of attacks would this prevent? From what I can tell XSS by using _GET, HTML input and MYSQL injection would have been prevented?
function _INPUT($name,$tag,$sql,$url)
{
if ($_SERVER['REQUEST_METHOD'] == 'GET')
$filter = ($_GET[$name]);//Assign GET to filter variable
if ($tag == true)//Remove all HTML, PHP and JAVASCRIPT tags
{
$filter = strip_tags($filter);
}
if ($sql == true)//If MYSQL escaping is enabled
{
$filter = mysql_real_escape_string($filter);
}
if ($url == true)//If URL encoding is enabled
{
$filter = urlencode($filter);
}
return $filter;
}
$output = _INPUT('name',true,true,true);
I will be using prepared statements for MYSQL too, although I need to read up on them more to fully understand how it prevents injection.
Thank you for your time.
Once again, there is no universal escape function that just magically makes things "secure".
See this: https://stackoverflow.com/a/7810880/362536
Different escape methods are used for different things. You can't just run a bunch of data through a bunch of functions that are supposed to be used in specific contexts. You are creating garbage data, and are no more secure than you were with the raw user data in the first place.
No,
For SQL Injection prevention, you really want to be using prepared statements. This is a safer way to do this, instead of escaping quotes. You also want to use htmlspecialchars() for escaping HTML tags, instead of just stripping them away, but that's up to you.
This is kind of an eternal question, and the answers vary across wanted usage: for prepared queries, I believe it’s 100 % safe to use its own variables system and let it handle the input. For HTML output, stripping tags may not always be what you want; moreover, it’s kind of safer to do a whitelist of what to allow in input than blacklist, because you know, hackers have fantasy. For URL output, your solution should be fine, but be aware that some other platforms may do a little different URL-encoding (see the difference between a string URL-encoded by Java standard libraries and iOS/Mac libraries, i.e.).

Will this code actually work against SQL-injection? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: the ultimate clean/secure function
I found this code snippet here: http://snipplr.com/view/12853/clean-variables-from-sql-injections/
The author claims:
This little function helps to fight common security issue with SQL injections, it can sanitize any global variable like $POST, $GET, $_SERVER etc and escape unsafe characters.
Is this code safe?
function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace("\\", "\\\\"
, htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str)
, ENT_QUOTES));
}
//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..
Please enlighten me whether this is safe, 'cause it looks jury-rigged to me.
Generic code cleaning functions are always a bad idea. They will break your data in one way or the other. Never use them; sanitize data right before it gets used, with the right sanitation method for the intended use.
Duplicate: PHP: the ultimate clean/secure function
Just use mysql_real_escape_string if you need to escape special characters for a mysql database. I'd figure other databases support similar functions too.
This snipped tries some silly replaces and may be pretty safe, but could just as well mess up your data too. Why reinvent the wheel?
Why wouldn't you just use the built-in escaping/parameterizing functionality for your database? I agree with it looking jury-rigged, go with the function built by the people who made the database library.
It's not safe (no addslashes or mysql_real_escape_string there), not optimal in performance too (get_magic_quotes_gpc being called for each variable).

"slash before every quote" problem [duplicate]

This question already has answers here:
Why are $_POST variables getting escaped in PHP?
(6 answers)
Closed 7 years ago.
I have a php page which contains a form.
Sometimes this page is submitted to itself (like when pics are uploaded).
I wouldn't want users to have to fill in every field again and again, so I use this as a value of a text-input inside the form:
value="<?php echo htmlentities(#$_POST['annonsera_headline'],ENT_COMPAT,'UTF-8');?>">
This works, except it adds a "\" sign before every double-quote...
For instance writing 19" wheels gives after page is submitted to itself:
19\" wheels
And if I don't even use htmlentities then everything after the quotes dissappears.
What is the problem here?
UPDATE:
Okay, so the prob is magic_quotes... This is enabled on my server...
Should I disable it? I have root access and it is my server :)
Whats the harm in disabling it?
Looks like you have magic quotes turned on. Use below condition using stripslashes with whatever text you want to process:
if(get_magic_quotes_gpc())
{
$your_text = stripslashes($your_text);
}
Now you can process $your_text variable normally.
Update:
Magic quotes are exaplained here. For well written code there is normally no harm in disabling it.
You likely have magic quotes turned on. You need to stripslashes() it as well.
Nicest way would be to wrap this in a function:
function get_string($array, $index, $default = null) {
if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) {
return get_magic_quotes_gpc() ? stripslashes($value) : $value;
} else {
return $default;
}
}
Which you can use as
$annonsera_headline = get_string($_POST, 'annonsera_headline');
By the way:
And if I don't even use htmlentities then everything after the quotes dissappears.
It's actually still there in the HTML source, you only don't see it. Do a View Source ;)
Update as per your update: the magic quotes is there to prevent SQL injection attacks in code of beginners. You see this often in 3rd party hosts. If you really know what you're doing in the code, then you can safely turn it off. But if you want to make your code distributable, then you'll really take this into account when gathering request parameters. For this the above function example is perfectly suitable (you only need to write simliar get_boolean(), get_number(), get_array() functions yourself).
Yes, you should disable magic quotes if you can. The feature is deprecated, and will likely go away completely in the future.
If you've relied on magic quotes for escaping data (for instance when inserting it into a database) you will may be opening yourself up to sql injection vulnerabilities if you disable it. You should check all your queries and make sure you're using mysql_real_escape_string().
I include the following file to undo magic quotes in apps that are deployed to servers not under my control.
<?php
set_magic_quotes_runtime(0);
function _remove_magic_quotes(&$input) {
if(is_array($input)) {
foreach(array_keys($input) as $key) _remove_magic_quotes($input[$key]);
}
else $input = stripslashes($input);
}
if(get_magic_quotes_gpc()) {
_remove_magic_quotes($_REQUEST);
_remove_magic_quotes($_GET);
_remove_magic_quotes($_POST);
_remove_magic_quotes($_COOKIE);
}
return true;
?>
This is actually a function of PHP trying to be security conscious, luckily there is an easy fix for it that looks something like this:
if (get_magic_quotes_gpc()) {$var = stripslashes($var);}
There isn't a huge problem in having it enabled, it comes down to personal preference. If you code will be moving servers much and you can't disable it through your php.ini file, it's best to use something as described above.
If you have access to your php.ini file and you want to change it, because you don't want to have to validate it each time you can add the following line to php.ini
magic_quotes_gpc = Off
Or the following to your .htaccess:
php_flag magic_quotes_gpc Off
Hope this helps clear things up.
Looks like your server is setup to use Magic Quotes.
You can fix it by stripping them with stripslashes, or better, by turning off Magic Quotes.
you shouldn't use htmlentities() when writing something to an input field value.
is magic_quotes enabled on your server? try out stripslashes before the output.

mysql_real_escape_string() leaving slashes in MySQL

I just moved to a new hosting company and now whenever a string gets escaped using:
mysql_real_escape_string($str);
the slashes remain in the database. This is the first time I've ever seen this happen so none of my scripts use
stripslashes()
anymore.
This is on a CentOS 4.5 64bit running php 5.2.6 as fastcgi on a lighttpd 1.4 server. I've ensured that all magic_quotes options are off and the mysql client api is 5.0.51a.
I have the same issue on all 6 of my webservers.
Any help would be appreciated.
Thanks.
Edit:
Magic Quotes isn't on. Please don't recommend turning it off. THIS IS NOT THE ISSUE.
The host that you've moved probably has magic_quotes_runtime turned on. You can turn it off with set_magic_quotes_runtime(0).
Please turn off magic_quotes_runtime, and then change your code to use bind variables, rather than using the string escaping.
I can think of a number of things that could cause this. But it depends how you are invoking SQL queries. If you moved to use parameterized queries like with PDO, then escaping is unnecessary which means the call to mysql_real_escape_string is adding the extra slashes.
If you are using mysql_query etc. then there must be some code somewhere like addslashes which is doing this. This could either be before the data is going into the database, or after.
Also you say you have disabled magic quotes... if you haven't already, just do a hard check in the code with something like this:
echo htmlentities($_GET['value']); // or $_POST, whichever is appropriate
Make sure there are no slashes in that value, then also check this:
echo "Magic quotes is " . (get_magic_quotes_gpc() ? "ON" : "OFF");
I know you've said multiple times it isn't magic quotes, but for us guys trying to help we need to be sure you have checked the actual PHP output rather than just changing the config (which might not have worked).
it sounds as though you have magic quotes turned on. Turning it off isn't too hard: just create a file in your root directory called .htaccess and put this line in it:
php_flag magic_quotes off
If that's not possible for whatever reason, or you want to change your application to be able to handle magic quotes, use this technique:
Instead of accessing the request variables directly, use a function instead. That function can then check if magic quotes is on or off and strip out slashes accordingly. Simply running stripslashes() over everything won't work, because you'll get rid of slashes which you actually want.
function getVar($key) {
if (get_magic_quotes_gpc()) {
return stripslashes($_POST[$key]);
} else {
return $_POST[$key];
}
}
$x = getVar('x');
Now that you've got that, all your incoming variables are ready to be escaped again and mysql_real_escape_string() won't stuff them up.
the slashes remain in the database.
It means that your data gets double escaped.
There are 2 possible reasons:
magic quotes are on, despite of your feeling. Double-check it
There is some code in your application, that just mimic magic quotes behaviour, escaping all input.
This is very common misconception to have a general escaping function to "protect" all the incoming data. While it does no good at all, it also responsible for the cases like this.
Of so - just find that function and wipe it out.
You must probably have magic quotes turned on. Figuring out exactly how to turn it off can be quite a headache in PHP. While you can turn off magic quotes with set_magic_quotes_runtime(0), it isn't enough -- Magic quotes has already altered the input data at this point, so you must undo the change. Try with this snippet: http://talks.php.net/show/php-best-practices/26
Or better yet -- Disable magic quotes in php.ini, and any .htaccess files it may be set in.
I am not sure if I understand the issue correctly but I had a very same problem. No matter what I did the slashes were there when the string got escaped. Since I needed the inserted value to be in the exact same format as it was entered I used
htmlentities($inserted_value)
this will leave all inserted quote marks unescaped but harmless.
What might be the problem (it was with us) that you use mysql_real_escape_string() multiple times on the same var. When you use it multiple times, it will add the slashes.
Function below will correctly remove slashes before inserting into the database. I know you said magic quotes isn't on but something is adding slashes so try the following page and see the output. It'll help figure out where. Call with page.php?var=something-with'data_that;will`be|escaped
You will most likely see number three outputting more slashes than needed.
*Change the db details too.
<?php
$db = mysql_connect('host', 'user', 'pass');
$var = $_REQUEST['var'];
echo "1: $var :1<br />";
echo "2: ".stripslashes($var)." :2<br />";
echo "3: ".mysql_real_escape_string($var)." :3<br />";
echo "4: ".quote_smart($var)." :4<br />";
function quote_smart($value)
{
// Stripslashes is gpc on
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number or a numeric string
if ( !is_numeric($value) )
{
$value = mysql_real_escape_string($value);
}
return $value;
}
?>
mysql_real_escape_string($str); is supposed to do exactly that. it is meant to add backslashes to special characters especially when you want to pass the query to mysql. Take note that it also takes into account the character set of mysql.
For safer coding practices it would be good to edit your code and use stripslashes() to read out the data and remove the slashes.

Categories