I am generating radio buttons based on an XML config values. Sometimes they have apostrophes in the text. When manipulating this data in PHP, I seem to lose everything after the apostrophe. For example:
<input type='radio' name='remove[]' value='Government wants to limit employers' communications about unionization'>
But when dumping it out after the form POSTs, I get this value:
array(1) {
[0]=>
string(35) "Government wants to limit employers"
}
Any suggestions on how to preserve the full string? Thanks!
use htmlspecialchars():
<input type="radio" ... value="<?php echo htmlspecialchars($array[0], ENT_QUOTES) ?>" ... />
It's explicitly intended to allow safe insertion of arbitrary text into html without 'breaking' the html. Note the 'ent_quotes' option. By default htmlspecialchars will only handle <>", but since you're using ', you need the option to tell htmlspecialchars to handle those too.
You can escape the quotes in the string: value='Government wants to limit employers' communications about unionization' Escaping it will cause this problem to stop.
PHP does give functions for this, in case your information is in a variable. Just use htmlspecialchars
Simplest way would be just to use double quotes like so:
<input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">
It's pretty much the reason for them.
I usually stick with those 2 easy options, both equally efficient:
You can encapsulate one type of quotes in the other type
$var = " here single quotes ' are encapsulated in double quotes";
$var = 'here double quotes " are encapsulated in single quotes';
you can escape quotes by using \
$var = "just quote some mathematician: \"quot erat demonstrandum\".";
You can use double quotes to surround the text:
<input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">
An even better way would be to replace the apostrophes with '.
<input type='radio' name='remove[]' value='Government wants to limit employers" communications about unionization'>
This is a more robust solution in case the text includes double quotes as well. You should replace all 's with 's and "s with "s.
This can be easily done using htmlspecialchars(string $str). http://php.net/manual/en/function.htmlspecialchars.php
Related
I am generating radio buttons based on an XML config values. Sometimes they have apostrophes in the text. When manipulating this data in PHP, I seem to lose everything after the apostrophe. For example:
<input type='radio' name='remove[]' value='Government wants to limit employers' communications about unionization'>
But when dumping it out after the form POSTs, I get this value:
array(1) {
[0]=>
string(35) "Government wants to limit employers"
}
Any suggestions on how to preserve the full string? Thanks!
use htmlspecialchars():
<input type="radio" ... value="<?php echo htmlspecialchars($array[0], ENT_QUOTES) ?>" ... />
It's explicitly intended to allow safe insertion of arbitrary text into html without 'breaking' the html. Note the 'ent_quotes' option. By default htmlspecialchars will only handle <>", but since you're using ', you need the option to tell htmlspecialchars to handle those too.
You can escape the quotes in the string: value='Government wants to limit employers' communications about unionization' Escaping it will cause this problem to stop.
PHP does give functions for this, in case your information is in a variable. Just use htmlspecialchars
Simplest way would be just to use double quotes like so:
<input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">
It's pretty much the reason for them.
I usually stick with those 2 easy options, both equally efficient:
You can encapsulate one type of quotes in the other type
$var = " here single quotes ' are encapsulated in double quotes";
$var = 'here double quotes " are encapsulated in single quotes';
you can escape quotes by using \
$var = "just quote some mathematician: \"quot erat demonstrandum\".";
You can use double quotes to surround the text:
<input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">
An even better way would be to replace the apostrophes with '.
<input type='radio' name='remove[]' value='Government wants to limit employers" communications about unionization'>
This is a more robust solution in case the text includes double quotes as well. You should replace all 's with 's and "s with "s.
This can be easily done using htmlspecialchars(string $str). http://php.net/manual/en/function.htmlspecialchars.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.
This may be a problem of my trouble with using single and double quotes in one statement. But I have this piece of code:
echo '<form>
<input type="submit" value="$number" onClick="function();">
</form>'
The problem with this is that the submit button says the phrase $number instead of the value of that variable.
So I looked around and found this solution:
echo "<form>
<input type='submit' value='$number' onClick='function();'>
</form>
This outputs the value of $number correctly, but I am used to using single quotes around my echo statements and would like to keep it that way. Why does just switching all single quotes into doubles, and doubles into singles fix the problem? And is there a modification to the first bit of code that would allow me to keep the single quotes on echo, and double quotes on the attributes?
In PHP, double quoted strings are automatically parsed for any variables contained within, but single quoted strings are not. Therefore:
$myVar = 21;
echo "myVar: $myVar"
This outputs the text: myVar: 21
Whereas:
$myVar = 21;
echo 'myVar: $myVar'
This outputs the text: myVar: $myVar
One problem with your code is that in HTML, the values of elements' attributes must be enclosed in double quotes, not single quotes. I know that some browsers will accept this form (or even no quotes at all), but this is not the correct method.
There are various ways of achieving what you wish, correctly.
Method one: Escaping double-quoted strings:
$myVar = 21;
echo "<div id=\"$myVar\"></div>";
While this may be a rather inelegant solution, it will work.
Method two: Using string concatenation with single (or double) quoted strings:
$myVar = 21;
echo '<div id="' . $myVar . '"></div>';
This offers a better solution IMO because you can use function calls or any other PHP code in there if you wish.
WARNING:
Please note that when you aren't certain of the contents of $myVar (i.e. the user enters it in), putting it directly into HTML code is a security vulnerability in the form of cross-site scripting (XSS). Imagine the user enters something like this:
lol"><script>alert('XSS!');</script></div><div id="lol2
This will cause the resulting HTML code to contain the following:
<div id="lol"><script>alert('XSS!');</script></div><div id="lol2"></div>
This is just a benign example, but an attacker could easily use the same technique to steal a user's cookies (to pretend to be logged in as that user). The message here is that when you aren't 100% sure of the contents of a variable, don't insert it into HTML code directly. Instead, call htmlspecialchars($myVar). This would translate to the following:
$myVar = $_POST['whatever'];
echo '<div id="' . htmlspecialchars($myVar) . '"></div>';
In PHP, variables inside double quotes are processed and evaluated, while in single quotes everything is considered as part of the string.
A better explanation here:
http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
double quote example from the above link:
$something="Oh something";
echo "My answer is $something.<br>";
//result is: My answer is Oh something
single quote example from the above link:
echo 'My answer is $something.<br>';
//result is: My answer is $something.
When you use the single quote, everything inside is taken literally, except single quotes. When using double quotes, anything starting with a dollar sign ($) is assumed to be a variable by PHP. When using variables, I usually like to start the echo with a double quote.
If you want to keep using single quotes, you'll need to use the append operator (a period).
echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';
You could just do this and avoid the whole song and dance. I think it is easier to read.
<form>
<input type="submit" value="<?php echo $number; ?>" onClick="myFunction()">
</form>
This outputs same to me
echo '<link rel="apple-touch-icon-precomposed" sizes="57x57" href='. ${base_url_favicon} . '/apple-touch-icon-57x57.png />'."\n";
echo "<link rel='apple-touch-icon-precomposed' sizes='57x57' href='${base_url_favicon}/apple-touch-icon-57x57.png' />\n";
PHP differentiates between single and double quoted strings as being different things. Single quoted strings are literals, you want them output as is. Double quoted strings are to be interpreted (scanned) for any PHP variables and the appropriate replacements made.
This is simply a feature (and a useful one) of the language. I would actually recommend that you get used to using double quotes for strings in all languages. There is no language where it is unacceptable and in staticly typed languages (C, C++, Java, ...) single quotes indicate a character while double quotes indicate a string. That is, String foo = 'my string'; would error in Java as would char * foo = 'my string'; in C or C++. However, char foo = 'a'; is valid, as is String foo = "my string";
Only if you need to eke out the last nanoseconds of performance from PHP might you go through and convert double quoted strings to single quoted strings. In other languages it doesn't matter. Afaik, PHP is the only language that make this string specific double vs. single quotes distinction.
PHP performs what is called variable interpolation on double-quoted strings, which means that the strings are searched for any variables that they might contain, whose values are substituted in the string. If you want to keep the single quotes, you will need to concatenate your strings and variables together like so:
echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';
Or, if you want to keep the double quotes, you can escape the double quotes that you want to print:
echo "<form>
<input type=\"submit\" value=\"$number\" onClick=\"function();\">
</form>"
I am accepting a preset input from another .php file
$Instructor=$_POST["Instructor"];
when I echo $Instructor, the OUTPUT is Dr. Doom (which is correct)
When i pass it through a fieldset I only get the (Dr.) and not the (Doom). I need for the entire name to get passed. Can any one please help. I am NEW TO PHP, so please try to explain in simple form. Thank you very much ahead of time.
here is the code i am using.
echo "<fieldset>
<Legend> Contact Information </Legend>
PROFESSOR: <inputname='Professor' type= 'text' value=$Instructor maxlength='35'
disabled='disabled'> </fieldset>"
Sincce you've omitted quotes on HTML attribute, only characters up to the first whitespace will be interpreted in your html. Quote the attribute, and escape it properly with htmlentities() using the ENT_QUOTES option:
echo "<fieldset ... ... value='" . htmlentities($Instructor, ENT_QUOTES) . "' ... </fieldset>";
Note that without the escaping, it is vulnerable to cross-site scripting, in addition to potentially breaking the output markup.
You need to put quotes around attribute values that contain spaces. In your case they need to be escaped, because the PHP string literal also uses them:
echo "... value=\"$Instructor\" ...";
Variable sanitization aside, you forgot to quote this:
value=$Instructor
And mind the space here:
type= 'text'
By the way, There's a nice syntax in PHP called "heredoc" if you want to use blocks of HTML text.
$str = <<<EOF
<fieldset>
<Legend> Contact Information </Legend>
PROFESSOR: <inputname='Professor' type='text' value='$Instructor' maxlength='35' disabled='disabled'>
</fieldset>
EOF;
What's nice is the text can stay human readable and still support inline variable interpolation (putting "$something like this")
I do not want to display all the slashes when displaying the html
What I have is
echo "<input type=\"text\" name=\"myname\" value=\"myvalue\"";
What I want to do is:
echo '<input type="text" name="myname" value="myvalue">';
I am looking to save myself from typing all the slashes. Is there a way around that?
Your second example works (although it is ugly), I assume you want a way to be able to print variables while printing the HTML with double quotes. If that's the case, you could use Heredoc syntax:
echo <<<DOC
<input type="text" name="myname" value="myvalue">
DOC;
Or, better, yet, you could use a templating system (which PHP kind of is) or a MVC framework to separate your business and presentational logic so you don't have to go around printing stuff like input fields in the first place. :)
You probably don't want to echo stuff really, and Paolo explained that quite well, but in general the best practice regarding apostrophes and quotation marks is as follows:
When you have apostrophes ' in the text, enclose it in double quotes "
echo "foo bar 'baz'";
When you have double quotes, enclose in apostrophes
echo 'foo bar "baz"';
This way you don't have to clutter it with backslashes. If you have both kinds, consider heredoc as per Paolo's example, or just stick to the style the rest of the code usually uses.
As to what comes to using apostrophes in HTML instead of double quotes.. While swapping them might be useful when you want to include variables, it would be more beneficial to always keep the same style - always apostrophes, or always double quotes.
You can also use printf (or sprintf), a function which often seems to be forgotten by PHP programmers:
printf('<input type="text" name="myname" value="%s" />', $value);
Your second example works just fine. However, if you want you can use single slashes to quote the HTML, it will still come out valid. This would also allow you to quote variables:
echo "<input type='text' name='myname' value='$value' />";
Do not forget you can also do something along the lines of:
/* PHP CODE */
?>
--- HTML HERE ---
<input type="text" name="myname" value="myvalue">
<?php
/*PHP CODE */
Typically I use the second example with apostrophes.
<?php
echo '<input type="text" name="myname" value="myvalue">';
?>
As Paolo has mentioned, you can also look into an MVC based framework. Which is Model-View-Controller. It is a very nice way to separate your Display Code (Presentation Logic) from your Functional Code (Business Logic).
A good starter MVC Framework is CodeIgniter. Check out their video tutorials to get a good idea of how these frameworks operate. There is somewhat of a learning curve but it will help you out in the long run!
Other Frameworks and Template Systems:
Zend
Smarty
Cake PHP
Best of Luck!
If you have any questions feel free to leave a comment.
echo '<img src="'.$files[$i].'">';