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... ;-((
Related
How to write a PHP code (using public id) that can embed into HTML file (abc.html) when we open that HTML file that has to call another PHP file(there we can insert stats of that file into database).
if i cannot do this in php, is there any other way except renaming html file extension to php extension
Do you mean this?
<html>
...
<body>
<?php echo "test"; ?>
</body>
</html>
or
using exec('php foo.php'); to call another php file?
or
including another php file using
include 'foo.php';
require 'anotherfoo.php';
EDIT:
Or you can use ajax to call a .php file to the abc.html file.
$.ajax({
type: 'POST',
url: 'foo.php',
data: 'username=myuser&id=123456',
success: function(result) {
/* do something with result here */
}
});
You need to have the jquery library which can be downloaded here.
If I understood you correctly, you're wanting to use the PHP include function. You may also want to check PHP's include_once function depending on what you're doing.
You will need to make sure the "HTML" page is actually a PHP page. If your page is already written and exists as HTML and not PHP, you will need sufficient privileges to edit the MIME types and associate .html (or whatever file extention you're using) with PHP processes on the server side. Otherwise you will need to recreate the page as a PHP page using the .php file extension.
For example you may have code like this in the initial file:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>My Web page title</TITLE>
</HEAD>
<BODY>
<p>Welcome to my website</p>
<?php include('this_page.php'); ?>
</BODY>
</HTML>
This will call the this_page.php file and allow it to execute any scripts within it.
I hope this helps you.
You cannot embed PHP into an web page, PHP is a server side scripting language, which means it is only executed on the server. The user does not even know whether you are using PHP (except for the .php extension, but that means nothing.)
You can however call a PHP script from another PHP script, e.g.
exec('php script.php');
include(other_file.php), include_once(other_file.php), require(other_file.php), require_once(other_file.php) ...
or
use an iframe or exec(other_file.php)
Within your HTML you could use a tag such as an image or script to call your php script. This could be useful if you want your PHP to do something simple such as to increment a counter in a database.
<img src="/path/to/script.php" alt="" />
This is trivial as long as you don't want the executing PHP to return anything visible within the page. If you use an image tag, after you've finished with whatever processing you are doing, it might be best to have your PHP return an image of some sort - but it could be as trivial as a 1px by 1px transparent gif.
$im = file_get_contents('/path/to/your/image/transparent.gif');
header('content-type: image/gif');
echo $im;
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 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.
If you look at the source of this page http://kingston.talking-newspapers.co.uk/ you will see a large amount of inline javascript near the top.
I don't really want all this extra stuff floating around in my page source, I'd much rather get it off into a script tag, and then I can minify it and all sorts.
If I call it as a php file, this SHOULD work in theory, I just end the js file extension with php instead, and in the header I put the following:
header("Content-type:application/x-javascript");
but... a lot of the php variables used to generate the playlist within the javascript are setup at the beginning of the main index.php file, and in calling this php-generated js playlist file like this, it seems to evaluate it entirely separately, so it's full of errors.
The only way round it I can think of is to have the page write a file, then immediately read it in. The other thing is, the playlist is likely to change often and dynamically, so I think I need to get minify to NOT cache it?
I made the solution by following this tutorial, which redirects the generate inline script to a file, then immediately reads that file in.
http://my.opera.com/zomg/blog/2007/10/03/how-to-easily-redirect-php-output-to-a-file
So now my page looks like:
<?php
require("./filewriter.php");
$obfw = new OB_FileWriter('jplay_gen_playlist.js');
$obfw->start();
require($includesdir . "jplayerscript.php");
$obfw->end();
?>
<script type="text/javascript" src="jplay_gen_playlist.js"></script>
et voila! All nicely external, can be minified, cached etc.
You can do it in two ways. First would be set up the variable inline and then include the script:
<script type="text/javascript">
var myPlayList = [
{
name: "Introduction and guidance on usage",
mp3:"http://www.talking-newspapers.co.uk/find/soundfiles/TnHomePageIntro.mp3",
ogg:"http://www.talking-newspapers.co.uk/find/soundfiles/kingstonkt9.ogg"
}
...
</script>
<script type="text/javascript" src="myinclude.js"></script>
The other would be to have your included .js file a simple library of functions which you include at the top of the page and then call from some inline javascript:
<script type="text/javascript" src="myinclude.js"></script>
....
<script type="text/javascript">
$(function() {
var myPlayList = [ ... ];
startPlaylist(myPlayList);
});
</script>
I would personally choose the second method. You shouldn't need to generate any of the script dynamically (as far as I can see, it can all be hard-coded except for the playlist, right?) Any other things you need to pass to the script could still be passed in by your startPlaylist() method call anyway.
I have a page that does the following:
The browser loads a very simple page with a valid head and body, with only a script/noscript pair as content.
In the body, it has a script (script a) that runs a function onLoad. This function dynamically includes a second script (script b), and runs a function in it when it becomes available.
The second script is a .js file that does various work.
Both scripts are parsed by PHP and use the application/x-javascript content type.
Now, I have this all working just fine, except a couple of JS hiccups. JavaScript isn't one of my strong languages, so I'm hoping these are simple issues and somebody can point me in the right direction.
Problem 1: If I do a simple alert('you are in script b'); in the second script, it works as expected. However, if I do anything else, it works fine, and then the browser keeps indicating that it is loading forever. This is the color tween in firefox, or the spinning thing in IE.
I've tried ending the script in different ways, and nothing seems to help. Any idea how to indicate to the browser that the script is all the way loaded? It's a .js file that is forced to parse through PHP.
Problem 2: The second script doesn't seem to be included at all in either Opera or Google Chrome. Works fine in FF/IE, other than the loading issue. Can anyone see if Im using something that isn't compatible in the loading of the second script?
Thanks!
Update:
Thanks for the answers. I actually have firebug, which is why I know everything is working properly (in FF, at least). I don't actually know that the script isn't working in Opera/Chrome, but nothing happens.
It is quite a bit of code =o) I will copy the actual responses out of firebug and post those, so you can see exactly what the code is. As far as the webserver closing the connection, I was thinking that too, but it seems odd that if I make script b into alert('whatever'); it will alert and then stop loading, but it I do everything exactly identical, but make the script document.write('whatever); it will load forever.
Here are the scripts, updated, copied directly from the net tab of firebug:
Note that discoverfire.net is an internal domain, so you won't be able to load anything from there...
Initial HTML page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Welcome!</title>
<style>body { font-family:arial; }</style>
<script language="JavaScript" type="text/javascript" src="http://www.discoverfire.net/analytics/l/a.js">
</script>
<script language="JavaScript" type="text/javascript">
document.onload = Start();
function Start(){
TAFKing_version = '1.0';
TAFKing_lkey = '19-8O-KKA8HV';
TAFKing_Lander();
}
</script>
</head>
<body>
<noscript>
Oops! We can't forward you properly because your JavaScript is turned off.<br /><br />
<a href='http://www.discoverfire.net/analytics/l/noscript/19-8O-KKA8HV.html'>Please click here to continue.</a>
<img src='http://www.discoverfire.net/analytics/l/imp/19-8O-KKA8HV.png' border='0' alt='tell a friend' />
</noscript>
</body>
</html>
** Script A (...a.js): http://www.discoverfire.net/analytics/l/a.js **
function TAFKing_Lander(){
version = TAFKing_version;
lkey = TAFKing_lkey;
var scrb = document.createElement('script');
scrb.type = 'text/javascript';
scrb.src = 'http://www.discoverfire.net/analytics/l/b.js?lkey='+lkey+'&version='+version+'&cb=4eohe8e65'
;
document.getElementsByTagName('head')[0].appendChild(scrb);
Interval = setInterval("Waiter()", 10);
return;
}
function Waiter(){
if(window.TAFKing_LanderB) {
clearInterval(Interval);
TAFKing_LanderB();
}
}
Script B (...b.js): http://www.discoverfire.net/analytics/l/b.js?lkey=19-8O-KKA8HV&version=1.0&cb=4eohe8e65
function TAFKing_LanderB(){
document.write("there are just a whole bunch of doc.writes here that build a simple table");
}
I bet it is nothing related with the scripts, but with the webserver. Your description, specially that it affects many browsers, and some of them don't even run the scripts, leads me to believe that the webserver is not closing the connection. Perhaps the webserver is not properly handling HTTP/1.1 Keep-alive requests.
Try using Firebug in Firefox. Install it, enable it for your page, reload the page and check the "Net" tab for what really is keeping the connection open.
This is a lot of code to go through. You should definitely get Firebug to help you diagnose it. The latest version will even show you when/if the onload events occur.
Firebug will also allow you to output message simply by writing console.log('somevar=',var); to test their values. You can even use the console to test value after the page has loaded since you're using the global name space.
Off the top of my head, I would make sure the connection properly closes in php. Also
document.onload = Start();
would assign the result of Start() to onload, not Start which is defined later.
Also window.onload is more compatible/standard.
You may want to save the output of your js files as outputphpA.js and outputphpB.js, directly source those and see if the loading behavior differs. That should help diagnose if it's a php issue.