I currently am trying to echo the contents of a text file within JavaScript. Everything works but there is a problem. The text within the text contains apostrophes, which is throwing everything off. Below is a portion of the code that I am using. I am using this code for MANY text files. I have considered changing each apostrophe to "\'" in each text file, but there are a lot of text files to deal with. I was just curious if there was another way to work around this. Any ideas are greatly appreciated.
<?php
$lyrics = file_get_contents('Includes/Songs/Lose_My_Mind.txt');
?>
JavaScript snippet:
var scrollercontent='<?php echo $lyrics; ?>'
Whilst addslashes will mostly work, this is better:
var scrollercontent= <?php echo json_encode($lyrics, JSON_HEX_TAG); ?>;
json_encode works for any datatype, not just strings. For strings it adds the quotes at the sides for you, and it will work for any character including control codes such as the newline character.
The JSON_HEXs are a PHP 5.3 feature. HEX_TAG replaces < with a JavaScript string literal encoding like \x3C, which means you can put any string literal in a <script> block without worrying that it might contain a </script> sequence that would prematurely end the script block. (Even just </ on its own is technically invalid.)
Try to use addslashes() function. In your case:
var scrollercontent='<?php echo addslashes($lyrics); ?>'
Try
addslashes(nl2br($lyrics))
(nl2br replaces new lines with <br> tags.)
Try changing this
var scrollercontent='<?php echo $lyrics; ?>'
to this
var scrollercontent='<?php echo addslashes($lyrics); ?>'
or
var scrollercontent='<?php echo htmlentities($lyrics); ?>'
these should help escape or entitize quotes etc...
Have you tried:
<?php $lyrics = addslashes(file_get_contents('Includes/Songs/Lose_My_Mind.txt')); ?>
You could add the following line after your file_get_contents command:
$lyrics = str_replace("\'","\\'",$lyrics);
This will change all of the single apostrophes to escaped apostrophes and should play nice with Javascript.
<?php
$lyrics = nl2br(htmlentities(file_get_contents('Includes/Songs/Lose_My_Mind.txt'), ENT_QUOTES));
?>
var scrollercontent="<?php echo $lyrics; ?>";
Related
hello every body i had a problem with echo in php that might be very simple but i'm a bit new in php.
i had a code like this:
<?php echo '<script>var str=Array(1);str.push('.$user_id.')</script>';?>
in this code i want to display script text instead of calling java script. what shall i do?
i have already tried every kind of writing types such as single quotes and double quotes like below
<?php echo '"<script>"var str=Array(1);str.push('.$user_id.')"</script>"';?>
even tried \ at the beginning and end of script but none of them worked.
You need to use htmlspecialchars() function to escape html tags.
<?php echo htmlspecialchars('<script>var str=Array(1);str.push('.$user_id.')</script>');?>
How do I put PHP Code into a string?
$phpCode = '<? if($condtion){ ?>';
For some reason, when I do this and echo out the code, I don't get the opening PHP tag, <?.
Am I missing something? Is there a better or more proper way to do this? I am currently looking at the PHP docs on strings but I would like to get your feedback.
Edit: The reason why I am using apsotrophes (') and not quotes (") is because I don't want the code to fill in the value for condition. I want it to echo as-is.
Use htmlspecialchars():
$phpCode = '<? if($condtion){ ?>';
echo htmlspecialchars($phpCode);
You need to echo htmlspecialchars($phpCode);
try these $str= htmlentities('<?php //***code***// ?>');
You can also use HTML entities.
When you replace just the opening square bracket in PHP, the rest will be considered a string when parsed with echo:
<?php
//< is the HTML entity for '<' (without quotes).
$str = '<?php yourstring ?>';
echo $str;
?>
Source HTML Entities
You can output PHP code as text in following way
$phpCode = '<? if($condtion){ ?>';
echo "<pre>";
echo htmlspecialchars($phpCode);
echo "</pre>";
There's already a few answers to this, but just to add my $0.02...
This code:
<?php
$test = '<?php echo "hello world!"; ?>';
echo $test;
?>
Produces a blank white screen in the browser, but if you view the source you'll see this output:
<?php echo "hello world!"; ?>
This has to do with the way the browser is rendering your PHP code. Browsers aren't meant to render PHP code, but rather HTML markup. If you're echoing out the code because you're testing what is going to be written to your file, then just view the source to validate what is being output is what you want to be written to the file. You won't see it in the browser itself because it doesn't know how to render the ?php tag, let alone what to do with the echo attribute.
Optionally, like everyone has stated already you can pass the string through htmlspecialchars if all you want to do is render it in the browser without having to view source. You wouldn't want to do that if you're writing it to the file, but may help you debug your output.
Another option would be to run your script from the command line. It won't attempt to render your output and instead just spit it out verbatim.
Eval php documentation
Use Eval() if you want to run the code in the string.
Example
$str = "Hello ";
eval('$str .= "World"');
echo $str;
/* Output: Hello World */
I pulling out some html/text strings that I need to insert into a javascript variable.
eg, that's how it would look in php:
echo "<script type=\"text/javascript\">\n";
echo "var myvar='{$value}'";
echo "\n</script>";
The problem with the above approach is that some special characters would actually break the javascript code.
So, I tried using htmlspecialchars:
htmlspecialchars($value,11,'utf-8',true); //11 stands for ENT_QUOTES|ENT_SUBSTITUTE
This did replace some unusual chars and most importantly the quotes.
However the new line chars pass it by and break my javascript.
So how could I escape the new line chars? I need to preserve them to be used later in the textareas.
*EDIT* I will post a sample value of my variable. (They are actually the input from Tiny_mce)
<p>You've been...</p>
<p><iframe src="http://www.youtube.com/embed/8d7OBluielc?wmode=transparent" frameborder="0" width="640" height="360"></iframe></p>
<script type="text/javascript">
var myvar = <?php echo json_encode($value); ?>;
</script>
JSON == Javascript notation == the proper encoding/escaping method for any values output to Javascript.
For example i've a php script with this content:
<?php
$msg = addslashes("I'm a message. The what happened >:(");
echo "<script>alert($msg); return false;</script>";
?>
But the alert get broken by the last "(". How can i solve this?
You should enclose alert parameter with quotes:
echo "<script>alert('$msg'); return false;</script>";
What your code outputs to the browser was:
<script>alert(The what happened >:(); return false;</script>
which is not a valid javascript, after putting the quotes, it becomes:
<script>alert('The what happened >:('); return false;</script>
which is valid javascript.
You need to put it in a JavaScript string, otherwise it gets interpreted like this, which is meaningless and causes an error:
<script>alert(The what happened >:(); return false;</script>
Notice the single quotes in the alert() call which denote a JavaScript string (double quotes work too):
<?php
$msg = "The what happened >:(";
echo "<script>alert('$msg'); return false;</script>";
?>
It is also a good idea to escape the content inside to mitigate XSS, using htmlspecialchars().
The other answers are along the right lines, but it is not sufficient to just put quotes around the string, if it can be any arbitrary string. If the string itself contains a quote, backslash, or newline, that will break the JavaScript string literal. If the string contains </script (or just </ in some cases) that will break the <script> block. In either case, if user-supplied input is involved, that gives you a big old cross-site-scripting security hole.
Whilst you may not need it for this specific value of $msg, it's a good idea to get used to JS-string-literal-escaping any text you output into a JS string. Whilst you can do this manually by adding backslashes, it's generally much easier to just use the built-in JSON encoder, which will work for other types like arrays and objects as well as strings.
<script type="text/javascript">
alert(<?php echo json_encode($msg); ?>);
return false; // huh? return, in a <script> block??
</script>
alert() accepts a string argument; you must enclose the text you're passing to it in quotes (either single or double) and insure that any matching quotes within the string are escaped by backslashes.
In your case single quotes would suffice:
echo "<script>alert('$msg'); return false;</script>";
Depending on the context, you might also just do:
<?php
$msg = "The what happened >:(";
?>
<script>alert("<?php echo $msg ?>"); return false;</script>
If there is no need to echo HTML or JavaScript code, then don't do it. It is easier to maintain .
I have some php code in a database like so
$x = "<?php some code here ?>";
but I want to output that whole line to the browser without php evaluating it. Right now it is evaluating it unfortunately. I thought about escaping it but that didn't work. How might a person accomplish this?
Thanks
EDIT:
<?php
echo '<? hey ?>';
echo "<dog dog>";
?>
if I run that code the dog dog tag shows up in the browser source code where as <? hey ?> does not. It seems like it would still be evaluating it.
Edit, got the answer, thanks everyone.
Just do:
echo htmlspecialchars($x);
'Single quotes' tell PHP to interpert the string exactly as is. It will include all whitespace and characters exactly as is.
"Double Quotes" tell PHP to parse the string. This reduces whitespace, replaces variables, and parses any other magic string things.
Finally, `backticks` are used for shell commands.
If you are trying to display it in a browser exactly like that, you might want to try htmlentities($string).
Do you want it to appear like that? If so, you'll need to use < and > (strictly only the < is necessary) to encode the string.
use '(single quotes) instead of "(double quotes)
Ih PHP double quotes evaluate expressions, single quotes do not so:
$a = 123;
$b = "value of $a"; // value of 123
$c = 'value of $a'; // value of $a
The only problem with single quotes is they don't understand characters like \n for newlines (that will be printed as \n not a newline when put in single quotes).
So is all you need:
echo '<?php some code here ?>';
?
For more information see Strings in the PHP manual.
You're a bit unclear about what gets evaluated.
If you're talking about variables, there are plenty of correct answers here.
If you're talking about the <? ?> block, something's wrong. That string should not be evaluated if within a PHP block (If you mean the opening and closing PHP statements).
Maybe you are missing the opening and closing <? ?> before and after your operation?
If you're outputting php code you might even consider using highlight_string which will perform syntax highlighting on the input