0

They say that It is not possible, but what about it? I was working on project to improve my skills and found a trick to run PHP from JS.

async function runphp() {
    const response = await fetch('phpfile.php');
    const data = await response.json(); //optional
  }

So we just make a request and all the code inside PHP will run. Also for eg. if we want just one function from PHP to run it is possible to make cookie in javascript, read it in php and run only some functions based on cookie value. I don't know anything about security and I'm working on localhost so the question is: Is it good if I add project with this on my website?

  • [What is the difference between client-side and server-side programming?](https://stackoverflow.com/q/13840429) – VLAZ Dec 15 '21 at 20:13
  • 6
    It's not really a "trick", it's just a different way to make your browser generate a HTTP request (which will then cause the PHP script to be executed when the server receives that request), in a manner which doesn't cause your whole page to refresh (which it would if you used the other methods such as a link being clicked, or a form being submitted). It's called AJAX and it's been around for 20 years or more. – ADyson Dec 15 '21 at 20:13
  • yes, there is no problem – Nasser Hajlawi Dec 15 '21 at 20:14
  • `run only some functions based on cookie value`...well, you could, but why not just pass some parameters directly to the PHP script via the `fetch` request? – ADyson Dec 15 '21 at 20:15
  • `Is it good`... a bit broad, that. Can you define "good"? If it works for you, then use it. There isn't anything _inherently_ insecure about what you're doing. Security comes from understanding potential threats and mitigating them whilst still achieving your goals. – ADyson Dec 15 '21 at 20:16
  • @ADyson Huge thanks for reply. Can you send link or explain how to send those parameters? I heard about fetch with POST method but I didn't find any good explanation – Royal Skoker Dec 15 '21 at 21:02
  • You can use post or get, you can send parameters on the querystring of the URL, or in the request body. Just like any other HTTP request. – ADyson Dec 15 '21 at 21:36
  • Super-simple examples at the start of this article: https://medium.com/meta-box/how-to-send-get-and-post-requests-with-javascript-fetch-api-d0685b7ee6ed and in many other places online – ADyson Dec 15 '21 at 21:37
  • Thanks for your help, I really appreciate it. The article is exactly what I needed. Much better than the one I saw before. – Royal Skoker Dec 15 '21 at 21:44

0 Answers0