Unescaping " In PHP Dynamically - php

There is a page that I'm currently working on (http://www.flcbranson.org/freedownloads-new.php) that loads data from an rss feed.
That rss feed contains descriptions, some of which contain quotation marks.
When the page is displayed (you can click on the Read Summary link for Filled With All The Fullness Of God to see what I'm talking about), it does \" for each quote.
I assume that it's because of php's escaping requirements.
Is there a way that I can remove the escape character (other than the obvious "remove the quotation marks")?

Sounds like you have magic quotes turned on. Read the PHP documentation for stripslashes() and pay special attention to the magic quotes stuff.
In a nutshell, if you know that your working with a string and not (say) an array, you can do the following:
if (get_magic_quotes_runtime()) {
$string = stripslashes($string);
}
If the data is coming from $_GET, $_POST, or $_COOKIE superglobals, use this instead:
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
If it's not a string you're dealing with, you may need to look at the stripslashes_deep() implementation in the PHP docs.

You need to remove the slashes by running data through:
stripslashes()
However, you still want to make your output (if you are doing something with this) HTML safe.
so run this function on the data after:
htmlspecialchars()

try using stripslashes()
http://www.php.net/manual/en/function.stripslashes.php

checkout stripslashes()

Related

HTML forms, php and apostrophes

Doing a uni assignment with HTML, XML and php 5.3 (no SQL). Building a review website. I have a textarea in which the user can place their comments. If the user enters an apostrophe, eg World's Best Uni!, when I echo $_REQUEST['reviewtext'] I get World\'s Best Uni!
To massage the data for saving in the XML, I have the following code:
$cleantext1 = htmlspecialchars($_REQUEST['reviewtext']);
substr_replace($cleantext1,"\'","'");
$cleantext2 = strip_tags($cleantext1);
$cleantext3 = utf8_encode($cleantext2);
I have echo's at each step an the quote remains World\'s Best Uni! at each step.
I expected the one of the first two lines to replace the escaped apostrophe with an html code but it doesn't seem to work.
Interestingly, this problem doesn't happen on my local XAMPP server; only on my hosted website.
Any suggestions?
Thanks,
Sean
What you are experiencing is PHP's Magic Quotes feature which is automatically escaping input from GET, POST, COOKIE. It is not wise to rely on this feature, and is deprecated as of PHP 5.3, and tends to default to off on most configurations (but not in your Uni's config).
You can use get_magic_quotes_gpc() to determine if this is turned on, and if so, unescape the data.
if (get_magic_quotes_gpc()) {
$val = stripslashes($_POST['val']);
} else {
$val = $_POST['val'];
}
The magic quotes reference goes into more detail on the history, usage, and how to deal with magic quotes.
Also, just an aside, when you output data, always make sure you escape it (e.g. htmlspecialchars() and when you process input from any untrusted source, make sure to filter it (e.g. addslashes(), mysql_real_escape_string()).
Try switching off magic quotes (a PITA IMO!). (as posted above while I was typing my response drew's method would be the most flexible for portability.
By the way, no need to declare new variables if you aren't going to process variables different ways. so after you clean the text with htmlspecialchars, I would toss it into $cleanreview. Also you are not specifying a character encoding which can come back to bite you. I use UTF-8 since it seem like the most forward thinking encoding that's already widely supported.
http://www.php.net/manual/en/function.htmlspecialchars.php
BTEW, I'm a stickler for proper punctuation too so in my code I replace the html entities on output:
$syn = str_replace("'", "’", $syn);
$syn = str_replace("“", "“", $syn);
$syn = str_replace("”", "”", $syn);
$syn = str_replace(" -- ", "—", $syn);
But of course that's assuming UTF-8 being declared in your html (first item after the tag for speed).
This effect of automatical escaping of some characters is called "magic quotes" and can be turned on/off in the php.ini configuration file. Apparently, in the configuration of your local server it is turned off, while on the server it is on.
For more info, just consult the PHP reference for "magic quotes".

PHP submitting forms, escaped quotes?

If I have a form with a value of just "" and I submit it and echo it with PHP, I get \"\"
How can I get around this?
This is because magic_quotes_gpc is on. This is a bad 'feature', designed to automatically escape incoming data for those developers who can't learn to escape SQL input.
You should disable this as soon as possible.
ini_set('magic_quotes_gpc', 'off');
You should switch off magic_quotes_gpc, which is a broken feature (see Delan's answer, I completely agree).
But wait! You must sanitize the user input from $_REQUEST, $_POST and $_GET and $_COOKIE, if you want to use it for database or display at your page! Otherwise your code would be prone to various types of attacks!
There is nothing like "universal sanitization". Let's call it just quoting, because that's what its all about.
When quoting, you always quote text for some particular output, like:
string value for mysql query
like expression for mysql query
html code
json
mysql regular expression
php regular expression
For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (always assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)
mysql_real_escape_string(addcslashes($str, "%_"))
htmlspecialchars($str)
json_encode() - only for utf8! I use my function for iso-8859-2
mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!
preg_quote()
Try stripslashes().
stripslashes() is the opposite of addslashes(), and removes escape slashes from strings.
You can use stripslashes() function.
http://php.net/manual/en/function.stripslashes.php
This behavior is caused by the "Magic Quotes" PHP-Feature. http://php.net/manual/en/security.magicquotes.php
You can use something like this to make it work whether magic quotes are enabled or not:
if (get_magic_quotes_gpc()) {
$data = stripslashes($_POST['data']);
}
else {
$data = $_POST['data'];
}
I always use this method as it grabs the value as a string and therefore there will be no slashes:
$variable = mysql_escape_string($_REQUEST['name_input']);

keep textarea input format after using mysql_real_escape_string to store

I am using php5.3.6 and mysql 5.1.56 and CodeIgniter. Here is what I did.
Input some text in textarea, something like this:
what's this?
I'm bob.
$string = $_POST['name'];
$insertdata = mysql_real_escape_string($string);
Insert $insertdata into database.
It shows "what\'s this?\n\n\nI\'m bob."(without double quotes) in the table.
Query the data stored in database, use stripslashes on it and then put it back to the textarea.
It shows "what's this?nnnI'm bob."(without double quotes) in the textarea.
My questions are:
In step 4, shouldn't it be "what\'s this?\n\n\n I\'m bob." stored in the table?
I checked php manual. It says:
mysql_real_escape_string() calls
MySQL's library function
mysql_real_escape_string, which
prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and
\x1a.
How am I supposed to keep the textarea input format after using mysql_real_escape_string()?
Is there anyway to choose which slash to strip and which not to?
Notes:
magic quotes option is off
I did not use stripslashes() before
using mysql_real_escape_string()
If I use addslashes() instead of
mysql_real_escape_string(),
everything works fine.
I don' want to use addslashes() since
it is not as secure as
mysql_real_escape_string(), as far as
I know.
Thanks,
Milo
This really does feel a lot like magic_quotes_gpc = On. Are you disabling it in php.ini or at runtime? It needs to be the former, otherwise it'll remain on.
http://www.php.net/manual/en/security.magicquotes.disabling.php
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Short answer:
// double quotes are *very* important, or chars are not interpreted
$text_from_db=str_replace("\\r","\r",str_replace("\\n","\n",$text_from_db));
Long answer
Pretty simple but tricky.
You write your textarea and hit the "return" key, there is placed a \r\n (on Windows systems) with slashes that escape the "r" and "n" letter rising their special meaning of carriage return and newline.
You actually can't see them because they are "not printable" chars.
The slash char itself (0x1B) is invisible, that is a single slash is a "not printable" char, to make it visible you have to "transform" it in a printable slash char (0x5C) and to achieve that you have to double it "\\".
Now back to the question: if you can read the slash, probably that's beacuse that slash is not the 0x1B but rather 0x5C, so the "n" and "r" lose their special meaning and you get them as mere strings.
The code I posted does this conversion, converting the "[0x5C]n" string in a "[0x1B]" char.
Notes
Hope this helps, it did for me. IMPORTANT : it is not normal that the text that comes from the db has this issue if it has been stored correctly. My suggestion is to triple check insertion and retrieving because (given from the issue) you could be applying the quoting twice somewhere.
The Best Solution..
$insertdata = mysql_real_escape_string($string); (You can insert it in your database if you want)
echo stripslashes(str_replace('\r\n',PHP_EOL,$insertdata)); (The output is exactly as your input was)
You must escape data before inserting it into the database, to ensure you do not produce broken queries and to avoid SQL injections.
However, when you retrieve that data via a SELECT, you'll receive the data unescaped, ready to be used.
MySQL escapes the string, but when displaying the result back to you it will give you the same result as if it was unescaped.

Escape quote or special characters in array value

In my PHP code, I'm setting up an area for people to enter their own info to be displayed. The info is stored in an array and I want to make it as flexible as possible.
If I have something like...
$myArray[]['Text'] = 'Don't want this to fail';
or
$myArray[]['Text'] = "This has to be "easy" to do";
How would I go about escaping the apostrophe or quote within the array value?
Thanks
Edit: Since there is only a one to one relationship, I changed my array to this structure...
$linksArray['Link Name'] ='/path/to/link';
$linksArray['Link Name2'] ='/path/to/link2';
$linksArray['Link Name2'] ='/path/to/link3';
The plan is I set up a template with an include file that has these links in a format someone else (a less technical person) can maintain. They will have direct access to the PHP and I'm afraid they may put a single or double quote in the "link name" area and break the system.
Thanks again.
POSSIBLE SOLUTION:
Thanks #Tim Cooper.
Here's a sample that worked for me...
$link = "http://www.google.com";
$text = <<<TEXT
Don't you loving "googling" things
TEXT;
$linksArray[$text] = $link;
Using a heredoc might be a good solution:
$myArray[]['Text'] = <<<TEXT
Place text here without escaping " or '
TEXT;
PHP will process these strings properly upon input.
If you are constructing the strings yourself as you have shown, you can alternate between quotation styles (single and double)...as in:
$myArray[]['Text'] = "Don't want this to fail";
$myArray[]['Text'] = 'This has to be "easy" to do';
Or, if you must escape the characters, you use the \ character before the quotation.
$myArray[]['Text'] = 'Don\'t want this to fail';
$myArray[]['Text'] = "This has to be \"easy\" to do";
If you really want to make i easy, use a separate configuration file in either INI or XML style. INI is usually the easiest for people to edit manually. XML is good if you have a really nested structure.
Unless you are letting users enter direct PHP code (you probably aren't), you don't have to worry about what they enter until you go to display it. When you actually display the info they enter, you will want to sanitize it using something like htmlentities().
Edit: I realize I may be misunderstanding your question. If so, ignore this! :)
You can use the addslashes($str) function to automatically escape quotes.
You can also try htmlentities, which will encode quotes and other special values into HTML entities: http://php.net/manual/en/function.htmlentities.php

Strip out all single quotes

I am looking for the best way to strip single quotes as it keeps breaking my important.
so
The image’s emotiveness enables
only comes through as
The image
It breaks at the single quote ' .I need a good way to strip out the tags can someone help.
I have looked at stripslashes();
Whats the best way function to stripout , - £
any help please.
MANAGED TO FIX IT>
Thank you for your help people i manage to fix it using the following function.
string utf8_encode ( string $data )
Cant figure out why it was coming out in that format from the database all i can think is it 6 years old website.
;)
I'm not 100% certain because PHP isn't my forte, but I think you need to look at something like urlencode(). This will encode all the special characters properly.
Note: This will remove all single quotes!
str_replace("'", "", $your_string);
example:
$your_string = "The image’s emotiveness enables.";
echo str_replace("'", "", $your_string);
output
The images emotiveness enables.
If you want to keep single quotes in string you should consider using real escape functions (recommended).
It sounds like what you really want is to encode the single quotes, not remove them. On the assumption that you are inserting into the MySQL database, look into mysql_real_escape_string.
The best way to get rid of specific characters is using str_replace.
To remove all single quotes from a string:
$noQuotes = str_replace("'", '', $stringWithQuotes);
There is several ways, depending on what are you doing.
You could use addslashes to escape all single / double quotes. You can unescape it with stripslashes later.
If you are planning on saving those data into MySQL database, you should use mysql_real_escape_string.
If you want to output data on HTML page, use htmlspecialchars to convert all special characters into HTML entities.
The next way is to use str_replace to remove all quotes, as few other people in this thread already mentioned.

Categories