How to include PHP $_SESSION values in a javascript file? - javascript

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!

Related

Load different PHP files based on JavaScript availability

I currently have the code below (PHP)
<?php
require_once __DIR__.'/includes/Connect.php';
require_once __DIR__.'/includes/Nojs.php';
require_once __DIR__.'/includes/Main.php';
require_once __DIR__.'/includes/footer.php';
?>
I want Main.php to load only if JavaScript is enabled, and Nojs.php to load only is JavaScript is disabled.
Surrounding Nojs.php with tags does nothing (See below code)
<?php
require_once __DIR__.'/includes/Connect.php';
?>
<noscript>
<?php
require_once __DIR__.'/includes/Nojs.php';
?>
</noscript>
<?php
require_once __DIR__.'/includes/Main.php';
require_once __DIR__.'/includes/footer.php';
?>
Since I know the PHP cannot access the browser as it is done server-side, is it possible to try to use HTML (Like I attempted) or other JavaScript to get it to work?
Thanks in advance.
EDIT:
Creating a new file for nojs.php and using meta refresh works, but there is a noticeable delay. The page starts loading the original URL and then redirects to the other. A visitor can quite easily cancel the page load process and stop the page load before the redirect. They will have a partly loaded page, but all the content they really need will be there. Is there a way to force an immediate redirect (Yes, "content" is set to "0" per the below anwser)?
Create another PHP file with no js version when first PHP loaded it will check if no js support will redirect to no js version of PHP
<noscript>
<meta http-equiv="refresh" content="0;url=nojs-version.php">
</noscript>
Edit: It is also mentioned by W3C as technique without confusing user
https://www.w3.org/TR/WCAG20-TECHS/H76.html

Storing PHP in Javascript doesn't work when in separate document

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.

Is it not feasible to make PHP run on .js pages?

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.

PHP Ajax jQuery cross domain file loading

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['d‌​ir']
)
)
); ?>
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.

Keep track of everybody who uses my code

I made a theme for tumblr and I want to release the code to the public. The thing is, want to know how many people are using my theme. Is there any javascript or other solution to this other than google analytic?
Yes, add to your code some javascript that sends a GET request to a php page that logs the request. You need to grab the tumblr document.URL when you do this.
<script type="text/javascript">
xmlHttp.open( "GET", '//mywebsite.com/tumblr_code_check.php?referrer='+document.URL, true );
xmlHttp.send( null );
</script>
PHP:
<?php
$referrer = $_GET['referrer'];
$file = '';
$filename = 'tumblr_refferalls.txt';
$file = file_get_contents ($filename);
file_put_contents ($filename, $referrer."\n");
?>
Then check the file tumblr_refferalls.txt. You can add some code to the php page ignore your own website, to prevent it from filling up.
Please note that anyone can remove the javascript from your code.
You can get more detailed, such as adding a timestamp, filtering it so you only get the page URL once appended to your logfile, have it send you a text message or email when someone new uses your code, etc.
Use a tracking pixel, a 1x1 image and just include it in the markup. Of course any end-user is free to remove it. I urge you to refrain from other methods, as you will not only raise red flags with anybody who looks into your theme, but you may negatively impact their PHP or JS execution should your host ever fail to connect.

Categories