Admittedly, I'm new to some of this...
Building a website on a local server. It has a ton of JS function in an external JS file.
Site has a MYSQL DB. (I am still learning this).
As part of my calculations from functions in that external JS file, I want to update and/or read from that DB.
I have been trying to read up on node.js and trying to read up on PHP (still learning both), but I'm not sure if I'm sniffing in the right direction.
Do I somehow invoke functions from node.js from the external JS file? Do I somehow invoke the PHP (in the form of a function, I suppose) from the external JS file?
How does one typically do this?
I have definitely learned that this in the external JS file does not do the trick. First window appears, but second doesn't:
// Activate the node.js library for MYSQL access
alert("got here 1");
var mysql = require('./mysql');
alert("got here 2"); // nope, this never pops up
Higher-level advice might be more useful than detailed in-the-weeds advice...? Still very new to this.
Thank you kindly!
-=-=-=-=-
self-muttering thoughts... I am using the external JS file to hold a bunch of functions that do all kinds of manipulation and conformation to the data that I collect on the front end:
<button class="ButtonOperation" onclick="DataLog(document.getElementById('DataWindow').value,'NE_AssembleOrder')">Log Data</button>
Am I eventually going to discover that I should instead port all of these functions over to a big PHP file instead?
-=-=-=-=-
Okay, took a while before I better understood this. So, this is the answer that would have gotten me moving in the right direction (for any future reference):
The thing to understand is that for this project, you want to manipulate data to and from a database, which means that (at least for now, for the sake of simplicity), the key is to get your data into a package and send it up to the server, and then have a function running on the server take up the yoke from there.
The way to do that (old school), is with a form.
When you SUBMIT a form, all that data on the form is bundled up and sent to the server.
In this instance you have an index.html page, and that page will open a new page for each of the functions you're trying to track. Use JavaScript to pop open the window and then when you include the URL for the window, pop in a Popup_SpecificFunction.php file. (change SpecificFunction as needed)
So far, so good. ;)
Now, in that Popup_SpecificFunction.php, you will collect all your data under a single form. A good ol' HTML form, with a [SUBMIT] button. That very same Popup_SpecificFunction.php file also has a reference in the header, referring to the big main library of PHP functions -- which is a file sitting on the server.
That [SUBMIT] button invokes a ProcessAllThisData function -- which is on the server-side PHP file. In doing this, it sends all the data from the form -- including a lot of data you include in hidden controls -- to the serverside function.
And at that point, you are basically "on the server" with all your data, and then you can just code that function in PHP and manipulate the database and other stuff as needed.
Using the form was the thought-jump you needed, because prior to this, you've generally thought of forms as standalone data, but they can have actions associated with the entire forms.
You can still use JavaScript to do client-side stuff, but here's another thing that can trip a person up:
There is a difference between these two HTML items as far as whether or not you should use them to send data to and from the server, or whether or not you are just going to JavaScript something on that button:
<button></button>
and
<input type="button"></input>
You might have to experiment a bit to figure out which is which.
This was everything you needed to get you moving in the right direction.
Sincerely,
Future Me. :)
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?
For example, to link a script from a website, we use:
<script type="text/javascript" src="http://somedomain.example/scriptxyz.js">
</script>
Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?
For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?
Good question with a simple answer: you can't!
JavaScript is a client-side programming language, therefore it works on the client's machine, so you can't actually hide anything from the client.
Obfuscating your code is a good solution, but it's not enough, because, although it is hard, someone could decipher your code and "steal" your script.
There are a few ways of making your code hard to be stolen, but as I said nothing is bullet-proof.
Off the top of my head, one idea is to restrict access to your external js files from outside the page you embed your code in. In that case, if you have
<script type="text/javascript" src="myJs.js"></script>
and someone tries to access the myJs.js file in browser, he shouldn't be granted any access to the script source.
For example, if your page is written in PHP, you can include the script via the include function and let the script decide if it's safe" to return it's source.
In this example, you'll need the external "js" (written in PHP) file myJs.php:
<?php
$URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($URL != "my-domain.example/my-page.php")
die("/\*sry, no acces rights\*/");
?>
// your obfuscated script goes here
that would be included in your main page my-page.php:
<script type="text/javascript">
<?php include "myJs.php"; ?>;
</script>
This way, only the browser could see the js file contents.
Another interesting idea is that at the end of your script, you delete the contents of your dom script element, so that after the browser evaluates your code, the code disappears:
<script id="erasable" type="text/javascript">
//your code goes here
document.getElementById('erasable').innerHTML = "";
</script>
These are all just simple hacks that cannot, and I can't stress this enough: cannot, fully protect your js code, but they can sure piss off someone who is trying to "steal" your code.
Update:
I recently came across a very interesting article written by Patrick Weid on how to hide your js code, and he reveals a different approach: you can encode your source code into an image! Sure, that's not bullet proof either, but it's another fence that you could build around your code.
The idea behind this approach is that most browsers can use the canvas element to do pixel manipulation on images. And since the canvas pixel is represented by 4 values (rgba), each pixel can have a value in the range of 0-255. That means that you can store a character (actual it's ascii code) in every pixel. The rest of the encoding/decoding is trivial.
The only thing you can do is obfuscate your code to make it more difficult to read. No matter what you do, if you want the javascript to execute in their browser they'll have to have the code.
Just off the top of my head, you could do something like this (if you can create server-side scripts, which it sounds like you can):
Instead of loading the script like normal, send an AJAX request to a PHP page (it could be anything; I just use it myself). Have the PHP locate the file (maybe on a non-public part of the server), open it with file_get_contents, and return (read: echo) the contents as a string.
When this string returns to the JavaScript, have it create a new script tag, populate its innerHTML with the code you just received, and attach the tag to the page. (You might have trouble with this; innerHTML may not be what you need, but you can experiment.)
If you do this a lot, you might even want to set up a PHP page that accepts a GET variable with the script's name, so that you can dynamically grab different scripts using the same PHP. (Maybe you could use POST instead, to make it just a little harder for other people to see what you're doing. I don't know.)
EDIT: I thought you were only trying to hide the location of the script. This obviously wouldn't help much if you're trying to hide the script itself.
Google Closure Compiler, YUI compressor, Minify, /Packer/... etc, are options for compressing/obfuscating your JS codes. But none of them can help you from hiding your code from the users.
Anyone with decent knowledge can easily decode/de-obfuscate your code using tools like JS Beautifier. You name it.
So the answer is, you can always make your code harder to read/decode, but for sure there is no way to hide.
Forget it, this is not doable.
No matter what you try it will not work. All a user needs to do to discover your code and it's location is to look in the net tab in firebug or use fiddler to see what requests are being made.
From my knowledge, this is not possible.
Your browser has to have access to JS files to be able to execute them. If the browser has access, then browser's user also has access.
If you password protect your JS files, then the browser won't be able to access them, defeating the purpose of having JS in the first place.
I think the only way is to put required data on the server and allow only logged-in user to access the data as required (you can also make some calculations server side). This wont protect your javascript code but make it unoperatable without the server side code
I agree with everyone else here: With JS on the client, the cat is out of the bag and there is nothing completely foolproof that can be done.
Having said that; in some cases I do this to put some hurdles in the way of those who want to take a look at the code. This is how the algorithm works (roughly)
The server creates 3 hashed and salted values. One for the current timestamp, and the other two for each of the next 2 seconds. These values are sent over to the client via Ajax to the client as a comma delimited string; from my PHP module. In some cases, I think you can hard-bake these values into a script section of HTML when the page is formed, and delete that script tag once the use of the hashes is over The server is CORS protected and does all the usual SERVER_NAME etc check (which is not much of a protection but at least provides some modicum of resistance to script kiddies).
Also it would be nice, if the the server checks if there was indeed an authenticated user's client doing this
The client then sends the same 3 hashed values back to the server thru an ajax call to fetch the actual JS that I need. The server checks the hashes against the current time stamp there... The three values ensure that the data is being sent within the 3 second window to account for latency between the browser and the server
The server needs to be convinced that one of the hashes is
matched correctly; and if so it would send over the crucial JS back
to the client. This is a simple, crude "One time use Password"
without the need for any database at the back end.
This means, that any hacker has only the 3 second window period since the generation of the first set of hashes to get to the actual JS code.
The entire client code can be inside an IIFE function so some of the variables inside the client are even more harder to read from the Inspector console
This is not any deep solution: A determined hacker can register, get an account and then ask the server to generate the first three hashes; by doing tricks to go around Ajax and CORS; and then make the client perform the second call to get to the actual code -- but it is a reasonable amount of work.
Moreover, if the Salt used by the server is based on the login credentials; the server may be able to detect who is that user who tried to retreive the sensitive JS (The server needs to do some more additional work regarding the behaviour of the user AFTER the sensitive JS was retreived, and block the person if the person, say for example, did not do some other activity which was expected)
An old, crude version of this was done for a hackathon here: http://planwithin.com/demo/tadr.html That wil not work in case the server detects too much latency, and it goes beyond the 3 second window period
As I said in the comment I left on gion_13 answer before (please read), you really can't. Not with javascript.
If you don't want the code to be available client-side (= stealable without great efforts),
my suggestion would be to make use of PHP (ASP,Python,Perl,Ruby,JSP + Java-Servlets) that is processed server-side and only the results of the computation/code execution are served to the user. Or, if you prefer, even Flash or a Java-Applet that let client-side computation/code execution but are compiled and thus harder to reverse-engine (not impossible thus).
Just my 2 cents.
You can also set up a mime type for application/JavaScript to run as PHP, .NET, Java, or whatever language you're using. I've done this for dynamic CSS files in the past.
I know that this is the wrong time to be answering this question but i just thought of something
i know it might be stressful but atleast it might still work
Now the trick is to create a lot of server side encoding scripts, they have to be decodable(for example a script that replaces all vowels with numbers and add the letter 'a' to every consonant so that the word 'bat' becomes ba1ta) then create a script that will randomize between the encoding scripts and create a cookie with the name of the encoding script being used (quick tip: try not to use the actual name of the encoding script for the cookie for example if our cookie is name 'encoding_script_being_used' and the randomizing script chooses an encoding script named MD10 try not to use MD10 as the value of the cookie but 'encoding_script4567656' just to prevent guessing) then after the cookie has been created another script will check for the cookie named 'encoding_script_being_used' and get the value, then it will determine what encoding script is being used.
Now the reason for randomizing between the encoding scripts was that the server side language will randomize which script to use to decode your javascript.js and then create a session or cookie to know which encoding scripts was used
then the server side language will also encode your javascript .js and put it as a cookie
so now let me summarize with an example
PHP randomizes between a list of encoding scripts and encrypts javascript.js then it create a cookie telling the client side language which encoding script was used then client side language decodes the javascript.js cookie(which is obviously encoded)
so people can't steal your code
but i would not advise this because
it is a long process
It is too stressful
use nwjs i think helpful it can compile to bin then you can use it to make win,mac and linux application
This method partially works if you do not want to expose the most sensible part of your algorithm.
Create WebAssembly modules (.wasm), import them, and expose only your JS, etc... workflow. In this way the algorithm is protected since it is extremely difficult to revert assembly code into a more human readable format.
After having produced the wasm module and imported correclty, you can use your code as you normallt do:
<body id="wasm-example">
<script type="module">
import init from "./pkg/glue_code.js";
init().then(() => {
console.log("WASM Loaded");
});
</script>
</body>
We have a PHP script that runs daily ( already working fine) that generates a PDF report for our employees. Now upon this generated PDF we need to add attachments/files that are generated by a JavaScript function. In this JavaScript function we work with data, loaded from our database. This data is different every day and saves a daily attachment file on our server.
In the PHP script mentioned above, we need to include those files/attachments created by JS.
My though was to run a JS function when the PHP script runs, daily. As I have found in this stackoverflow question ( see answer by Vladimir ) it is basically impossible to run js from a PHP script.
How can I achieve this? How can I make sure the files/attachments are generated by JS every day, before the PHP script runs?
(It is allowed for the javascript attachments/files to be generated at 2am, for example. While the PHP script can run at 3am. It doesn't have to be the exact same time).
Any suggestinos would help!
I would work toward using curl to get the JS to run by calling the html file with curl from within the PHP script.
A lot of this depends, of course, on what the JS is doing, exactly, but if you have access to both codebases, you should be able to get it to work, by saving the response from curl into a variable and then parsing and handling it appropriately.
I know this answer is a generalization, but this is because we only generally know how the JS and PHP need to interact. I will be happy to be more specific if we get a few more details.
Good luck and Take care,
JB
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to create a website for a friend of mine using PHP. It is basically an online store.
I want to use new features of HTML5, CSS3, jQuery and other JS libraries.And I want to keep all the document generation and manipulation separate from PHP.
I have done a lot of searching on Google. People come up with MVC architecture. And that's all good.But the problem is in all the examples or tutorials that I found; people retrieve the data from the SQL based databases, and then echo or print it to generate html, or use some ORM classes to display it. I don't know much about ORM or PHP frameworks.
I have always made pet projects, small websites, nothing like this medium-sized Store.
The way I understand the MVC architecture is this:
**Model:** Basic purpose is to save and retrieve data from the databases.
**Controller:** Do some operations on the data to either store them using Model, or do some operations on the retrieved data (again using the Model), to be passed to the View.
**View:** This is used to display the user the content.
What I want to do is do almost ZERO html generation using PHP.Instead I was thinking of a approach in which :Model is used for database handling only. Controller is used to convert that data into JSON objects, and make those JSON objects available to the appropriate Views.Then using JavaScript I will do the DOM Manipulations according to the JSON objects.
Is this approach any good ? If yes how to do it (especially the part of converting the data retrieved from database to JSON objects).
If you can provide me with a better approach where I won't have to do generate html using PHP, and use PHP for front-end as less as possible.
I am doing all the front-end stuff which the user is gonna see. My friend will be doing all the database handling. I don't wanna get involved in the PHP part, and if it is mandatory (i.e. there is no way-out) then as little as possible.
Please provide me with some solution. In desperate need here.
EDIT: I am especially talking about echo and print commands. I would like to have a fresh slate to work on instead of getting the html creation mixed with PHP and JavaScript.
If NOT using these commands is not suggested based on the fact that the user may be on mobile device, or have JavaScript turned off. Then is it possible to have a simple looking website with all the data displayed if JavaScript is turned off; and if it's not turned off then remove all those elements from the DOM and make a fresh DOM with JavaScript. However the main hindrance to this is converting the data retrieved from database to JSON object so that it can be used by the JavaScript.
I don't think this is possible, but is there some way in which PHP variables can be directly used by JavaScript ?
PHP does never manipulate the DOM, the DOM is purely client side, while php is purely server-side. PHP can generate HTML, which will be sent to the client, and processed to a DOM by the clients browser.
If you want to (nearly) completely split it in two parts, you could split it into an API server (php & database) which will provide a RESTful JSON-API and a content server, which will provide your static HTML, CSS and Javascript files.
The Javascript on the content server will connect to the API server with AJAX get and post requests to retrieve and send data to the database.
Yes, it's entirely possible to do what you're describing. You'd use static HTML files for the basic page setup, the usual CSS and images and such, and your PHP would only be used to generate JSON to return to the client and get used by JavaScript. So for instance:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example</title>
</head>
<body>
<table id="theTable">
<tbody>
<tr><em>Loading...</em></tr>
</tbody>
</table>
<script src="yourscript.js"></script>
</body>
</html>
yourscript.js:
getDataViaAjax("data.php", function(data) {
var table = document.getElementById("theTable");
// ...fill in the table using the information from `data`...
});
data.php:
<?php
// Get data from somewhere
// ...
// Output it
echo json_encode($theData);
?>
Obviously the table there is just an example. You'd probably have much more static content, and a few places where you wanted to add dynamic content.
This is a perfectly feasible approach, and the separation of concerns helps as the team expands.
However, note that if you do this, any page that has content from the DB will result in two HTTP requests to the server (one to load the HTML, the other — which won't start until after the first one is at least partially finished — to load the data) rather than one. In general, the goal is to minimize HTTP requests. So there are trade-offs.
I don't think this is possible, but is there some way in which PHP variables can be directly used by JavaScript ?
Correct, that's not possible. There are frameworks like Meteor (that one isn't PHP-based) that handle the middle layer for you, though, and make it seem a lot like that's happening.
You can also look at tools like AngularJS and KnockoutJS that can bind your JavaScript data objects to DOM elements, saving you a huge amount of manual update code, or even just things like Handlebars that render templated stuff for you.
I think what you are looking for is a client-side template engine, where the document is built client-side using ajax queries. The ones I have heard good things about are Handlebars and Mustache, though I'm sure there are others to choose from.
But even with such a solution, I imagine that some amount of server-side HTML needs to be output to "prime the pump", in which case, you would want to consider a server-side template engine like Smarty or whatever the latest-and-greatest equivalent is. With a server-side template engine, you would write the templates as standalone files (like .tpl for Smarty) and PHP would consume the template as an object and then pass in any unique variables for the template via the template-engine's methods and then you would call the display method for the template.
In either scenario (or a combination of both) you are separating your final HTML output from PHP so that PHP is interacting with the templates rather than doing plain echo "<div>This looks so Web 1.0</div>"; which I think is what you are trying to avoid.
I'm using W3 Schools' AJAX PHP Example (http://www.w3schools.com/ajax/ajax_aspphp.asp) as the foundation for my guestlist web app that uses data stored in LocalStorage, rather than MySQL database, in order for users to be able to search while offline. Now I'm trying to finalize the search guest part.
This is how it works (and differs from the example above):
(index.php). Placing / mirroring all records from MySQL db into
javascript arrays
(index.php). Storing the above mentioned js arrays in LocalStorage
(index.php). By using the AJAX GET code used in the example,
sending the searched item to getData.html (a html file instead of
php file as W3 does)
(getData.html). Successfully getting the searched item through the
URL parameter
(getData.html). Looping through and matching values like in the
above example (code rewriten in javascript).
BUT here ends my success. The AJAX code is identical to the one in the above supplied example (except of course the reference to getData.html), and everything else seems to be working so I won't bother you with my entire code. In the example mentioned, at the very buttom of the PHP-file it says
//output the response
echo $response;
This is where javascript seems to be failing. I've desperately been trying to echo / print the response but for some reason, it doesn't get returned to index.php properly. The only way to force it to display at least something is to either use php echo, or simply just write plain html text somewhere in the getData document within the HTML tags. I've also tried getElementById('txtHint').innerHTML = "hello"; to see if it works but with no success.
The most obvious way to do this would be to simply replace echo $response with the equivalent in js:
document.write(response);
but whatever document.write prints, nothing's dipslayed. The div in which the "hint" is supposed to pop up is yet empty. I've googled solutions, different ways of printing js variables with no further success. Perhaps, document.write is not "compatible" with XML or AJAX responseText? There must be a simple solution to this. Hope you guys can help me out. Thanks!
php is of course a server-side language that emits a page and runs on your back end.
js is of course a client-side language that runs on the user's front end.
document.write() is the proper function for emitting client-side text; it runs at page load time. Example:
<b>My domain is: <script>document.write(document.domain);</script></b>
properly gives
My domain is: www.mydomain.com