Single and double quotes together as HTML attribute value? - php

We have a code like this:
echo '<input type="text" name="myInput" value="Double " Quotes" />';
Absolutely it doesn't work because the quote after Double ends the value.
We can fix it by using single quotes instead of double ones.
echo '<input type="text" name="myInput" value=\'Double " Quotes\' />';
Now I wanna use both single and double quotes as the value. It should outputs She said:"I don't know."
Is there a way to fix it WITHOUT using HTML entities (Like "), htmlentities() or similar functions?

Is there a way to fix it WITHOUT using HTML entities (Like "), htmlentities() or similar functions?
No, there is not. The double quote (") has special meaning inside a HTML attribute. If you want to put it into an attribute value, you must (this is not a true must but a good rule of thumb. It's a must if you use attributes delimited by double-quotes as you do in your question) write it as its entity ". There is no way around it.
Actually even <tag attr='this"'> is not wrong HTML, too and most browsers can deal with that. However it doesn't help you because you're looking for both quotes - single and double - and one of these always in HTML is a delimiter of the attribute value - if you need spaces inside the attribute value (as you do).
However, do not worry about that. It works, and you can express everything you like with that, including the combination of quotes you have.
And actually PHP is there for you to take the burden of "escaping" all those characters just with the htmlspecialchars method doing all the work for you. Inside a PHP string you have the original text - with single and double quotes as you see fit - verbatim.
$myString = 'She said: "I don\'t know."';
printf('<input type="text" name="myInput" value="%s" />'
, htmlspecialchars($myString));
Just a shortened example that should demonstrate how this works. Online demo.

To address the question in the title, there is no problem with using both " and ' in an attribute value. The problem arises in linearization of values, i.r. writing them in HTML markup (as opposite to generating them with client-side JavaScript). Then, if the value contains both " and ', either of them needs to be escaped, depending on which one you use as value delimiter.
You do not need to use entity references, though. The character references " and ' (or the equivalent decimal references) can be used, too.
In the case of the string
She said: "I don't know."
the correct English spelling is
She said: “I don’t know.”
Using the correct punctuation marks, no markup problem arises, since you can use the Ascii quotation mark " or the Ascii apostrophe as delimiter. They are meant for use in computer languages, not in human languages.

Related

Is it safe to concatenate a double quoted to a single quoted string?

Are there any issues I should be aware of when doing the following:
$table_html = ' <td id="unescaped-double-quotes-yay">Some stuff</td>' . "\n";
I do not like escaping double quotes withing HTML and I can't stand using single quotes in HTML, my solution is what I have above. Am I going to run into any issues with this practice?
You MUST escape strings that comes from DB or from the user because they could easily break you concatenation if the unexpected kind of quote is present in that string (not to mention that you MUST cleanse anything that comes from the user for minimal security).
Other than that you can concatenate strings any way you like. Still, life will always be easier if you manage to use them cosistently the same way.
I have done this many times on client sites (have since found better alternatives), you are 100% fine.
Are you aware of the following representation:
$table_html = <<<HTML
<td id="unescaped-double-quotes-yay">
Some stuff, and i can use normal newlines here
</td>
HTML;
It is called "heredoc", and you must keep in mind that the final string must be equivalent to the opening one, and must be the only thing on the line (no spaces or even comments are allowed).
You must also terminate the last line with the newline, even if it is the last line in the file.
To read more about it click here

Is it possible to create a hyperlink to a page that has Double quotes within the path?

I want to create hyperlinks to pages on my site but the page address have double quotes within them?
Eg:
the above just links to mysite.com/search.php?q= as I would expect as it is written.
The API returning results allows phrase searches by placing them in double quotes.
Is there a way to escape these within the href tag?
Simple solution: use altenative quotes:
<a href='mysite.com/search.php?q="sales+manager"&l=usa'></a>
This will work fine (the browser will make sure the URL gets properly formatted when a user clicks it), but you should really be urlencoding special characters because there's a whole bunch of stuff that you're not allowed to use in URLs, and some stuff that has a different meaning (in a URL, spaces become +, for instance, so you can't drop in a + and get it to stay that once you parse it. URL magic!).
Have a look at urlencode and use that when generating the link URL server side. This will turn things like spaces into %20, double quotes into %22, etc., and is how you send literal string data from a client to a server.
Yo must encode the quotes &quot
mysite.com/search.php?q="sales+manager"&l=usa
Is there a way to escape these within the href tag?
Yes, with the escape character. \.
Although, the current state of your code would produce:
effectively breaking the href since you are breaking the string.
What you want, is just:
...
you are considering whether the characters need to be escaped in order to work in your HTML.
however, you should also consider whether they need to be escaped in order to be sound URLs.
to work in your HTML you may do
<a href="mysite.com/search.php?q='sales+manager'&l=usa">.
however, the ' character cannot be in a URL.
"Uniform Resource Locators may only contain the displayable characters in the standard ASCII character set. Nondisplayable characters or characters in the extended ASCII set (128 through 255) are specially encoded."
See here for a list of URL escape codes.
perhaps you want to retain the quotes in the get-request of your URL. in that case, you might want:
<a href="mysite.com/search.php?q=%22sales+manager%22&l=usa">

MySQL Data Into Value Attribute? (Quotes)

Alright, so there's still stuff I have yet to learn about PHP. I'm trying to retrieve data from a MySQLi database and it's all fine until I'm forced to choose between double quotes or single quotes breaking something. With real_escape_string, I can store string data that contains a single quote, and it just gets escaped with a backslash, but if I don't use stripslashes() when I insert it into the value attribute...
If my value attribute looks like this in the code: value="_" then double quotes within the string, trim any data after it because it seems to be interpretted as the end of the value attribute.
If my value attribute looks like this in the code: value='__' then if I don't use stripslashes(), I see the slashes in the output, and if I use stripslashes(), it's the same thing with the double quotes, but with any of the escaped single quotes within the string.
Hope this makes sense. I'm fairly tired right now, but with a few replies and questions asked for anyone who doesn't quite understand, I'm sure we can figure this out. :)
If you have to output data into html which might have special characters use htmlspecialchars
<input type="text" value="<?php echo htmlspecialchars('\'"&<>') ?>">
http://codepad.org/DxV3uq0L
http://jsfiddle.net/Uu29D/

Escaping string before assigning to innerHTML echoed by PHP

I'm encountering a problem involving escaping character that I think it's not simple at all. If this is done in javascript, nothing to say but the context is using echo command (in PHP) to write javascript code like this:
echo "<script>document.getElementById('spanID').innerHTML=\"$x\"</script>";
$x is a variable in PHP environment, which can contain both single and double quotes. What I do here is:
1. Keep the $x not change, and if $x contains any double quote, the above code won't work, the text echoed may look like:
<script>document.getElementById('spanID').innerHTML="leftside"rightside"</script>;
I supposed $x = leftside"rightside, and you can see it surely won't work.
Escape the double quotes in $x (change all " to "), then the text echoed may look like this:
document.getElementById('spanID').innerHTML="leftside"rightside";
The " won't be converted to " when it is assigned to innerHTML attribute of a Span (for e.g), so instead of my want, the innerHTML of my SPAN should be leftside"rightside, it will be leftside"rightside.
If I change the " to ' in the original echo, like this:
echo "<script>document.getElementById('spanID').innerHTML='$x'</script>";
It is the same because $x here can contain both single and double quotes.
I don't find out any other ways to escape quotes in this case. Could you please help me out?
Thanks!
You need to put between the quotes a string that is a valid string of JavaScript containing valid (and safe) HTML.
Your best option is to not use innerHTML and instead use document.createTextNode which means you only need to slash-escape the content.
Otherwise, you need to HTML escape, then slash escape the content. For correctness, your slash-escaping function should escape at least double-quotes, backslashes, and all JavaScript newlines (U+A, U+D, U+2028, U+2029). I believe PHP's addslashes does not handle U+2028 or U+2029 by default but How to escape string from PHP for javascript? has some alternatives.
To put it all together:
$x_escaped = json_encode($x, JSON_HEX_TAG);
echo "<script>document.getElementById('spanID').appendChild(document.createTextNode($x_escaped))</script>"
should do it. The JSON_HEX_TAG makes sure that $x_escaped will not contain </script> or any other content that prematurely ends your script tag. </script> will instead become \u003c/script\u003e.

Apostrophe issue

I have built a search engine using php and mysql.
Problem:
When I submit a word with an apostrophe in it and return the value to the text field using $_GET the apostrophe has been replaced with a backslash and all characters after the apostrophe are missing.
Example:
Submitted Words: Just can't get enough
Returned Value (Using $_GET): Just can\
Also the url comes up like this:search=just+can%27t+get+enough
As you can see the ' has been replaced with a \ and get enough is missing.
Question:
Does anybody know what causes this to happen and what is the solution to fix this problem?
The code:
http://tinypaste.com/11d62
If you're running PHP version less than 5.3.0, the slash might be added by the Magic Quotes which you can turn off in the .ini file.
From your description of "value to the text field" I speculate you have some output code like this:
Redisplay
<input value='<?=$_GET['search']?>'>
In that case the contained single quote will terminate the html attribute. And anything behind the single quote is simply garbage to the browser. In this case applying htmlspecialchars to the output helps.
(The backslash is likely due to magic_quotes or mysql_*_escape before outputting the text. I doubt the question describes a database error here.)
Update: It seems it's indeed an output problem here:
echo "<a href='searchmusic.php?search=$search&s=$next'>Next</a>";
Regardless of if you use single or double quotes you would need:
echo "<a href='searchmusic.php?search="
. htmlspecialchars(stripslashes($search))
. "&s=$next'>Next</a>";
(Notice that using stripslashes is a workaround here. You should preserve the original search text, or disable the magic_quotes rather.)
Okay I forgot something crucial. htmlspecialchars needs the ENT_QUOTES parameter - always, and in your case particularly:
// prepare for later output:
$search = $_GET['search'];
$html_search = htmlspecialchars(stripslashes($search), ENT_QUOTES);
And then use that whereever you wanted to display $search before:
echo "<a href='searchmusic.php?search=$html_search&s=$next'>Next</a>";
Single quotes are important in PHP and MySQL.
A single quote is a delimeter for a string in PHP, for example:
$str = 'my string';
If you want to include a literal quote inside a string you must tell PHP that the quote is not the end of the string. It is escaped with the backslash, for example:
$str = 'my string with a quote \' inside it';
See PHP Strings for more on this.
MySQL operates in a similar way. An example query might be:
$username = 'andyb';
$quert = "SELECT * FROM users WHERE user_name = '$username'";
The single quote delimits the string parameter. If the $username included a single quote, this would cause the query to end prematurely. Correctly escaping parameters is an important concept to be familiar with as it is one attack vector for breaking into a database - see SQL Injection for more information.
One way to handle this escaping is with mysql_real_escape_string().

Categories