简体   繁体   中英

How can I “cloak” my Javascript and CSS files using PHP?

Would it be possible to display different content if someone opened one of my .js or .css files in a browser? I configured Apache to execute PHP code in .js and .css files. How can I detect if the file was requested by a webpage or viewed directly by an user?

Edit: I know there's no way to hide my files 100%. I'm looking for the best way to discourage people from copying my code.

Nothing on the web that works in a browser can be genuinely cloaked. The browser is just an agent requesting the file, same as any agent requesting the file for any use. A server knows no difference between a browser downloading a JS file as part of a web page and a user downloading the JS file to view it. To the server, they are just requests to download the file. The server doesn't know what's going to be done with it.

Even further, JS files and CSS files are usually kept in the disk cache (for performance reasons) where they can be retrieved independent of the server.

The only thing you can do is to obscure your code with minification and obfuscation. Minification makes sense because it also makes thing more efficient. I wouldn't personally recommend obfuscation because it doesn't really stop a determined viewer - it only slows them down slightly. If the browser can understand the JS file to run it, then so can a hacker.

In general, people seem to think that their javascript is somehow way more important a secret than it really is. If you do have some sort of secret algorithm that really needs to be protected, then your best bet is to keep the code for that on the server and use ajax calls to access it from your client javascript as needed.

You can detect if the file is called directly by the user checking the HTTP Referrer header. But it will not prevent the user to check in Firebug or equivalent tools to see the source of your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM