Can I load javascript from a php file? - php

Can I do something like this?
<script src="/js/custom-user.php" type="text/javascript"></script>
The reason behind it is that I want the .php file to die() when the user is not logged in, so that other visitors (not authenticated) cannot see what the javascript looks like. Is it possible/safe to do like this?

Yes, but I do have two recommendations. First, it is better, in your circumstance, to only output the <script> if the user is logged in. Seriously, you don't want the thing which is outputting you js to really know or care about whether the user is logged in.
If you do output js in PHP, then you should include the appropriate header:
header("Content-type: text/javascript");
// either readFile or custom stuff here.
echo "alert('i canz have data!')";
// or, if you're less silly
readFile('/path/to/super-secret.js');
Actually, I once had CSS output by PHP (oh, you can do that too) which completely changed based on the get variable. I literally could have:
rel="stylesheet" type="text/css" href="css.php?v=#FF0000">
And it would use #FF0000 as a base color to completely re-define the color schemes in the website. I even went so far as to hook it in to imagemagick and re-color the site logo. It looked hideous because I'm not a designer, but it was really neat.

Certainly, so long as the php file being reference sends the appropriate content-type header when being downloaded.

Yes, you can do this, and it is safe.
In custom-user.php you will have to set a proper Content-Type header:
header('Content-Type: text/javascript');
And then output the javascript:
readfile('script.js');

Yes, but... You should better do it like this:
<?php
if ($loggedIn) { echo '<script src="/js/custom-user.js" type="text/javascript"></script>'; }
?>
That would prevent loading of empty file. All functions should be put in outer file, if you want some specific javascript changes, make a code in HEAD SCRIPT

Yes, that will work.
That's how JavaScript minifiers are able to dynamically serve minified scripts. (e.g. http://code.google.com/p/minify/)

You can but it will slow down your pages since every time someone accesses your page modphp will have to run your php/javascript script.

Related

How to know php file is loaded from source code

I'm working with my JS files, what i have now is a unique php file with JS header, if a variable is set it includes the real js file, which is fine.
The "home" page has the script tag for the php-js file:
<head>
<script type="text/javascript" language="javascript" src="bootstrap.php"></script>
</head>
the bottstrap.php file has something like:
if(isset($hostData) && !empty($hostData)) {
include('bootstrap.js');
}else {
echo "document.write('<center><bold>PLEASE DO SOMETHING...!</bold></center>');";
}
all that seems to be fine, however when viewing the source code (CTRL+U) the browser shows the "bootstrap.php" part as a link, if clicked it obviously redirects to http://mydomain/bootstrap.php and the js code can be easily seen, which is exactly what i don't want...
So my question is, is there any php-way to know if the file is being loaded from browser's "rendering view" or being loaded from browser's "source code view" ???
Any help is truly appreciated =)
In short, no. You can't hide your script source from your users. The best you can do is obfuscate it using tools like YUICompressor.
There's no way you can hide the javascript code. It needs to be executed by the client, and even if you try to hide it by formatting your code badly, tools like firebug can easily introspect the code and pull out the code.
To be honest I don't think you can actually hide it like that. I'm assuming the best thing you've got to go on is the useragent string but I'm assuming if you "view source" in a browser it would still send the regular headers.
The only way I can think of adding the JS include without it appearing when in view source mode is to actually load the external file via javascript (you could even break the path of the js file into variables so it isn't really human readable) which I would not advise.
If someone wants to get at your javascript they will there no is way of avoiding it.
and the js code can be easily seen, which is exactly what i don't want...
You don't want the JS to be seen, but you do want to use it???
There IS something wrong with your code though if you want the js file to be used in your page.
You need to include / require the file:
<script type="text/javascript" language="javascript" src="<?php include bootstrap.php ?>"></script>
Otherwise the browser will load the contents of the bootstrap file, but you want to run the code inside it (which can only be done at the server).
Also:
change:
include('bootstrap.js');
to
echo bootstrap.js;
EDIT
by re-reading your question (and other answers) that's exactly what you want: make your JS code invisible (correct me if wrong).
The answer to that is: No cannot be done.
You can try to obfuscate the code but it will take someone who wants to see it seconds to 'decode'.
Try using the $_SERVER["HTTP_referer"], which have the url that called this file.
I'm really sorry for disappearing from here...
The best solution I decided to implement is quite simple: don't show ANY URL or PHP files within JS code; so during last months I've used a unique PHP file to do all necessary database queries, a stored procedure generates dynamically all the URL's needed from JS.
In that way URL's vary every time and what I've named "poor logic" goes free for users to view/copy I don't mind that while server data is secure.
THANKS ALL FOR YOUR VALUABLE ANSWERS!!!

Can I source a php file as javascript?

I am using a WP template that allows me to incorporate arbitrary HTML. Unfortunately, I have to use this particular widget and can't use other WP widgets.
I have on my webserver /some/path/serve_image.php that spits out a random HREF'd IMG SRC with a caption and some other info from a MySQL query.
Now...how can I say "take that output and treat it as HTML"? If I just put "/some/path/serve_image.php" I get that literal string.
I tried:
<script type="javascript" src="/some/path/serve_image.php"></script>
but that didn't work. I tried changing everything in serve_image.php to be document.write() calls and that didn't seem to work either. I'm not the world's greatest JS guy...
So if I have a URL on the net that spits out some HTML and I want to include that HTML in my web page, what's the best way to do that? Sort of like what Google does with Adsense - you source their show_ads.js.
Why no? Add
header('Content-Type: application/javascript');
And output JavaScript Like:
echo("var image = \"".$images[array_rand($images)]."\";");
echo("$('img.randim').attr('src', image);
No. JavaScript and PHP are two completely separate languages. In fact, if it was JavaScript, you aren't even loading it the right way.
<script type="text/javascript"></script>
The way you're trying to do it would throw a parse error, because it would try to use the PHP as JavaScript. Some browsers would even reject it, because PHP files have a text/html MIME type, while JavaScript should be application/javascript.
PHP has to be done server side, so loading it in the client just doesn't work.
What I think you're after is this:
<?php
require('/some/path/serve_image.php');
?>
Just place that wherever you want the image to be.

How can I redirect using a PHP script called from an SSI?

On a WAMP server, I have a server-side include in a file, a.shtml, composed of the following code:
<!--#include virtual="./req.php"-->
The contents of req.php are:
<?php
Header("Location:index.php");
echo "still here";
?>
When I open a.shtml, I see the text still here, but the page has made no attempt to redirect itself. Why is this? And is there any way to make it work?
Thanks for the help
EDIT: The reason I want to do this is because I have some session variables that I want to influence the way the PHP script acts. If the session variables are not set, I need it to redirect to a login page. I know I can just write the entire thing in PHP, but I'd like to do it this way if possible. If it's not possible to change header information from an included PHP file from SSI, then I'll just do it entirely in PHP.
it's impossible
you don't need that.
just address tour script that set session variables directly, not through ssi
MAYBE (with capital letters Lol), you can pull this off if you call that script in an IFRAME and that IFRAME outputs some JScript like window.parent.location = <some_url_here> forcing its parent to change its location... Its just fast-thinking from my part, I might be wrong with IFRAMEs' parent-child relation to the original document, as I haven't tested the "idea" myself :)
If your req.php returns the following html code, the redirect will happen:
<html><head>
<title>HTTP 301 This page has been moved</title>
<meta http-equiv="Refresh" content="0;URL=https://www.example.com/index.php">
</head>
<body></body></html>
But: "Google Warning: Using The Meta Refresh Tag Is Bad Practice"

Preventing jQuery from Loading

If jquery is added in globally used header.php across the site then How to stop to load jquery library only for those pages of site which doesn't need actually? If we can't use more than one header.
purpose of question is to not to penalize those page with slow loading which actually don't need.
Your site shouldn't need more than one global-header, if you opt to even use headers to begin with. If it does, just include jQuery on all pages. It's a small cached file, it won't hurt the browsing experience.
By using the google-hosted version, it may be the case that many of your uses already have it cached before they even reach your site.
I have been guilty of pounding my fist into the nail while asking everyone else to move the hammer that's in the way...
Why not tackle the problem from the other end and use jQuery to optimize the first load?
If you have big pages that are already taking a while to download, why not section off the less-performant areas and use $().load() to fill those in?
The page will load quicker (better user experience) and you don't have to be adding any additional processing to pages that don't need it.
Cheers,
-jc
assuming you are loading the jQuery file from a correctly-configured webserver (or from google's CDN), it will be cached and not re-downloaded on each page. Assuming a visitor will hit at least one page on your site that needs jQuery then you really won't gain anything by trying to remove it from loading on pages that don't use any javascript features from the library.
First, use the compressed jquery for production. It's much smaller. Second, IIRC, once jquery is downloaded with the first page, it will be cached and won't need to be retrieved from your server for each subsequent request.
Otherwise, if you really need to explicitly load jquery only on those pages that need it, you would have to have some way for the body of your page to tell header.php that it doesn't need to load jquery. If header.php is loaded before "body.php" then that's pretty hard to do without some fancy output buffering or such.
If you're using a templating system like Smarty you could have a conditional in the master page template to check a $loadjquery flag that you set in body.php before sending the whole page off to be rendered. But that's complicated too.
Your question is very general, some specific would be great, maybe even a link to the site. Personally if you are using a CMS I would try to make some sort of "flag" for that page, or if you are simply loading a page and then loading the header from that page, insert a variable before you load the header and use that as your flag for loading jQuery.
An example:
If a user wants to see www.mysite.com then the following file would be loaded: www.mysite.com/index.php with the following code:
<?php $needJQuery = true;
include('header.php');
echo 'content will go here';
include('footer.php'); ?>
header.php would include something such as this:
<?php if ($needJQuery) { ?>
<script src="/jquery/jquery-min-3.2.1.js" />
etc. for all the content that you need above/below.
<?php } ?>
For the pages that don't need jQuery loaded, you would either leave $needJQuery undefined or you would do as follows:
<?php $needJQuery = false; ?>
Hope this helps,
As stated earlier, modify the header file so it'll check for the presence of flag variable and only output the jquery headers if needed.
If you don't have the ability to modify the header file, you could load it with output buffering turned on and filter the output before it heads out to the client:
<?php
ob_start();
include('header.php');
$header = ob_get_flush();
$cleanheader = some_operation_that_removes_the_jquery_script_tags($header);
echo $cleanheader
?>

hide javascript from showing up in browser

I have some javascripts that I am using in my files. But when we view the source code it shows our javascript as it is. Is there any way with which we can hide our javascript from showing up in the browser using php.
There is a free javascript obfuscator at javascriptobfuscator.com. It will not prevent dedicated people from "stealing" your code, but normal copy&paste will not be easy.
Also see this question: How can I obfuscate (protect) JavaScript? . It contains some very good answers and also explain how this is security through obscurity.
That's how it works, it visible to everyone.
You can obfuscate it, though.
As Javascript is executed inside the browser, on the client's machine, it has to be sent to that client machine.
So, one way or another, the client has to be able to read it. So, no, you cannot prevent your users from seeing the JS code if they want to.
You could obfuscate it, but someone who really want to get to your source will always be able to (event if it's hard)... But the thing is : why would you prevent your users from seeing the JS source code if they want to ?
As a sidenote : with minified/obfuscated JS code, when you'll have a bug, it'll be really harder to track down... (and you really have to keep a no-obfuscated version on your development/testing machine)
I recommend minifying it and that will remove the comments and white spacing from your code. If you don't want the names of the variables visible then you will need to obfuscate it.
I'm not sure if this will work, I may try it sometime. But basically:
<script type="text/javascript" src="MyScript.php"></script>
In the PHP file add some sort of refering to check what page requested it or what the last page was. Then if it was one of your own pages, then echo the JS, if not then don't echo it. It will still be possible to read the JS, but even harder than just viewing source and de-obfuscate it. So you could also obfuscate the code inside the .php file.
no. javascript executes on the client side.
There is another way of hiding the Javascript for the most simple users
Just test here to try finding the javascript behind the textbox...
Yet, the script is still visible for experienced users -see the bottom of this post to understand why-
The idea is to put your javascript functions in a separate ".js" file. When loading your source PHP or HTML page, instead of calling it directly with
<SCRIPT language="JavaScript" SRC="original_file_to_hide.js"></SCRIPT>
, you will include a header php script that will copy the "mysource.js" file to a random "kcdslqkjfldsqkj.js" file, and modify your HTML file to call
<SCRIPT language="JavaScript" SRC="temporary_copy_of_the_file.js"></SCRIPT>
instead. After that, just delete the copy kcdslqkjfldsqkj.js file on your server, and when the user will look for the source code, the browser will link to a vanished file !!!
So this is for the theory, next, there is a small issue to workaround : if the HTML/PHP file is loaded too fast, your script will be vanished from your server before the browser had time to load the script.
Thus, you need
To copy the file to a different random name
To load the file in the source PHP file
To wait a few seconds after your HTML/PHP file is loaded before...
...Deleting the file
Here is the source for the HTML/PHP "test.php" page which is to be displayed to the end-user:
<?php
//javascript source code hiding technique : Philippe PUECH, 2013
//function thanks to Stackoverflow, slightly modified
//http://stackoverflow.com/questions/4356289/php-random-string-generator
function RandomString()
{
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$randstring = '';
for ($i = 0; $i < 10; $i++)
{
$randstring = $randstring.$characters[rand(0, strlen($characters))];
}
return $randstring;
}
//simple header script to create a copy of your "precious" javascript ".js" file
$original_filename="functions.js"; //find a better (complicated) name for your file
$hidden_filename=RandomString().".js"; //temporary filename
copy($original_filename,$hidden_filename);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Catch my Javascript if you can !</title>
</head>
<SCRIPT language="JavaScript" SRC="<?php echo($hidden_filename); ?>"></SCRIPT>
<script type="text/javascript">
</script>
<body onLoad="javascript:testfunc();">
This is the page with anything you like !
</body>
</html>
<?php
sleep(1);
//you can comment following line
echo "finished !";
unlink($hidden_filename);
?>
Here is the source for the "functions.js" file which will be hidden to the user.
// JavaScript Document
function testfunc(){
alert("It works...");
}
However, as told in the comment, the developer tools of the browser will keep the script in memory, and make it still visible to the curious users... ;-((

Categories