I am having an issue where a PHP variable's value from a MySQL database is breaking my HTML syntax.
<?php
echo '<a style="cursor: pointer;" onclick="openContentWindow(\''.$row['creativeStrengths'].'\')">Open content</a>';
?>
If the string contains a " or ' it will break my string and give an error.
Is there any way to escape the characters in HTML? Or if there is a way to use javascript/jquery in this situation that's fine too.
The value of $row['creativeStrengths'] is a string by the way hence the single quotes around it.
Thanks!
EDIT: I solved my issue by using addslashes(). Sorry that my question may not have been specific enough. Your answers were most likely right however I may not have clarified enough.
The escape code for " is " and the escape code for ' is '. The entity name for the former is ", but I don't know if there is one for the latter.
Source
Try:
htmlspecialchars($row['creativeStrengths'])
It will escape any HTML character.
I solved my issue by using addslashes().
addslashes($row['creativeStrengths']);
Related
So I am trying to link using data I got from a function but it keeps giving me a blank value for ID. Here's my code for what I'm trying to print
<h3 style="text-align: center;">Seller: <?php $sellername =
getNameFromListingID(); $id = getIDByUsername($sellername); echo "".$sellername."";?></h3>
The functions work properly, I have tried printing both of them and it works. They're in a file called getinfo.php, which I have
Include 'getinfo.php';
At the top of my document.
The link with the name works but I always get seller.php?id=, with no value after. Any clue as to why?
You're ending the href attribute too early.
<a href=\"seller.php?id=".$id."\">
This will put the $id inside the href attribute, where it belongs.
Use single quotes in PHP, it's a good practice to get into, and it's also slightly (a teeny tiny bit) faster for PHP to process. Why? Because, when you use double quotes, you're telling PHP that your string contains variables that may need to be evaluated.
So in truth, you don't even need the quotes around variables here.
echo "$sellername";
But doing it like this would be following a best practice.
And now you don't need to escape \" double quotes that HTML uses.
echo ''.$sellername.'';
Caution: It's also a very good idea to escape special characters in anything you're outputting into HTML markup. That avoids the potential for an XSS vulnerability. See: htmlspecialchars()
echo ''.htmlspecialchars($sellername).'';
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
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 question already has answers here:
single quote inside double quote in php
(3 answers)
Closed 9 years ago.
The below outputs
href="javascript:showBed(" a114:1')'
when I want it on the form
href="javascript:showBed('A114:1')"
in order to get javascript to work. I had a look at this site but coudn't get it to work so I gave up. Perhaps you could give me a hint on how the corrent syntax would be?
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' target='main' class='larmlink'>link</a>");
Thanks =)
Your output is not what it would output, but it is how it would be interpreted (HINT: don't look at a parsed DOM tree, look at the source).
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' ...
==>
echo("<a href=\"javascript:showBed('" . $row['Bed'] ."')\" ...
You really should be using the more standard double quotes around HTML element properties. As such, it is probably best to use single quotes in PHP. I would suggest this:
echo('link');
To print the double-quote character, you can escape it by doing \"
echo("<a href=\"javascript:showBed('" . $row['bed'] ."')\" target='main' class='larmlink'>link</a>");
Live demo
When you want to output variable data to JavaScript, it is good to use json_encode() so that all special characters are escaped automatically. The htmlspecialchars() escapes any values for use in the HTML attribute value.
echo '<a href="',
htmlspecialchars('javascript:showBed(' . json_encode($row['Bed']) . ')'),
'" target="main" class="larmlink">link</a>';
Note that I use single quotes for PHP string literals so that PHP doesn't have to search through my string for a variable to replace. You don't have to do this, but I recommend it.
I like to use sprintf (or printf, but sprintf is easier to refactor) for long strings like this so it's easy to see the template:
echo sprintf("<a href='javascript:showBed(\"%s\")' target='main' class='larmlink'>link</a>", $row['Bed']);
I'd also consider using addslashes on the $row['Bed'] variable in case it has quotes in it.
Using the heredoc syntax often makes code with mixed quotes easier to understand:
echo <<<EOD
link
EOD;
As others mentioned, if the value of your $row['Bed'] might contain single or double quotes, you have to escape it with addslashes.
You can use the heredoc syntax to avoid to escape anything:
echo <<<LOD
link
LOD;
Notice that if your variables contains some quotes you must use the addslashes function or str_replace before.
Another good practive is to separate systematically all the html content from php code:
<a href="javascript:showBed('<?php
echo $row['Bed'];
?>')" target="main" class="larmlink">link</a>
try this one:
echo("<a href='javascript:showBed(\"" . $row['Bed'] ."\")' target='main' class='larmlink'>link</a>");
I am trying my best to work this out and it is driving me crazy, I am hoping that I can use either preg_replace or ereg_replace for this.
Basically I am putting out string of text which is taken from a news article, I am taking the first 100 characters rounded to the closest end of word, the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail. So I need to write some kind of replace code so that all " and ' will be replaced with \" and \' so they are escaped and don't affect my PHP.
Update
I cannot correct anything to do with database insertion as I am dealing with a very old archive of data which I cannot process and re-enter into the database so I'm stuck with what I have got there.
This is the code I have:
$text = preg_replace('/\s+?(\S+)?$/', '',substr($text, 0, 100));
echo '<div style="color: #8197cd;" >'.$text.'...</div>';
So that takes my text, shortens it and puts it to the nearest word.
Then I am trying to do something along the lines of:
$text = preg_replace("\"","\"",$text);
$text = preg_replace("\'","\'",$text);
But preg_replace is not a strong point of mine so that is completely wrong!
the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail.
You're trying to fix a problem that shouldn't be there in the first place - most likely unescaped input in a mySQL query. You need to fix that instead (it's also a security problem).
Show the code that breaks, I'm sure someone will be able to point out what needs to be done.
Something seems to be missing from your question. You should consider posting the code that is having a problem.
Having quotes inside a variable you are echoing out is not going to fail. The only thing I could imagine causing an error would be if you were using some sort of template system or code that was taking the string and using it to do an eval() somewhere, but that would be a very poor system.
If you are inserting the string into a database, then you would need to escape those characters, as mentioned by SiteSafeNL.
If an eval is the source of the problem, then htmlentities which he also suggested would fix it.
Added based on latest additions to the question
Please try this:
echo '<div style="color: #8197cd;" >'. htmlentities($text) . '...</div>';
And the preg_replaces are not useful, so simply omit that code.
Don't you need anything like mysql_real_escape_string or htmlentities?