Escaping <?php ?> in the JavaScript of a php file - php

I have a php file, index.php, that contains the jQuery/JavaScript code below. The code is defining a string that will be a new PHP file after it gets ajaxed up to the server. index.php loads fine until I put the PHP line in the first array member. Then when I load index.php I get:
SyntaxError: <html xmlns="http://www.w3.org/1999/xhtml"><head>
Since index.php is a PHP file that is running I know I have to escape the leading < in <?php or the PHP processor will jump in at the server. But apparently I need to do more than that. Does anyone see how I can structure this so that index.php loads and then this code passes <?php ?> up as a harmless string?
$(function() {
var seg1 = ["\<?php phpinfo(); ?>\n",
"<!doctype html>\n ",
"<!-- HTML5 -->\n",
"<html>\n",
"<head>\n",
"<meta charset='utf-8' />\n",
"<title>MyPlace</title>\n" ,
"<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'><\/script>\n",
"<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js'><\/script>\n"
].join('');
}

phpinfo() generates a HTML page by itself, so concatenating that with another document isn't exactly kosher.
That said, you could use output buffering first to capture the output of phpinfo() and then use json_encode() to properly escape it:
<?php
ob_start();
phpinfo();
$info = ob_get_clean();
?>
$(function() {
var seg1 = [<?php echo json_encode($info); ?>,
"<!DOCTYPE html>\n" // etc etc
].join('');
Update
I misunderstood your question; it seems that you allow the upload and execution of arbitrary PHP code on your server. This is highly dangerous and my first advice would be to basically abandon that idea.
If you still feel like shooting your foot off, here's how:
var seg1 = ["<" + "?php phpinfo(); ?" + ">\n",
"<!DOCTYPE html>\n" // etc etc
].join('');

Related

JQuery .html() insertion method won't take PHP file_get_contents() as an argument

Here is the code:
echo "<script>jQuery(document).ready(function($)
{ $('.page-id-24 .entry-content').html('" . file_get_contents('about.php') . "'); });</script>";
Note: In my about.php file it has: <?php echo "html content..."; ?>
Results: I get nothing.
What's wrong? What am I not understanding?
Your code reads the entire contents of about.php and dumps it into the middle of your string, but it does not attempt to execute any PHP. The result is a string of data starting <?php that the browser attempts to interpret as HTML. It doesn't understand PHP, so the result is unpredictable, and will depend on the exact contents of about.php.
Say for example, that your about.php contains the following:
<?php echo "<div>Some text</div>"; ?>
Strip all the PHP to leave just the HTML and change the name to about.html:
<div>Some text</div>
You could just stop here and update your PHP code to read the about.html file:
echo "<script>jQuery(document).ready(function($)
{ $('.page-id-24 .entry-content').html('" . file_get_contents('about.html') . "'); });</script>";
This will work provided your about.html doesn't contain any single-quote characters.
There is a much easier way of doing this.
Edit about.php to produce about.html as above, then change your script to get jQuery to load the file direct from the server:
echo "<script>jQuery(document).ready(function($){ $('.page-id-24 .entry-content').load('about.html'); });</script>";

php syntax for big block of echo <?php if(1): ?> html<?php endif; ?> correct way

Well most is in the title. I wonder if it's supposed to be that way or i can do the same without an if(1) condition I'm doing this because my website pages are all as php includes.
Thank you all
Answer retained:
Okay basically the way to do it is simply to include('file.php') as it will be considered out of the current <?php ?> environment.
Putting
<?php if(1): ?>
...
<?php endif; ?>
around your HTML code in a PHP file will have no effect on the result. You will still be able to include the file without it.
You can think of it like the "default mode" for a PHP file is that it contains HTML content. You only need to add <?php ?> tags if you want to add PHP code. If you're just putting HTML code in a PHP file, they're unnecessary.
The beauty of PHP is that you can move "in" and "out" of PHP very easily. You can do the following without issues:
<?PHP
if(whatever) {
?>
your HTML
<?php
include('whatever.php');
?>
more HTML
<?PHP
}
?>
To build on Zak's answer:
You can also use PHP to echo out things that aren't PHP... as long as you quote it appropriately.
<?php
//HTML
while ($x < 5) {
echo "<p> this is html that you can wrap with html tags! </p>";
$x++;
}
//Javascript
echo "<script type='text/javascript'>
some javascript code
</script>"
?>
Although, it's less confusing to just end the php tag to keep things separate.
And you can even use php as you want within html or javascript as long as you put the tags, and as long as the file is saved as a .php file (so PHP can be processed on the server).
Ex:
<script type="text/javascript">
//set a javascript image array to a php value
var imgArray = [<?php echo implode(',', getImages()) ?>];
</script>
But if you want to do this the other way around (IE, assign a browser-compiled value, such as a javascript value to a php value), you'll need to use AJAX.

echo php variable on external javascript possible?

I (absolute php beginner) was given a script with different variables that are based on date and time on the top of xhtml strict page:
<?php
$var1="2011,9,31,18,0,0";
[...]
?>
Inside the html body I have a javascript that currently starts like this:
<script type="text"/javascript">
dateFuture = new Date(<?php echo $var1; ?>);
[...]
</script>
Is it possible to make the javascript external, but still pull the variable $var1 from the top of the index page and then have it show the same output on the index page as it currently does?
I have found one example where the beginning of the external .js is supposed to look like this:
dateFuture = new Date(<?php include("/index.html");echo $var1;?>);
Unfortunately that doesn't seem to work.
Is there any possible solution for this?
Any help is greatly appreciated.
Thank you in advance.
Yes. Make the javascript variable global and you can access it inside you external js file.
Something like this
<script type="text/javascript">
var dateFuture = new Date(<?php echo $var1; ?>);
</script>
<script src="your-external-js-file.js" type="text/javascript"></script>
In your-external-js-file.js, you can access the dateFuture.
Or you can encapsulate the code in external js file in a class and pass on the date from php as a parameter to the constructor of that class.
The external JavaScript file itself can point to a PHP file — provided that the PHP file outputs valid JavaScript. That way, you can do something like the following:
myJS.php:
<?php
// Initialize your PHP variable(s) here, or include the PHP script(s) to do so.
$var1="2011,9,31,18,0,0";
...
?>
dateFuture = new Date(<?php echo $var1; ?>);
In your HTML file:
<script type="text/javascript" src="myJS.php"></script>
Since the output of myJS.php is purely JavaScript code, the file extension will not matter to the browser. Same way as your PHP code currently outputs purely HTML code, and your browser understands how to parse that as well.
If your purpose is to move the javascript code to an external script for better modularization, you can move it to a php file and then reference php file as javascript.
<script type="text/javascript" src="myscript.php"></script>
Inside myscript.php -
<?
Header("content-type: text/javascript");
dateFuture = new Date(<?php echo $var1; ?>);
?>
Whilst the answers given by Jonathan Newmuis and RonakG are perfectly acceptable and will work, the purpose of this answer is to answer your question as close to the setup you've got now as possible. However I'd personally agree with RonakG's answer.
If you're using Apache on your server then add the following line to your .htaccess file: AddType application/x-httpd-php .js. Alternatively you could add that code into the Apache configuration if performance is an concern for you.
The goal of that code is, essentially, to say that PHP should parse all files ending in ".js" as if they were ".php"
Yes. It is possible. However, you are going to have to make the javascript file into a php file, or force Apache, or whatever web server you use, to run javascript as php (perfectly harmless, because all code outside of <?php ... ?> is just written to output).
In my-external-js.php or my-external-js.js (whichever you choose, though I would recommend the former, because it requires less configuration):
<?php require_once 'file-which-defines-var1.php'; ?>
dateFuture = new Date("<?php print $var1; ?>");
Note: you should always use require_once instead of include or require, so that the same file is never included twice, which leads to messed-up variables and colliding functions/classes. Also, require and require_once case Fatal errors if the script could not be loaded, while include and include_once do not.

Can I load a file in PHP as a string with inline variables?

I've got a simple (but not tiny) template for some HTML, complete with inline variables. I'd like to pull that out as a separate file, and have the ability to switch in other template files. Is there a way to load a file into a string, but have it process inline variables?
Eg:
$thing="complete sentence";
$test=<<<END
This will get parsed as a $thing.
END;
echo $test; // This will get parsed as a complete sentence.
What I want is something like this:
// "test.html"
<html>
<body>
<p>This will get parsed as a $thing.</p>
</body>
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.html");
echo $test; // This will get parsed as a complete sentence.
How do I achieve this, preferably without a templating library?
<?php
$thing="complete sentence";
$test=file_get_contents("test.php");
echo preg_replace_callback('#\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)#','changeVariables',$test);
function changeVariables($matches)
{
return $GLOBALS[$matches[1]];
}
This code uses preg_replace_callback to check what is variable. But, because we are in function, we cannot directly access script variables. We have to use $_GLOBALS variable which contains every script variable. $matches[1] contains name of matched variable.
Something like this should work...
// "test.php"
This will get parsed as a %s.
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.php");
printf($test, $thing);
You can use include to simply load the file as if it were part of the calling code.
include("included_file.php");
If you cannot include for some reason, you can read the file contents and eval it.
$content = file_get_contents("included_file.php");
eval($content);
UPDATE:
As pointed by NikiC, your file test.html doesn't have valid PHP. You would have to change it so include can work. Your test.html should have this content:
<html>
<body>
<p>This will get parsed as a <?= $thing ?>.</p>
</body>
And eval would not work with this code, as this is not pure PHP code, it is HTML code with PHP inside it. If your included file has just PHP code, it would work fine.

Organising code that includes php and javascript files

I have a website where I am including a php library file and a javascript library file. I have condensed the problem to the following files:
index.php
<?php
include('constants.php');
?>
<html>
<head>
<script type="text/javascript" src="lib.js"></script>
</head>
<body onload="javascript:show_const_1('<?php echo(CONST_TEXT); ?>');
show_const_2();">
Some text here
</body>
</html>
constants.php
<?php
define('CONST_TEXT', 'Hello World');
?>
lib.js
function show_const_1(string)
{
alert(string);
}
function show_const_2()
{
alert('<?php echo(CONST_TEXT); ?>');
}
The result is that when the page loads I get two message boxes. The first says "Hello World" and the second says "<?php echo(CONST_TEXT); ?>". The first javascript method does what I want it to, but I will be using the function in many places across the site and so ideally I don't want to have to pass the constant as a parameter every time.
Is there a good way to rearrange the code to make the second javascript method work?
The simple answer is rename "lib.js" to "lib.php".
You should also add
header('Content-type: text/javascript');
to the top of the file.
Incidentally, you should us json_encode() to output text to javascript:
alert(<?php echo json_encode(CONST_TEXT); ?>);
And "javascript:" doesn't belong in event attributes (which are kindof outdated anyway):
<body onload="doSomething();">
The method body inside alert() is not interpreted by PHP (it's interpreted by Javascript), so you can't put PHP tag in it

Categories