Escape quote or special characters in array value - php

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

Related

line breaks showing up as \r\n in textarea

I am trying to display a data into textarea which is fetched from tables that i have submitted via another form. The issue comes up when a new line is entered.
The data getting displayed in the textarea is as
lin1\r\nlin2
it should be like
lin1
lin2
I have tried nl2br but it does not work as expected.
How can i make things optimized. Thanks
This problem can be solved using stripcslashes() when outputting your data.
Please note that the method above is different from stripslashes() which doesn't work in this case.
I tried using nl2br but it wasn't sufficient either.
I hope str_replace saves you.
<?php
$str='lin1\r\nlin2';
$str=str_replace('\r\n','<br>',$str);
echo $str;
OUTPUT:
lin1
lin2
This is a common question and the most common answers are ln2br or str_replace.
However this is just creating unnecessary code.
In reality the problem is pretty much always that you have run the data through a mysql escape function before displaying it. Probably while you were in the process of saving it. Instead, escape the data for saving but display an unescaped version.
<?php echo str_replace('\r\n', "\r\n", $text_with_line_breaks); ?>
See single quotes & double quotes this is a trick.
A perfect solution for newbies.
you overdo quote in insert/update statement
This problem in you case you can solve doing next
<?php
$str = 'lin1\r\nlin2';
$solved_str = str_replace(array("\\r","\\n"), array("\r","\n"), $str);
var_dump($str,$solved_str);
But you need to check insert/update statement on over quotation escape symbols
I would recommend using double quotes for \r\n such as "\r\n". I've never had it work properly with single quotes.
For non- textarea use this function
function escapeNonTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("<br>","<br","<br>"),$string);
return $string;
}
For text area use this function
function escapeTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("\n","\r\n","\r"),$string);
return $string;
}
call appropriate function and pass argument

Unescaping " In PHP Dynamically

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()

MYSQL Characters like ( ', ", &) etc. appear different

I'm keeping a database that is filled automaticlly by my users. but when there is an input like My Father's Will. It will get into the database like: My Father's Will.
This is not what I want. Can someone tell me how to enable these kinds of special characters or possibly a work around to not show these ugly characters to my users.
I'm using PHP, a MySQL server and PHPMyAdmin as DB Management tool.
It looks like the ' is escaped like a HTML character. I guess you're doing a wrong escaping, like using htmlentities instead of mysql_real_escape_string. If this info doesn't help, please post your code. It will be guessing without.
When you pull the values out of your database, use htmlspecialchars_decode(). This will convert all html special characters back into regular text.
$str = 'My Father's Will';
echo htmlspecialchars_decode($str);
will output:
My Father's Will
I can't really figure what you are asking, since "My Father's Will" and "My Father's Will" is exactly the same?
But it seems like a problem related to either string escaping in PHP or conflicting encoding in the MySQL-database, try to have a look into both and feel free to specify you question a bit more.
It sounds like you might be escaping (such as php's htmlentities()) your input on its way to the database. The correct thing to do would be to instead escape it only on output back to the screen.
Most likely you have a call to htmlspecialchars(..., ENT_QUOTES) in your code somewhere, which would encode ' and " into character entities. If they're in the database in encoded form, and the end-user sees the character entities, then you're doing a double-encoding and your script's output is something like &x27;.

Getting rid of \r\n strings

I have a form into which I entered a newline character which looked correct when I entered it, but when the data is now pulled from the database, instead of the white space, I get the \n\r string showing up.
I try to do this:
$hike_description = nl2br($hike_description);
But it doesn't work. Does anyone know how this can be fixed? I am using PHP.
And here is the page where this is happening. See the description section of the page:
http://www.comehike.com/hikes/scheduled_hike.php?hike_id=130
Thanks,
Alex
Does anyone know how this can be fixed?
Sure.
Your code doing unnecessary escaping, most likely before adding text to the database.
So, instead of replacing it back, you have to find that harmful code and get rid of it.
This means, you have probably plain text '\n\r' strings in the db.
Try to sanitize db output before display:
$sanitized_text = preg_replace('/\\[rn]/','', $text_from_db);
(just a guess).
Addendum:
Of course, as Col. Shrapnel pointed out, there's something fundamentally wrong
with the contents of the database (or, it is used this way by convention and you don't know that).
For now, you have fixed a symptom partially
but it would be much better to look for the reason for these escaped characters
being in the database at all.
Regards
rbo
You can use str_replace to clean up the input.
$hike_description = nl2br(str_replace("\r\n", "\n", $hike_description));
$hike_description = str_replace(array('\n','\r'),'',$hike_description);
You may want to read up on the differences between the single quote and double quote in PHP as well: http://php.net/manual/en/language.types.string.php

PHP Wrap a string in double quotes

I'm attempting to wrap a user-inputted string in double quotes for output but I want to make sure I don't end up with double double quotes on either side of the string. For example, if a user posts
"Hello"
I don't want to turn it into
""Hello""
I can do this fairly easily using the code below, however I'm concerned that this may get slow if I'm looping through lots of strings.
$string = '"'.trim($string,'"').'"';
If anyone has a better way of doing this, that'd be great. Equally, if anybody can confirm that my way is fine, I'll be happy.
Thanks
This is exactly how I would solve this problem. It's only worth worrying about the code being slow if you have a problem with the application being slow, and you can trace it down to the trim statements.
A well known programming quote is "Premature Optimisation is the root of all evil" - see the wikipedia article linked for more on this.
Make a careful consideration of what should happen with all the cases.
(using [] as quotes for readability)
You've said what you do for ["Hello"] but what do you do for [I said "Hello", punk]? Do you still strip the user-input quotes, or do you remove them? Or maybe go one step further and substitute single quotes for double quotes...but then you'd have to consider the cases where the user input contains both single and double quotes! What about when the user puts in "grammatically wrong" text like ["Hello] (no closing quote!).
Best way to ensure you do it right is to make a test case for each edge case you can think of and make sure your proposed solution actually does what is expected.
If the actually reason for this requirement is [I am taking a user's input at some point and then re-displaying it to them at another point, and don't want to show them stupid looking data like [""data""]], you'll probably just want to only remove double quotes from the start or end of the input string, because stripping them from the middle screws with the user's intended data.
If your goal is merely to clearly distinguish between their input and text that they didn't input, consider using other means of highlighting that instead of quotation marks. So instead of [you entered "data"], you could display [you entered data] or [you entered: data] which avoid this problem altogether.
Personally, I'd suggest stripping the quotes on input. As for making it faster, if you allow quotes to be entered or stored, you're always going to be stuck with using an if/else before displaying them.
Obviously, you'd still need to perform a sanity check of the input data regardless of whatever system you end up with.
I did it this way:
function quotize(&$string)
{
if (empty($string) || is_null($string)) {
return;
}
$char = '"';
if ($string[0] != $char) {
$string = $char . $string;
}
if (substr($string, -1) != $char) {
$string .= $char;
}
return;
}
It is common practice to use quotation marks to represent a quote within a quote, if you want to let your users write:
and she said "hey ho"
, which you could turn into:
User: "and she said 'hey ho'"

Categories