If you're trying to build something like a SaaS, Micro-SaaS or just a website with some functionalities, then you're going to need to learn how to Perform backend operations with PHP.
First of all, why would you need to perform backend operations in PHP?
Say you're trying to build a web application and you want it to perform tasks such as Machine Learning, Web Scraping and Language Translation, then you'd probably want to perform them in the backend, there are 4 main reasons for this:
- Your frontend language may not be able to perform the task well enough or doesn't fulfill all the desired functionalities.
- The task is too memory intensive and/or executes for too long
If your task is something that requires a lot of memory and/or executes for too long, it's not a good idea to make such a task running in the frontend, in turn slowing down your webpage and web performance.
- The task simply can't be performed in the frontend
Some tasks like web automation can't be performed in the frontend because it requires opening browsers and performing tasks in those browsers, needless to say, this can't be performed on a webpage.
Let's create our
index.php file and add the following contents:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Simple operations</title> </head> <body> <?php $output = exec("python3 op1.py"); echo("99 divided by 6 is "); echo("<h1>$output</h1>"); ?> </body> </html>
As you can see, the PHP script only does 3 things:
- It executes
op1.pyand stores it's output as
- It echos the simple math operation we want
- Finally, it echos the output of the python3
print(99 / 6)
Read more about exec
Now if you run
php -S localhost:8000 in your project's terminal and navigate to that address, you should see that your
index.php script has executed the
op1.py script and returned it's output as intended:
That's it for simple backend operations with PHP, stick around for part 2 and part 3 to learn about more complex and demanding backend operations!