Using php with python

How to Run a Python Script from PHP

PHP (hypertext preprocessor) is a widely used free and open-source scripting language for web developers, and Python is known for its simplicity and versatility, which make it a popular choice for building complex web applications.

It would be much more convenient if we could use Python and PHP, both scripting languages, in one program.

And to run or facilitate Python scripts in PHP, we can use the “shell_exec“ function, which returns all of the output streams as a string. The shell executes it, and the result can be returned as a string.

So, let’s learn how to execute a Python script in PHP.

How to Execute a Python Script in PHP

To perform all the below steps properly, you need to install Python and a web server.

To install a web server, if you are on a Windows or Linux operating system, go for XAMPP, or else you can also manually install Apache and PHP on Linux,which is a cross-platform web server.

Create a Python Script

First, we will create a Python script file and store it in the respective directory so that it can be accessed by the PHP file when you execute the script.

Читайте также:  Html код середина страницы

For XAMPP user make sure to store file in htdocs directory of your respective web directory.

Now let’s create a short & simple program that returns “TREND OCEANS” as output.

Open a command line editor and paste the following line code where we have used the shebhang line to declare the path of the python binary file, and then we put “TREND OCEANS” under the print function to print.

#!/usr/bin/env python3 print("TREND OCEANS")

After adding the line Save and close the file with a .py extension, like here, I have saved with test.py.

Create a PHP file

To run Python Script in PHP we use two function of PHP.

escapeshellcmd() escapes all characters in a string that can trick a shell command into executing arbitrary commands.

shell_exec() that returns all of the output streams as a string.

Now we create a PHP file and save it in the same location where we have saved our python script.

Save the above script with the .php extension.

Run Script

Start your web server and visit your web server domain. In my case, I’ve demonstrated on my localhost, so I visit http://localhost with the file name sample.php on my browser.

Run Python script from PHP result

If you perform all steps properly above output will be displayed on your browser.

Bonus (One More Short Demo)

In this method, you do not need to install a web server. You just need to have a PHP installation, and if you don’t have it, check out this guide.

Here, I do have PHP and Python installed, so let me write one more short script to print system information like hostname, platform, architecture, and date.

Open your system command line editor, paste the following lines of code, and save the file with system.py name.

#!/usr/bin/env python3 import platform from datetime import date system_hostname = platform.uname().node platform_name = platform.system() machine_arch = platform.machine() current_date = date.today() print("Hostname Info:", system_hostname) print("Platform:", platform_name) print("Machine Architecture:", machine_arch) print("Current Date:", current_date)

After that, create a new file with the name sample.php & copy and paste the following lines of script, then save the file.

Next, you have to test the functionality of the script by running the next line of commands. But before that, you need to make the script executable. Otherwise, you may get sh: 1: ./system.py: Permission denied.

To avoid this, execute the following line of code, then run the PHP file to execute the inner script.

$ chmod u+x system.py $ php system_info.php 

The result of the above-mentioned procedures

Run Python script file in PHP

Wrap up

That’s all for this guide, where I showed you how to execute or run Python scripts in PHP using the shell_exec function with two different examples.

If you have a query, feel free to ask it in the comment section.

See you in the next article…spread ☮️ and ❤️.

Innovative tech mind with 12 years of experience working as a computer programmer, web developer, and security researcher. Capable of working with a variety of technology and software solutions, and managing databases.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Access the power and flexibility of PHP from within Python

joshmaker/python-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Have you ever wished that the Python standard library had the power and flexibility of PHP? Now it is as simple as import php

Python PHP can be installed using pip

$ pip install -e git+git@github.com:joshmaker/python-php.git#egg=python-php 

To access PHP functions in Python, simply import the php module and get started.

import php php.str_replace('Python', 'PHP', 'Hello World of Python') # Output: u'Hello World of PHP'

Python PHP supports the following types: int, string, list, and dictionaries

Of course Python-PHP has unit tests! How else would we know that it is safe to use? Run tests with $ python tests.py To test with python 2.6+ and 3.3+ type $ tox

Python-PHP is compatible with all relevant Python versions: 2.6, 2.7, 3.3, 3.4 and 3.5

Is this really a good idea?

What could possibly go wrong? OK, probably a lot of things. First release on April Fools Day 2016, this project was designed as a tongue-in-cheek coding exercise intended more for mirth than productivity. Using this in production is probably a very bad idea.

About

Access the power and flexibility of PHP from within Python

Источник

How to Run a Python Script in PHP

PHP (which is a recursive acronym for PHP Hypertext Preprocessor) is one of the most widely used web development technologies in the world. PHP code used for developing websites and web applications can be embedded directly along with the rest of the HTML markup. This, along with a rich amount of libraries to perform system tasks, or to integrate with other application, makes PHP the go-to language for the Internet.

While there are plenty of libraries (or modules) in PHP, there can be cases when a module for a certain task is either missing or is not properly implemented; while the same module is available in Python.

Apart from this, for certain scripting tasks the user might find Python more suitable, while he finds PHP suitable for the rest of his codebase.

In this article, we will take a look at how a Python script can be run from a PHP interpreter in a Linux terminal.

Calling a Python Script in PHP

Let us consider the following PHP code (test.php).

Note: The ‘\n’ at the end of the string is a newline character, which will move the cursor to the new line for the next commands on the terminal.

Let’s now call a simple Python script ‘ test.py ’, which simply prints ‘Hello World’.

$ cat test.py print(“Hello World”) 

To call this script from PHP, use the ‘exec’ function.

We can call the script with the command line program ‘php’, which is nothing but the PHP interpreter.

$ cat test.py $ cat test.php $ php test.php

Run Python Script Using PHP

As we can see, the output of Python script test.py was displayed.

Next, let’s consider the following Python script file, ‘test2.py’, which takes one argument, a String, and prints it.

$ cat test2.py import sys print(sys.argv[1])

Now let’s call this script from PHP, passing the argument.

Execute Python Script Using PHP

As we can see, the Python Script got executed and printed the parameter value ‘Example’.

Conclusion

In this article, we saw how to call a Python script from within our PHP code. This can be used on more complex Python scripts, the output of which will be stored in the PHP variable as shown in our examples above.

This can especially be helpful when some complex Python libraries, eg. the machine learning and data science libraries, are to be used. If you have any questions or feedback, make sure you leave a comment below!

Источник

Using Python and PHP together

Today i decided to install Python in Ubuntu OS and to use PHP and Python both together. If i hadn’t installed php and wanted to have python as only localhost in my OS, so it was easy, there are plenty of examples which show how to do it(for example). But if you have already installed php and you want to have python, then let’s go on. In this sample we will need two different ports if we want to do so. And i could easily install and test it. So i am sharing how i did it:

You have installed apache2-php in your Ubuntu(or other Linux based OS) and you want to install python for having python localhost. If python has not installed in your OS, do it. Let’s open Terminal:

sudo apt-get install python

Now you have python installed. Now we need apache mod for python. Let’s install it :

sudo apt-get install libapache2-mod-python

Then we must make some apache operations in terminal:

cd /etc/apache2/sites-available/ sudo gedit default

(default is the name of default apache conf file. )

Copy all block and paste it at the bottom. Then you will have two …. blockes. Then find in pasted block(second one) this:

 
Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny allow from all

Add these lines to new line after “allow from all” :

 
AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On

Then go to first line of pasted part and edit

 
Listen 81 <virtualhost:*.81>

Save and close the file. Restart apache:

 
sudo /etc/init.d/apache2 restart

It is ready. Both PHP and Python work together in your OS. PHP has 80, Python has 81 port.

PHP – http://127.0.0.1 or http://127.0.0.1:80

You can test python with simple test file which contains these 2 strings:

 
def index(req): return "Python works!";

In default apache virtualhost root localhost folder is /var/www. It is better to use different folders for Php and Python. For clear undersanding i am sharing my apache default conf file:

 
&lt;virtualhost:*.80&gt; ServerAdmin [email protected] DocumentRoot /home/user/public_html/ Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 &lt;/virtualhost&gt; Listen 81 &lt;virtualhost:*.81&gt; ServerAdmin [email protected] DocumentRoot /var/www/ Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny allow from all AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On # Uncomment this directive is you want to see apache2′s # default start page (in /apache2-eh) when you go to / #RedirectMatch ^/$ /apache2-eh/ ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </virtualhost>

You can see from last sample that i use /home/user/public_html folder for PHP, and /var/www folder for Python.

That’s all. If any question, you can add it to comments.

Share this:

Источник

Оцените статью