Python в расширении php

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.

Читайте также:  Php redis connect error

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.

Источник

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!

Источник

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.

License

Raeen123/phpy

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

phpy is library for php

You can use python in php with it

  • Show all output from python file
  • Show last line output from python
  • Send data to python file
  • Get data from python file
  • show image in php from python
  • path Genrate
  • write python line code
  • mange python line code
  • write python part
  • require python part
git clone https://github.com/Raeen123/phpy
composer require raeen/phpy

Prerequisites

php = 8.0.1 (Your php version must be at least 7.4 ) python = 3.9.1 numpy = 1.19.3 python-opencv = 4.4.0.46 

You must if you don’t add python in your path environment , add yor python path in core/Python.php in const python_path

We use these libraries for create phpy.py:

import sys import json import base64 import numpy as np import cv2

Import phpy.py file in Python/include/library/php.py

Get Data from php

Get datas to python file For Get data you must

phpy.get_data( Number Of Send data )

For return data you must use print function

Push data from python

Push image from python

It function for pushing data from python to php

Example for reading image

videoCaptureObject = cv2.VideoCapture(0) ret, frame = videoCaptureObject.read()

Send data from php

Create and Send data from php to python

You can send infinite data

require_once "../vendor/autoload.php"; use app\core\App; $app = new App(); $python = $app->python; $data1 = [ 'name' => 'raeen', 'library' => 'phpy' ]; $data2 pl-s">test"; $output = $python->set("../Python/test2.py")->send($data1, $data2)->gen();
$site pl-s">google.com"; $python->set('../Python/test6.py')->send($data)->live()->gen();

Show result

$output = $python->set(path)->send(datas..)->gen()

You can use this function to genrate what’s return from phpy.push_img()

$app->img($output,$type,$show,$style)

$type must be same type in php.push_img()

If $show is true , show image in img tag

Also you can set style for this

$app->img($output,$type,true, [ 'border' => '1px solid red' ])

For example , I have image file in this diractory but python file in Python/**.py and I want to send path to it . for this in must to send this path ../my-img Or use this functiuon for send path file or directory

If you have loop in php file it’s very good to add this function in top of file

If you want to run a python line , you should use this function

$Snippet->set($code,function()< // controller >)->gen();

For control varable , you should it’s name in |&name|

For fill varable you should return array , it must be in order

You must use » in python code and use ; in the end of each line

$Snippet = $app->snippet; $Snippet->set("print(f'hello world <|&data|*7*|&test|>'); print('--Hello')", function ($data,$test) < $data = 2; $test = 9; $data2 = $data*5; return [$data2 , $test]; >)->gen();

start Before start writing codes you should use this

For write your codes , you should use this

name in start function must be same this name

For get output anywhere you should use this

Example , index.php :

$Snippet->start("test"); $Snippet->line("a = 'Hello world'"); $Snippet->line("print(a)"); $Snippet->end("test"); $Snippet->select("test")->gen();

You can use this code in another file

Live Output Any where (Snippet and Python class) you can use this so easy

just before use gen() use live() then use «`gen(/* you can write function here to control output */)

$python->set("../Python/test6.py")->send($site)->live()->gen( function ($res) < return " $res "; > );

you can also set time without each reading ouput (defult is 1)

$python->set("../Python/test6.py")->send($site)->live()->ini(3)->gen( function ($res) < return " $res "; > );
$Snippet->set( "import subprocess as sub; sub.call('ping |&site|') ",function($site)< $site pl-s">google.com"; return [$site];> )->live()->ini(3)->gen();
$Snippet->select('snippet-test8')->live()->gen(function($res)< return " $res ";>);

Copyright (c) 2021 Raeen Ahani Azari

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

BY RAEEN AHANI AZARI

Источник

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