So before you say this can't be done. These are all files that I have one server. I just have some of them listed under different domains.
My PHP script will access all the files but when I try to do an ajax request to try to load the file I will often get an error (because the site i am accessing is secure and the one I am accessing it through isn't).
What I need is a way to have php grab the file. But I need aJax to retrieve the file and render it for me. I am also using ACE editor to edit the file
The bit of code I have here will actually error out as well because it will load and print out the file where $page is defined but won't load where htmlspecialchars is.
<script>
var e = ace.edit("editor");
<?php
$page = readfile($_SERVER['DOCUMENT_ROOT'].$_GET['dir']);
echo 'e.setValue('.htmlspecialchars($page, ENT_QUOTES).');';
?>
</script>
I have an ajax get request working but it doesn't work when I go to a directory with a special htaccess file. Now I can't change the htaccess file (unless there is a way for me to confirm that it is my script running and not someone else.
The question is, how can I access those other files without getting that error? Mind you those files could be extension. It is not limited to just scripts or css, mostly they will be html or php files.
After an hour of searching the deep dark depths of the php.net site I was able to put together a solution that works.
<?php
echo htmlspecialchars(
addslashes(
file_get_contents(
$_SERVER['DOCUMENT_ROOT'].$_GET['dir']
)
)
); ?>
the addslashes is the extra part that I needed. Then I also had to put it between the div for the editor. I couldn't use the editor.setValue() function.
Related
When I put the script directly in the .PHP file my script works perfectly:
function setup()
{
var setRows = <?php if(!isset($_GET['rows']))echo 3;else echo $_GET['rows']; ?>;
var setColumns = <?php if(!isset($_GET['columns']))echo 3;else echo $_GET['columns']; ?>;
document.getElementById('rows').value = setRows;
document.getElementById('columns').value = setColumns;
document.getElementById('rowOutputId').value = setRows;
document.getElementById('colOutputId').value = setColumns;
}
However, when I put it in a separate file and link it, it prints out the literal string instead of the correct value. So like this:
<script type="text/javascript" src="js/file.js"></script>
It echoes the following:
<?php if(!isset($_GET['rows']))echo 3;else echo $_GET['rows']; ?>
Also, it's important to note that when I have it directly in the HTML file it stores the PHP perfectly without the quotes around it, but in the separate file it gives me the following error if I take away the quotes:
Uncaught SyntaxError: Unexpected token <
Your server decides what to do with a request based on its extension (this is an over-simplification, but will do for now).
Your server has been configured to treat files ending on .php as a php file. This means, that when you request this file from Apache, Nginx, or whatever webserver software you are using, your webserver will first ask the php software to parse and execute it. When the PHP software executes the first code, it will run anything between <?php and ?> . It will then return the result of the code execution to your webserver, which will pass it back to the client.
However, when your browser loads the .js file, your webserver considers this as a "normal" file. It will then read the file and return it straight to the client, without passing it to the PHP software first. Therefore, nothing will be executed or interpreted, and you will simply see all the text in the file.
Now assume you put PHP code in your .js file. It wasn't executed, and therefore the PHP code will still be present when your browser receives the response from the webserver. Your browser will then try to parse and execute the javascript in the file, but your <?php tag isn't valid javascript. Therefore, attempting to execute this file will cause errors in your browser console.
You can configure which extensions should be treated as PHP code in your webserver config.
For Apache this is done through addHandler, while for nginx this can be done through location directives.
I would strongly advice against changing this to treat javascript as PHP, as your javascript files aren't supposed to contain PHP code. If you want to pass something to a variable, just do it in the HTML code generated by the PHP file.
Instead of putting my javascript into a .js file, I would like to use a .php file so that I can use some php code (for example getting my wordpress blog url, or "if this page" statements).
Are there any down sides in terms of performance if I do this?
You can have a .php page and have your js functions within it with the proper <script></script> tags, as you said, and there shouldn't be anything wrong with it.
Though, if you have lots of js functions that require its own page, then you can pass the values that come from the server-side to the function in the client side. For example.
in .php page
<script>
var blogUrl = "<?php echo get_bloginfo('url'); ?>";
myFunction (blogUrl);
</script>
and in .js page
function myFunction (blogUrl)
{
alert(blogUrl);
//do something
}
This way, you can have a proper pure js file, while not making your php files too messy with JavaScript either.
Yes.
You can echo or print your js like so
<?php
echo "<script type = \"text/javascript\">
// code here
</script>":
?>
Remember to escape any characters with a backslash.
OR
<?php
//some php here
?>
<script type = "text/javascript">
//code
</script>
You can have a php file request return javascript content, and have it act as if it were an external javascript file (without the need to write the HTML tag around it) by setting the Content-type header to a javascript mime type:
example.php:
<?php
header("Content-type: text/javascript");
?>
alert("<?=$_SERVER['HTTP_HOST']?>");
Then you can use this php file as if it were a regular external javascript file:
example.html
<script type="text/javascript" src="http://www.myserver.com/example.php"></script>
In this case looking at the source of the javascript that the php responds with would just contain:
alert("www.myserver.com");
As far as performance goes, you might have a small hit by processing a php page instead of just serving a static file, but if you add suitable cache layers in front of it it shouldn't make much difference.
Yes, you can easily write your javascript code in .php file without using any php tag.
This is totally same as you are writing javascript in HTML. Have to use tag, which you did not use in .js file.
Yes can code js inside a php file but, remember to add tags or else your Script will not function
Scripts are flexible as both external .js file and within a php file in spite of the CMS we use.
Example:
<?php
<script type = "text/javascript">
// Script code to be embedded
</script>
?>
Above is the standard Syntax to be followed for integrating Script inside a PHP file.
I use $_SESSION['siteRoot'] to store the root address of my website in (it's basically a framework so this can change depending on the URL used to access the site). I need to use this value in some of my javascript files...
Up until now I've been including my js files as .php, and putting the following code at the top of my js files, like so:
<?php
header("Content-type: application/javascript");
session_start();
?>
This has been working fine on my local-host for testing - but when I upload it to the live server I noticed that my session was being reset every time I reload the page, and after a day of debugging finally discover that it's the session_start(); line in my java-script files that is causing this behavior.
I've tried the following:
if (!isset($_SESSION))
{
session_start();
}
if (session_id() == '')
{
session_start();
}
if (session_status() !== PHP_SESSION_ACTIVE)
{
session_start();
}
and also just leaving out the session_start altogether. If I don't start the session then I can't use the variables (obviously...), but I can't find a way of starting it that doesn't wipe the session I already created in my main page.
Any ideas?
The problem was not caused by the session itself exactly, but because I hadn't included my class autoloader before calling the session, and so my custom classes were not surviving the deserialize process (even though it's a javascript file and I don't use any of said classes!)
I changed my javascript code to:
<?php
include ('include/autoloader.php');
header("Content-type: application/javascript");
session_start();
?>
and everything works fine. Easy to forget when you're not using any of the serialized classes on that page!
I see much scripts in traffic exchange services or affiliate programs like the following
<script type="text/javascript" src="http://trafficexchange.com/trafficout/user/300?limit=10"></script>
A source without file extension. How does this work? Is this a javascript file or php file? If this is only javascript how can they access the database to collect stats about who clicked on your link etc (AJAX?)?
The query variable limit=10. Again, is this javascript or php? If it is javascript, how can you access this variable?
Other example from Google Ads
<script type="text/javascript">
google_ad_client = "xxxxxxx";
google_ad_slot = "xxxxx";
google_ad_width = 336;
google_ad_height = 280;
</script>
<script type="text/javascript"
src="//pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
Again, how can google access their database to display relevant ads with only a .js file?
The client only expects one thing of an included <script> file: to have the proper Content-type: application/javascript header.
So a PHP file like this is valid (although bad form):
<?php
header('Content-type: application/javascript');
?>
var answerToEverything = <?php echo 42; ?>;
And the browser will see it as a valid JavaScript file containing
var answerToEverything = 42;
Even if the file is not explicitly named .js.
A more general approach is to capture all requests to your webserver, do some action, and then include your JavaScript file with the proper header.
Note that including PHP variables directly inside JavaScript files is considered bad practice.
For more information see How to pass variables and data from PHP to JavaScript?
Scripts like this are probably being run by PHP (or similar server-side scripting language).
Doing so is a case of, on an apache server, adding something similar to the following in the .htaccess file:
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^trafficout/user/(\d+)$ some-script.php?%1&user=$1 [L]
What this is doing is looking for any requests for the above file, then passing in the query string ((.*)) and user id ((\d+)) into a php script.
What are %1 and $1 doing?
In a htaccess file %1 and $1 represent variables retrieved from RewriteConditions and RewriteRules. Specifically, %n represents any variables acquired from a %{QUERY_STRING} condition and $n repesents any variables acquired from rules. In both cases n represents the variable id. In the example above, there is one query string variable and one rewrite rule variable so both are 1.
For the script in your question, this will turn the second part of our rewrite rule into:
some-script.php?limit=10&user=300
How we get the variables from the query string etc is done via Regular Expressions, and is a WHOLE other topic that I am not going to go into right now.
The PHP script will then get the variables using $_GET or similar, for example:
$user = $_GET['user']; //bad example - no validation etc.
[L]?
This is a flag used to tell the server to stop processing any more rewrite rules.
No file extension
It is possible to call for a file without a file extension, as long as the script sets the correct content-type header, then the browser will process the returned file. In PHP, this would be done like:
<?php
header('Content-type: application/javascript');
And is sent before any content.
Google Ads
The original .js script is just a .js script. What the script is doing is generating an ajax call back to the Google Servers replacing local variables with whatever variables you have defined.
I'm curious about passing PHP output to Javascript. Two things specifically:
I'm assuming this can be done safely using script tags on a .php page. Is there any reason not to?
Can you make PHP run on .js pages? What configuration changes would be required? And again, would there be a reason not to?
I'm assuming this can be done safely using script tags on a .php page. Is there any reason not to?
Yes. No reason not to.
Can you make PHP run on .js pages? What configuration changes would be required? And again, would there be a reason not to?
Yes, you would have to configure your webserver to use the PHP module for the .js suffix. On nginx you might add a location line for files ending in .js:-
location ~ \.js$
{
}
On Apache you'd do something like:-
AddType application/x-httpd-php .php .js
One reason you might not want to do this, is that any static JS files would go through the PHP module and that would cause additional overhead. Another option would be to reference the PHP file in the HTML script tags eg:-
<script src="myfile.php"></script>
and then make sure your PHP returns its output with the correct content-type eg:-
header('Content-Type: application/javascript');
You're right on both counts.
You can output dynamic content (PHP) in a <script> tag on a .php page
You can output dynamic content (PHP) in an all-javascript file, though the extension would still be .php
Example 1
<script type="text/javascript">
var myobject = {
data: '<?php echo $myPHPvariable; ?>';
};
// or better yet:
var myBetterObject = <?php echo json_encode($myPhpObject); ?>;
function foo () { ... }
</script>
Example 2
Not recommended
<?php
// This is an all-javascript file but the extension ends with .php
header('Content-Type: application/javascript');
?>
var myobject = {
data: '<?php echo $myPHPvariable; ?>';
};
function foo () { ... }
Then you include that file in your HTML document with:
<script type="text/javascript" src="/custom_javascript.php"></script>
It should definitely end with .php, and thankfully the web browser knows it is JavaScript by the type="text/javascript" part and because your PHP script outputs the right Content-Type header.
The first solution is simpler : declare some JS variables in the output HTML, they can be constant or generated by the PHP code:
<script>
var my_variable = '<?php echo($my_variable); ?>';
</script>
Then you can use this variable in your Javascript code.
The .js files should be static to allow the browser to cache them, so they won't be loaded every time the user loads a page. By generating .js files on the fly with PHP, you may have problems with browsers using cached .js instead of the expected generated file. For example, if your variable contains dynamic content as the last news from your website, a datetime, etc.
So, yes you can do it, but you'll have to prevent the browser to cache the file, increasing the bandwidth usage or expect unexpected behaviours with browsers loading cached .js files. There's no benefit in using this way.