How to add mysql_real_escape_string to this code? - php

I am unsure as to how to add escape string to the $_POST['scan'] I used
$var = mysql_real_escape_string($_POST['scan']);
And then swapped it with the $_POST['scan'] in the code but it won't work. It just shows me blank screen.
foreach ($_POST['scan'] as $key => $value1) {
echo "$value1, ";
}

mysql_real_escape_string($str) is used for escaping SQL queries, not for displaying to the user. You may like to use htmlentities($str) or htmlspecialchars($str) instead.

try: print_r($_POST);
to see what you are getting in your post variables. Are you even passing an array via $_POST['scan'] or any data at all? As someone else alluded to, mysql_real_escape_string is to be used on a string prior to inserting into mysql, and hopefully after the string has been validated/sanitized.

Related

mysql_real_escape_string Not Working with '

I have a form processed with PHP. It contains a field for Notes about the client job.
The problem is that if there is a ' within in the notes - such as it's, O'Reilly, that's etc, it escapes the string in the database, so I have all of the notes up until it encounters the ' then that's the end of the notes.
I realise there are things like mysqli_ and PDO, but it's the busy season at the moment and I could just do with quickly fixing this before doing a complete update/overhaul in January.
Any idea why it isn't working? Code included. It doesn't matter where I put the mysql_real_escape_string(), it doesn't work anywhere.
FYI: The table column is TEXT. And there are a couple of other fields hence the foreach
// SELECTS AND CONNECTS TO SERVER/DB
include_once('config/db.inc.php');
// CONVERT ALL $_POST['name'] to $name and clean/prep for mysql insertion
foreach($_POST as $key => $value ) {
$$key = mysql_real_escape_string($value);
}
// UPDATE CLIENT JOB NOTES
$query = "UPDATE client_list SET bookingNotes='$bookingNotes' WHERE id='$CID'";
mysql_query($query, $conn) or die(mysql_error());
TIA
Edit for the responses below:
$bookingNotes and $CID are define by the form variables $_POST['bookingNotes'] and $_POST['CID'] where the foreach essentially removes the "_POST" part. (that's the whole $$key = $value part)
As mentioned, I appreciate mysqli_ and PDO but am currently unable to learn, update and implement those system wide at the moment. This runs locally and my current version of PHP 5.4.1 supports the function. I understand PDO is better, but for now that is not an option so please don't belittle me with "do it properly" or "learn how to code". That isn't the issue at hand.
I know what's happening and where and why - mysql is treating the ' as and end of the string. But I don't know why it's happening when I believe the function should escape the ' and allow it into the database.
To surmise, this is what happens.
"Today is very grey and it's raining" is entered into the form as $bookingNotes. The script then inputs that into the TEXT column of the database. But what appears in the database is;
"Today is very grey and it"
TIA and Thanks for the responses so far.
Are you sure the problem is on the writing end? Your code looks like it should work. (Well, for some value of work, you don't want to have a field <input name='conn' value='haha'>. Anyway, you seem to understand the problems with the code well enough.)
I assume that what you see is not SQL-injection but HTML injection:
<input name='bookingNotes' value='<?php=$bookingNotes?>'>
try escaping that with
<input name='bookingNotes' value='<?php=htmlspecialchars($bookingNotes, ENT_QUOTES)?>'>
to avoid the problem.
I tried it and it seems okay
$_POST['name'] = "1'";
$_POST['age'] = '2';/*
$_POST[] = '3';
$_POST[] = '3'; */
foreach($_POST as $key => $value ) {
$$key = mysql_real_escape_string($value);
echo $$key;
}
The result I got was : 1\' - which is correct
Thank you to everyone with helpful input.
It's fixed now, I honestly don't know how.
I removed the '' on the SQL statement (WHERE bookingNotes='bookingNotes') to force an error.
I also checked (echoed) the contents of $bookingNotes, which was the POST data AFTER mysql_real_escape_string() and it had the full string with apostrophes escaped (slashed)
I removed the echo, put the SQL back, and it all worked as it should / as expected.
I backed up the script before I started working, I have since compared the "new" working one with the original one that failed and they are exactly the same, no missing characters or extra/missing whitespace, exactly the same. o_O
So I don't know what happened there!
Thanks for the input anyway.
Try changing this
$$key = mysql_real_escape_string($value);
INTO
$key = mysql_real_escape_string($value);
First, mysql_real_escape_string() always works. If some your code doesn't - well, it's your code.
Second, but most important: NEVER run a code like this
foreach($_POST as $key => $value ) {
$$key = // whatever.
}
it is actually a hole in security, worse than any other.
Finally, it is extremely unclear from your extremely vague explanation, but I guess it's HTML form where you get your "end of notes". Anyway, you have to fix the very place where it happens, not blame a function you were running long time ago

Using stripslashes on a database row php

{$row['info']}
How do I use stripslashes() php function on this?
I've tried :
stripslashes({$row['info']}), doesnt work and this: {stripslashes($row['info'])}
Neither work.
Do I have to use a $var first??
Thanks
stripslashes returns the modified string, leaving its argument unchanged. You have to assign the result to a variable:
$var = stripslashes($row['info']);
That said, why are you doing this? You almost certainly shouldn't be. There is no reason to strip slashes on data coming from the database, unless you've double-escaped the slashes when the data was inserted.
Your question is somewhat confusing.
stripslashes() takes parameter and converts backslashed symbols to normal ones. more over, it does not affect the parameter. it returns stripped version.
so $result = stripslashes($source) or $row["info"] in your case.
$var = stripslashes($row['info']);
is more correct. Or in string, use it like this
echo "something".stripslashes($row['info'])." some more thingy";
It almost seems, that you are using heredoc syntax because of your {}. Question, is why? Are you seriously displaying your results like this?:
echo <<<my_results
Info: {$row['info']}
my_results;
Well, since that is cool way to do so then here is your fix:
$row_info = stripslashes($row['info']);
echo <<<my_results
Info: {$row_info}
my_results;
However, I do not recommend that approach. Rather do it like this:
echo 'Info:' . stripslashes($row['info']);
Because {stripslashes($row['info'])} doesn't work indeed and stripslashes({$row['info']}) is an anecdote!

PHP removing backslash from code submitted through $_POST

I have a code editor block and and submitting code like the following:
$something = "Link";
However, when I submit it the string that gets output is missing the backslash escape characters and I get:
$something = "Link";
...which obviously isn't correct. I've figured out that it has to do with magic_quotes_gpc and when turned "On" works properly. My goal is for the application to be able to be installed easily on multiple hosts and I'd like to avoid having to turn on magic_quotes_gpc on every instance.
Link Here
Magic Quotes are depreciated and going
to be removed in PHP6. If you still
want your code to be portable, no
warnings etc, as of PHP52 you can use
the following code.
<?php
foreach ($_GET as $key => &$val)
$val = filter_input(INPUT_GET, $key);
foreach ($_POST as $key => &$val)
$val = filter_input(INPUT_POST, $key);
?>
The above will retrieve an-escaped
GETs and POSTs regardless system
settings. It can also be used for
$_COOKIES and others.
Try double escaping:
$something = "Link";
The addslashes()-method might be what you're looking for.
However, if you want to directly put those values in a Database, you can use the mysql_real_escape_string()-method or you go with a Prepared Statement.

A nice function to escape $_POST // what do you think about it

I'm using $_POST and aware about mysql exploit, I decided to use this function on the top of my page, therefore all POST will be safe:
Can you tell me if I miss something and this function will really do the job as I think it will?
function clean_post(){
if ( $_POST){
foreach ($_POST as $k => $v) {
$_POST[$k]=stripslashes($v);
$_POST[$k]=mysql_real_escape_string($v);
$_POST[$k]=preg_replace('/<.*>/', "", "$v");
}
}
if ( $_COOKIE){
foreach ($_COOKIE as $k => $v) {
$_COOKIE[$k]=stripslashes($v);
$_COOKIE[$k]=mysql_real_escape_string($v);
$_COOKIE[$k]=preg_replace('/<.*>/', "", "$v");
}
}
}
It will also remove all html tag, a safest option to output the result might be to use:
<pre>
$foo
</pre>
Cheers!
Cheers!
I think it's a bad idea to do this. It will corrupt the data your users enter even before it hits the database. This approach will also encourage you to use lazy coding where you consistently don't escape data because you believe that all your data is already "clean". This will come back to bite you one day when you do need to output some unsafe characters and you either forget to escape them or you aren't really sure which function you need to call so you just try something and hope that it works.
To do it properly you should ensure that magic quotes is disabled and only escape data when necessary, using precisely the correct escaping method - no more, no less.
There are some problems with it.
First you apply functions on types that doesn't need them, your integers for example needs only a (int) cast to be secure.
Second you do not secure lenght, when you're requesting a '12 chars string' it would be a good idea to ensure you've got only 12 chars, and not 2048. Limiting size is really something your attackers will not like.
Third in your foreach loop you have a $v variable, you assign 3 times a function on $v to $_POST[$k]. So the 1st two assignements are lost when the 3rd occurs...
Then all the things previous people said are right :-)
The rule is apply the filter at the right moment for the right output. HTML output need an html filter (htmlspecialchars), but the database doesn't need it, it need a database escaping. Let's say you want to extract data from your database to build a CSV or a PDF, HTML escaping will make you life harder. You'll need CSV escaping at this time, or PDF escaping.
Finally it is effectively hard to remember if you are manipulating a data which is already well escaped for your output. And I recommend you an excellent read on Joel on Software about Apps Hungarian. The text is quite long, but very good, and the web escaping sequence is used as an example on why Apps Hungarian is good (even if System Hungarain is bad).
Hi this is my first answer for any question asked on web so please review it.
Put this code in top of your script and no need to assign these posted values to any variables for doing the same job of making the input data safe for database. Just use $_POST values as it is in your query statements.
foreach ($_POST as $k => $v) {
if(!is_array($_POST[$k]) ) { //checks for a checkbox array & so if present do not escape it to protect data from being corrupted.
if (ini_get('magic_quotes_gpc')) {
$v = stripslashes($v);
}
$v = preg_replace('/<.*>/', "", "$v"); //replaces html chars
$_POST[$k]= mysql_real_escape_string(trim($v));
}
}
Don't forget $_GET[]
if ($_POST OR $_GET)
Also you can add strip_tags()
I don't know whether your function is correct or not, but the principle is certainly incorrect. You want to escape only where you need to, i.e. just before you pass things into MySQL (in fact you don't even want to do that, ideally; use bound parameters).
There are plenty of situations where you might want the raw data as passed in over the HTTP request. With your approach, there's no ability to do so.
In general, I don't think it's that good of an idea.
Not all post data necessarily goes into MySQL, so there is no need to escape it if it doesn't. That said, using something like PDO and prepared statements is a better way, mysql_* functions are deprecated.
The regular expression could destroy a lot of potentially valid text. You should worry about things like HTML when outputting, not inputting. Furthermore, use a function like strip_tags or htmlspecilchars to handle this.
stripslashes is only necessary if magic quotes are enabled (which they shouldn't be, but always is possible)
When working with stripslashes I'd use get_magic_quotes_gpc():
if (get_magic_quotes_gpc()) {
$_POST[$k]=stripslashes($v);
}
Otherwise you'll over-strip.

PHP / MYSQL: Sanitizing user input - is this a bad idea?

I have one "go" script that fetches any other script requested and this is what I wrote to sanitize user input:
foreach ($_REQUEST as $key => $value){
if (get_magic_quotes_gpc())
$_REQUEST[$key] = mysql_real_escape_string(stripslashes($value));
else
$_REQUEST[$key] = mysql_real_escape_string($value);
}
I haven't seen anyone else use this approach. Is there any reason not to?
EDIT - amended for to work for arrays:
function mysql_escape($thing) {
if (is_array($thing)) {
$escaped = array();
foreach ($thing as $key => $value) {
$escaped[$key] = mysql_escape($value);
}
return $escaped;
}
// else
if (get_magic_quotes_gpc()) $thing = stripslashes($thing);
return mysql_real_escape_string($thing);
}
foreach ($_REQUEST as $key => $value){
$_REQUEST[$key] = mysql_escape($value);
}
I find it much better to escape the data at the time it is used, not on the way in. You might want to use that data in JSON, XML, Shell, MySQL, Curl, or HTML and each will have it's own way of escaping the data.
Lets have a quick review of WHY escaping is needed in different contexts:
If you are in a quote delimited string, you need to be able to escape the quotes.
If you are in xml, then you need to separate "content" from "markup"
If you are in SQL, you need to separate "commands" from "data"
If you are on the command line, you need to separate "commands" from "data"
This is a really basic aspect of computing in general. Because the syntax that delimits data can occur IN THE DATA, there needs to be a way to differentiate the DATA from the SYNTAX, hence, escaping.
In web programming, the common escaping cases are:
1. Outputting text into HTML
2. Outputting data into HTML attributes
3. Outputting HTML into HTML
4. Inserting data into Javascript
5. Inserting data into SQL
6. Inserting data into a shell command
Each one has a different security implications if handled incorrectly. THIS IS REALLY IMPORTANT! Let's review this in the context of PHP:
Text into HTML:
htmlspecialchars(...)
Data into HTML attributes
htmlspecialchars(..., ENT_QUOTES)
HTML into HTML
Use a library such as HTMLPurifier to ENSURE that only valid tags are present.
Data into Javascript
I prefer json_encode. If you are placing it in an attribute, you still need to use #2, such as
Inserting data into SQL
Each driver has an escape() function of some sort. It is best. If you are running in a normal latin1 character set, addslashes(...) is suitable. Don't forget the quotes AROUND the addslashes() call:
"INSERT INTO table1 SET field1 = '" . addslashes($data) . "'"
Data on the command line
escapeshellarg() and escapeshellcmd() -- read the manual
--
Take these to heart, and you will eliminate 95%* of common web security risks! (* a guess)
If you have arrays in your $_REQUEST their values won't be sanitized.
I've made and use this one:
<?php
function _clean($var){
$pattern = array("/0x27/","/%0a/","/%0A/","/%0d/","/%0D/","/0x3a/",
"/union/i","/concat/i","/delete/i","/truncate/i","/alter/i","/information_schema/i",
"/unhex/i","/load_file/i","/outfile/i","/0xbf27/");
$value = addslashes(preg_replace($pattern, "", $var));
return $value;
}
if(isset($_GET)){
foreach($_GET as $k => $v){
$_GET[$k] = _clean($v);
}
}
if(isset($_POST)){
foreach($_POST as $k => $v){
$_POST[$k] = _clean($v);
}
}
?>
Your approach tries to sanitize all the request data for insertion into the database, but what if you just wanted to output it? You will have unnecessary backslashes in your output. Also, escaping is not a good strategy to protect from SQL exceptions anyway. By using parametrized queries (e.g. in PDO or in MySQLi) you "pass" the problem of escaping to the abstraction layer.
Apart from the lack of recursion into arrays and the unnecessary escaping of, say, integers, this approach encodes data for use in an SQL statement before sanitization. mysql_real_escape_string() escapes data, it doesn't sanitize it -- escaping and sanitizing aren't the same thing.
Sanitization is the task many PHP scripts have of scrutinizing input data for acceptability before using it. I think this is better done on data that hasn't been escaped. I generally don't escape data until it goes into the SQL. Those who prefer to use Prepared Statements achieve the same that way.
One more thing: If input data can include utf8 strings, it seems these ought to be validated before escaping. I often use a recursive utf8 cleaner on $_POST before sanitization.

Categories