Establing connection to MYSQL Database [PHP] - javascript

I had this random question in my mind while I was surfing on the net...
Is it possible to establish connection to MYSQL database WITHOUT refreshing? Like if there is a button in a page which when clicked it secretly establishes connection to Database without even letting user notice any change in the webpage, Everything looks the same but secretly a webpage connects to the database..
I know.. This process is possible in Javascript, but I wanted to find out a way in PHP

When the page has been loaded. PHP can't be used anymore because it's a server side language. Javascript on the other hand works client side. Which means you can execute functions and such on the client's machine without page reload.
AJAX can enable you to 'open' a PHP and execute PHP code (not JS) without page reload. If you will, it's like you're opening a PHP page but it's not visible to the user, it runs the PHP file 'behind'.

As others have said, remember that PHP is a "server-side" language, and that the SQL database also lives on the "server side." The JavaScript application, running on the client, has no direct access to it.
What the JavaScript application must do, then, is to issue asynchronous requests ("AJAX ...") to the server, asking for whatever it wants. The end-user will not be directly aware that this is going on, and the content of the screen-display won't necessarily change (unless you change it).
As part of servicing the (properly authorized ...) request, the PHP side might connect to the database and issue queries against it to get the information that it needs, in order to prepare and send-back a reply to the (JavaScript) client.
Now, the JavaScript side won't necessarily know, nor will it care, just how the results that it receives were actually obtained by the PHP code. It only "issues a request, and, sometime thereafter, gets a corresponding answer."

Related

Security implications of having credentials show up in HTML

I'm currently developing a java backend and a frontend using php, html and javascript for a private project (but which I'd eventually like to open source), which means that access is limited to my LAN anyway and security does not play a vital role at the moment but might in the future.
As I'm most comfortable with coding in java most of the data processing and storage (MySQL) is handled in java and provided over http to the frontend (javascript; fetch()).
Additionally this java backend handles the authentication process which means I have to pass the login credentials with a fetch call in javascript to the backend.
As I'm not really into advanced web programming, I figured a basic POST -> REDIRECT -> GET setup for the login should suffice and I used similar login procedures (but handling the authentication in PHP) before. Therefore:
The client fills out a HTML-Form and submits it
The browser does a POST request to /login passing the credentials and the target page
PHP then returns the HTML containing a javascript portion that holds the credentials in plain text login("<?php echo $_POST['username'] ?>", "<?php echo $_POST['password'] ?>", "<?php echo $_POST['target'] ?>");
Javascript then fetches the java-backend with those credentials to create a session
Javascript issues window.location.replace(target); and the client is redirected to the target page (where authentication is handled via the session cookie)
I'm currently overthinking, if this is a good idea from an efficiency and security perspective. My current idea is to use the form to directly fetch the data to the backend with javascript instead of using a POST request to an additional page (skipping step 2 and 3 above):
This would mean that first of all PHP would never see the credentials (which would be one less point of failure) and that the credentials probably would not show up in the HTML. Additionally, this would cut loading times as the POST is not needed anymore.
My questions are therefore:
Is it bad security practice to have credentials show up in the HTML (as it is with having them in the URL, to prevent the user from accidentally sending their credentials to someone while copying the URL)? What are the risks associated with this? Could these credentials be read by any JS-libraries used or browser extensions? If so, those could probably also read the credentials which I type into the form anyway?
Is my alternative setup better from a security perspective (and efficiency perspective)?
Are there any other suggestions for improving security in this context?
Thank you for helping me.
Short summary of this post and the discussion below:
By first POSTing the credentials to PHP and then serving them back to the client in the returned HTML, latency (due to an additional page load) is increased, PHP is added as another point of failure and the system is theoretically opened up to more security problems (i.e. through javascript or browser extensions scanning the code or by hacking the PHP server).
Therefore two solutions are plausible:
Skip PHP entirely and let the login be handled by javascript and the java backend only (detailed description of this procedure below in points 1 - 5; this is only possible as the PHP server doesn't need authentication information in this specific use case)
POST the credentials to PHP and let PHP communicate with the java backend responsible for authentication, instead of reserving them to the client
Original post:
I don't quite understand why you think the PHP backend can't be trusted but in your scheme the PHP already gets your credentials, thanks to that original POST. If you want to avoid using PHP why not have your form call a JavaCcript function instead of POSTing to the PHP backend in the first place:
User enters credentials
User clicks "login"
JavaScript intercepts the login attempt, calls login()
JavaScript fetches user,pass from document body (getElementById(...))
JavaScript contacts the Java backend which handles login
No PHP needed. But I might wonder why that's necessary - if you can't trust your own backend, what exactly are your security practices? If your PHP can't be trusted why would your Java be any better?
In your scheme you're already passing the credentials to the PHP backend in the POST request. If your concern is PHP not knowing the credentials you've already failed.
As for efficiency, your scheme has extra page loads, which will use bandwidth, maximize latency (as opposed to the goal of minimizing latency) and make you look incompetent to users who notice the extra redirect. JavaScript sounds like the better solution is you want to write your database code in Java.
As far as the credentials appearing in the HTML there's really no difference since the only person who could access them would be the user (who already typed them in). If they input incorrect credentials they'll only see incorrect credentials. That said, it violates best practice and probably isn't a good idea.
Is it bad security practice to have credentials show up in the HTML (as it is with having them in the URL, to prevent the user from accidentally sending their credentials to someone while copying the URL)? What are the risks associated with this? Could these credentials be read by any JS-libraries used or browser extensions? If so, those could probably also read the credentials which I type into the form anyway?
The answer is Yes, it's entirely bad practice and opens you up to extra risk. They're probably not too concerning but you got it exactly right - there are more places where malicious code could read the credentials, and any JS library or installed extension can read them.
Is my alternative setup better from a security perspective (and efficiency perspective)?
No and no. From the security perspective it adds another point of failure; instead of needing to hack the Java backend they could choose to hack the PHP backend instead. This wouldn't necessarily be the end of the world but is an extra point of failure.
Are there any other suggestions for improving security in this context?
I explained my advice above. Either suck it up and use PHP, or use JavaScript to bypass PHP entirely.
One more thing, when handling logins make sure the Java passes a secret value (unique to each session) and the server verifies that value on every page load. When I was working as an ethical hacker an app I tested passed an auth token (OAuth2) but the server didn't actually verify it was correct, just that the client said it was valid. Make sure the server checks anything the client does.
Also, emphasis on unique to each session since a secret value that stays the same for each session is definitely gonna be the worst-kept secret you've ever wished hadn't got out.

Can Javascript access an external or localhost database or nodejs?

I'm using a javascript scripting engine for a MUD i'm playing, they have a javascript client hosted on their server. I'm wanting to store some information in a database and access it from the client (or inject it somehow into the client) but I'm not seeing how I could do that.
Basically I can write javascript files into the trigger section of the website and they fire. It has Javascript and JQuery options. It does not have a database option on their end, which is why I'm trying to add it myself.
I know client side javascript has a lot of restrictions on it, so I'm not sure how far I could really go with this.
I think you might be able to do this, but it's going to be hacky.
If you're able to attach a script node to the dom, you can trigger GET requests with no origin restrictions wherever you want. You would do that to your own backend.
You would have to throw away all good practices and use GET requests with a lot of query params so send data to that (your) backend.
You would have to write the backend so that it does whatever you want with the data, e.g. store it in the db.
You would have to make sure you return valid js to the client, even if it's only to dismiss it.
Alternatively...
you could load an iframe to a site you control, and change the iframe src with the data, and then do with the data whatever you want (like sending it to some bakcend of yours properly) in your site (that's loaded in the iframe) by detecting changes in the url...

"Run and forget" a link from javascript

I'm working on a site that will keep a track of when user enters a page and how long he's there (or to be more specific, when he leaves)
I have set up a node server and I would like to run the action there, but the question is irrelevant to node itself, it's a javascript related question.
My goal is to have javascript call a certain method with specific parameters and then forget about that. However, I would like to avoid ajax if possible, I know I could do it with ajax, but I think that's an overkill and I'm not sure even if ajax would work on a node server.
What I'm looking at is something like
*User opens web page
*Javascript runs the script, let's say.
Run("http://server.com/User/EnteredPage/IDOFUSER");
and when the user closes the page
Run("http://server.com/User/LeftPage/IDOFUSER");
Point is.. I don't need anything from that call, I just want the javascript to run it, to save the data I need and that's it.
HTTP is stateless. The browser asks for a resource. The server gives the browser the resource. The end.
The request is done and dealt with. There is no further communication about that request so the server doesn't know when the visitor has left the page that it served up. If you want to know that, then you need another request to tell the server about it.
The problem with that approach is that the visitor might leave the page by:
Quitting their browser entirely
Running out of battery
Getting disconnected from the network
… so you can't reliably send a new request when the user leaves the page.
So the best you can do is to have the browser tell the server that the user hasn't left yet (you could do this with Ajax or (potentially more efficiently) WebSockets).
Combine this with a timer based action on the server that tests how long it has been since the visitor's browser last sent an I'm still here message and use that to call your visitor has left function.

Can PHP run after the page is loaded?

So PHP is executed server-side. But is it possible for PHP to be run after the page is loaded?
To illustrate, if I had a value (stored in a file, lets say) that changed every second. When I hit a button that uses Javascript to ask PHP to get that value, does it display what the value currently is, or what it was at page load?
I think you need to get one of those diagrams that show how basic HTTP and the web server works. It will make more sense to you, than explained in plain words here.
In the simplest possible case, the result of you typing some address and getting a web page with its contents can be summed up, due to a result of process in request/response relationship between your browser and a web server located somewhere in the world.
Plain HTML
In a less simpler way, think of it like this. basically, if a page is during a refresh phase, (meaning you clicked something and are waiting for a data to comeback) then, that means it is getting/loading the response from the web server. If the web server does not have PHP installed as a module, then the only thing it is waiting/loading (in many cases) is plain HTML content.
With PHP
On the other hand, if we assume you have a file called index.php in your webserver, and have PHP is installed, in this case the web server will send everything that appears in-between <?php ?> to the PHP interpreter, first, then wait for it until PHP does its magic and send back to the server only the result.
<?php
echo 1+1;
?>
So, in the above case, the webserver (ex: Apache, Nginx) does not care what is inside the opening and closing tags, and sends the entire code to the PHP interpreter, and PHP would compute that script according the way it understands it and sends only the computed result back to the server, as plain HTML. In this case the number 2.
The role of AJAX.
AJAX (Asynchronous JavaScript and XML) is a technique used Javascript, to help you send requests and receive the response without having to load the page. This is usually done by using the browsers XHR object. So, there is no mystery in this whole shebang.
The above can be summed up simply in the following steps.
Enter foo.com browser sends a request to the server of foo.com
server/browser exchange messages server allows browser to aquire
information server sends index.php back to browser if <?php tag
is found in the script, server sends all the codes inclosed in those
tags to the PHP interpreter The PHP interpreter, compiles the query
and sends the result as HTMl
PHP is server-side script, before return page content to client side like browser, it should parse all the PHP logic into HTML logic, so it should display the value which was at page load. And if your PHP logic consumes long time to execute, it will delay the content display at client side.
Your example case is really difficult to explain, without getting technical, or using a lot of chained logic...
...however, I'll try to keep this a little more simple:
The overwhelmingly vast majority of the time, PHP will run only when something connects to the server, and will stop running as soon as it's done running the script that was accessed.
That "something" might be a page-load (//mysite/index.php), or it might be issuing an XMLHttpRequest ("AJAX") to ask the server for data (//mysite/articles.json).
Not all languages work this way.

Is it possible to make server push without using javascript?

Is there some mechanism to provide server push technology using plain HTML, without using javascript (or any other script languages on the client side).
Under "server push" I mean process where the server to update some part of the page content when needed.
I don't know of any way that true server push can be used without any javascript in the page.
Without javascript, the only thing I'm aware of is a meta refresh tag that would tell the browser to refresh this page after some particular time interval. This tag applies to a whole page only. If you wanted only part of a page to be updated, you could use an iframe and have only the iframe be updated. Of course, this is not server push, but a client-driven auto-update and it will be run on a predetermined interval, not just when there is actually new data. For something smarter than this, you will need javascript.
The most efficient server-push would be to use javascript from the page to connect to your server over a websocket and then have the server just send data to the page via the websocket whenever it wants (true server-push). The client's javascript can then respond to the receipt of that websocket data by updating a particular piece of the page.

Categories

Resources