.js file as javascript source but acting as php on backend - javascript

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.

Related

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.

Create json data file with extension '.json' [duplicate]

So I want to write a REST API in PHP for JSON for consumption on the iPhone, but also a lot of websites and devices. I have the below code, when accessed via a GET statement, returns a file like:
1mdi2o3.part
How do I return something like: users.json
$db->setQuery( "SELECT * FROM users");
$db->query() or die($queryError);
$numRows = $db->getNumRows();
$row = $db->loadObjectList();
// PRINT JSON FILE
header("Content-type: application/json");
for($i = 0 ; $i < $numRows; $i++){
$json_output[$i] = $row[$i];
}
$MYjson_output = json_encode($json_output);
echo $MYjson_output;
Not entirely such what your goal is but here are 3-4 solutions that might work:
Common Solutions
Rewrite
This is probaly the most conventional way of getting clean URIs for your API. If you want the user part of user.json to be dynamic, you can use mod_rewrite (again assuming Apache) to rewrite your URLs to a php handler script. If you are going the conventional RESTful style URL route, you will probably want to use this anyway to achieve clean / separated URLs.
# For grabbing all users
RewriteEngine on
RewriteRule ^users\.json rest.php [L]
# For grabbing one particular user
RewriteEngine on
RewriteRule ^([a-z0-9]+)\.json rest.php?user=$1 [L]
Where rest.php is your PHP handler script.
URL Rewriting without mod-rewrite
If you don't want to use mod_rewrite, you can also do something like
example.com/rest.php/users.json
example.com/rest.php/user-id.json
or even
example.com/rest.php/user-id
example.com/rest.php/user/user-id
Where rest.php is your PHP handler script. You can grab the user-id from the URL (or URI if we're talking RESTful terms) using the $_SERVER global with $_SERVER['REQUEST_URI'].
Other solutions
Changing download name via Content-Disposition:
I believe you want to add the Content-Disposition header...
<?php
header('Content-Disposition: attachment; filename="users.json"');
?>
This will force the file to be downloaded as user.json. This usually isn't the behavior expected for a REST API, but from the way your question was worded, I figured I'd throw it out there.
AddHandler (or AddType)
Assuming you're running an Apache server, you can also just use AddHandler directive to make .json extension files be treated like they are php.
AddHandler application/x-httpd-php .json
Warning: Other plain .json files will be treated as PHP so you'd probably want to set this in a .htaccess file in the directory with the PHP script. This would work fine for this one URI but not ideal if you were exposing many URIs
Welcome to SO. Have you considered using the Zend framework for this application? I've written about this topic before, and if you do use Zend I could probably be of additional help. It would certainly help get you past the basics.
HTH,
-aj
The problem is this line:
header("Content-type: application/json");
I know this looks like the right way to do (after all, application/json is the official MIME type for JSON content), but it causes most browsers to present you with a file download dialog, when you just want to see the text. You can use the text/plain encoding to avoid this. Note that your AJAX/iPhone/... app probably doesn't care about the content type, so your API will work in both cases.
Also see this blog post which provides some more context.

Is it okay to save my javascript in a .php format for a wordpress site?

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.

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.

Categories