├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── config └── laravelPy.php ├── example-scripts ├── advance_example.py └── sum_calculator.py ├── phpunit.xml ├── src ├── LaravelPyFacade.php └── LaravelPyServiceProvider.php └── tests ├── LaravelPyTest.php ├── Pest.php └── fake-path └── sum_calculator.py /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-php-py` will be documented in this file 4 | 5 | ## 1.0.0 - 201X-XX-XX 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) omar alalwi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Py - Laravel Python 🚀🐍 2 | 3 | Laravel wrapper for **[php-py package](https://github.com/omaralalwi/php-py)** package, to Seamless enabling secure and efficient execution of Python scripts within Laravel applications without spread multiple applications and or setup API. 4 | 5 | ## 📌 Table of Contents 6 | 7 | - [🔧 Requirements](#requirements) 8 | - [🚀 Installation](#installation-) 9 | - [🚀 Quick Start](#-quick-start) 10 | - [✨ Features](#-features) 11 | - [📋 Changelog](#-changelog) 12 | - [🧪 Testing](#-testing) 13 | - [🔒 Security](#-security) 14 | - [🤝 Contributors](#-contributors) 15 | - [📄 License](#-license) 16 | 17 | 18 | --- 19 | 20 | ## Requirements 21 | 22 | - PHP 8.1+ . 23 | - [python3](https://www.python.org/) must be installed in server . 24 | 25 | ## Installation 🛠️ 26 | 27 | You can install the package via Composer: 28 | 29 | ```bash 30 | composer require omaralalwi/laravel-py 31 | ``` 32 | 33 | ## Publishing Configuration File 34 | 35 | ```bash 36 | php artisan vendor:publish --tag=laravel-py 37 | ``` 38 | 39 | --- 40 | 41 | ## 🚀 Quick Start 42 | 43 | 1. 📂 Create a folder for scripts, e.g., `phpPyScripts` in your project root directory. 44 | 2. 📝 Create a Python script file (`.py` extension) and write Python code. [See this script examples](https://github.com/omaralalwi/php-py/tree/master/example-scripts). 45 | 3. 🔧 make script file executable, `chmod +x script_file_path` . 46 | 47 | ### ⚡ Easy Usage 48 | 49 | ```php 50 | loadScript($script) 64 | ->withArguments($arguments) 65 | ->run(); 66 | 67 | print_r($result); // 60.0 68 | } catch (Exception $e) { 69 | echo "Error: " . $e->getMessage(); 70 | } 71 | } 72 | } 73 | ``` 74 | 75 | ### 🔥 Advanced Usage 76 | 77 | ```php 78 | 'phpPyScripts', 95 | 'python_executable' => '/usr/bin/python3', 96 | 'max_timeout' => 120, 97 | ]); 98 | 99 | $result = $laravelPy 100 | ->setConfig($config) 101 | ->loadScript($script) 102 | ->withArguments($numbers) 103 | ->withEnvironment(['FIRST_ENV_VAR' => 10, 'SECOND_ENV_VAR' => 'second var value']) 104 | ->timeout(60) 105 | ->asJson() 106 | ->run(); 107 | 108 | print_r(json_encode($result)); 109 | } catch (\Exception $e) { 110 | print_r("Error: " . $e->getMessage()); 111 | } 112 | } 113 | } 114 | ``` 115 | 116 | --- 117 | 118 | ## ✨ Features 119 | 120 | ### 🔐 Secure Execution 121 | - **Path Validation** ✅ Ensures scripts are within allowed directories. 122 | - **Argument & Environment Validation** 🔍 Restricts unauthorized input. 123 | - **Timeout Control** ⏳ Prevents long-running scripts. 124 | - **black list** for these vars `PATH,PYTHONPATH,LD_LIBRARY_PATH,LD_PRELOAD,PYTHONHOME`, can not passed . 125 | - **Uses `proc_open` as an alternative to `shell_exec`**. 126 | 127 | ### 🔧 Flexible Configuration 128 | - Centralized settings via `ConfigManager`. 129 | - Customizable execution parameters. 130 | 131 | ### 📤 Output Handling 132 | - Supports JSON parsing. 133 | - Captures and reports script errors. 134 | 135 | ### 🚨 Error Management 136 | - Detailed exception handling for debugging. 137 | - Standardized error reporting. 138 | 139 | ### 🔌 Extensibility 140 | - Modular execution through `CommandExecutor`. 141 | - Customizable for advanced use cases. 142 | 143 | --- 144 | ### Important Critical Note: 145 | 146 | ❌ Never pass user-controlled input directly script, just pass scripts that you will need as a administrator (Just from Your side) . 147 | 148 | --- 149 | 150 | ## 📋 Changelog 151 | 152 | See detailed release notes in [CHANGELOG.md](CHANGELOG.md) 📜 153 | 154 | --- 155 | 156 | ## 🧪 Testing 157 | 158 | ```bash 159 | ./vendor/bin/pest 160 | ``` 161 | 162 | --- 163 | 164 | ## 🔒 Security 165 | 166 | **Report Vulnerabilities**: Contact [omaralwi2010@gmail.com](mailto:omaralwi2010@gmail.com) 📩 167 | 168 | --- 169 | 170 | ## 🤝 Contributors 171 | 172 | A huge thank you to these amazing people who have contributed to this project! 🎉💖 173 | 174 | 175 | 176 | 185 | 186 |
177 | 178 | Omar AlAlwi 179 |
180 | Omar AlAlwi 181 |
182 |
183 | 🏆 Creator 184 |
187 | 188 | **Want to contribute?** Check out the [contributing guidelines](./CONTRIBUTING.md) and submit a pull request! 🚀 189 | 190 | --- 191 | 192 | ## 📄 License 193 | 194 | This package is open-source software licensed under the [MIT License](LICENSE.md). 📜 195 | 196 | 197 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "omaralalwi/laravel-py", 3 | "description": "Laravel wrapper for php-py package, to seamless enabling secure and efficient execution of Python scripts within PHP applications.", 4 | "keywords": [ 5 | "laravel-py", 6 | "laravel-python", 7 | "python-python", 8 | "php-py", 9 | "python", 10 | "python-php", 11 | "deepseek-r1", 12 | "laravel-api-server", 13 | "python-in-laravel", 14 | "php-pytho", 15 | "laravel python integration", 16 | "run python in php", 17 | "omaralalwi", 18 | "execute python from laravel", 19 | "python shell execution", 20 | "secure python execution", 21 | "laravel python bridge", 22 | "python subprocess in laravel", 23 | "laravel exec python script" 24 | ], 25 | "homepage": "https://github.com/omaralalwi/laravel-py", 26 | "license": "MIT", 27 | "type": "library", 28 | "version": "1.0.0", 29 | "authors": [ 30 | { 31 | "name": "omar alalwi", 32 | "email": "omaralwi2010@gmail.com", 33 | "role": "Developer" 34 | } 35 | ], 36 | "require": { 37 | "php": "^8.1", 38 | "illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0", 39 | "omaralalwi/php-py": "^1.0" 40 | }, 41 | "require-dev": { 42 | "orchestra/testbench": "^6.0", 43 | "pestphp/pest": "^1.23", 44 | "phpunit/phpunit": "^9.0" 45 | }, 46 | "autoload": { 47 | "psr-4": { 48 | "Omaralalwi\\LaravelPy\\": "src" 49 | } 50 | }, 51 | "autoload-dev": { 52 | "psr-4": { 53 | "Omaralalwi\\LaravelPy\\Tests\\": "tests" 54 | } 55 | }, 56 | "scripts": { 57 | "test": "vendor/bin/phpunit", 58 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 59 | 60 | }, 61 | "config": { 62 | "sort-packages": true, 63 | "allow-plugins": { 64 | "pestphp/pest-plugin": true 65 | } 66 | }, 67 | "extra": { 68 | "laravel": { 69 | "providers": [ 70 | "Omaralalwi\\LaravelPy\\LaravelPyServiceProvider" 71 | ], 72 | "aliases": { 73 | "LaravelPy": "Omaralalwi\\LaravelPy\\LaravelPyFacade" 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /config/laravelPy.php: -------------------------------------------------------------------------------- 1 | base_path('phpPyScripts'), 8 | 9 | /* 10 | * The path to the Python executable. 11 | */ 12 | 'python_executable' => '/usr/bin/python3', 13 | 14 | /* 15 | * The maximum execution time for Python scripts in seconds. 16 | */ 17 | 'max_timeout' => 120, 18 | ]; 19 | -------------------------------------------------------------------------------- /example-scripts/advance_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import sys 3 | import json 4 | import os 5 | 6 | def main(): 7 | # Retrieve command-line arguments (excluding the script name) 8 | args = sys.argv[1:] 9 | 10 | # Retrieve environment variables 11 | env_vars = os.environ 12 | 13 | # Prepare the response dictionary 14 | response = { 15 | 'script': 'sum_calculator.py', 16 | 'received_args': args, 17 | 'received_env_vars': {} 18 | } 19 | 20 | # Process environment variables 21 | allowed_env_vars = ['FIRST_ENV_VAR', 'SECOND_ENV_VAR', 'ANOTHER_VAR'] 22 | for var in allowed_env_vars: 23 | if var in env_vars: 24 | response['received_env_vars'][var] = env_vars[var] 25 | 26 | # Validate input arguments 27 | if not args: 28 | response['error'] = 'No numbers provided to calculate the sum.' 29 | print(json.dumps(response)) 30 | sys.exit(1) 31 | 32 | # Convert arguments to floats (to handle decimal numbers) 33 | try: 34 | numbers = [float(arg) for arg in args] 35 | except ValueError: 36 | response['error'] = 'All arguments must be numbers.' 37 | print(json.dumps(response)) 38 | sys.exit(1) 39 | 40 | # Calculate the sum 41 | total = sum(numbers) 42 | 43 | # Add the result to the response 44 | response['sum'] = total 45 | 46 | # Return the response as JSON 47 | print(json.dumps(response)) 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /example-scripts/sum_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import sys 3 | import json 4 | import random 5 | 6 | def main(): 7 | # Parse command-line arguments into numbers 8 | try: 9 | numbers = [float(arg) for arg in sys.argv[1:]] 10 | except ValueError: 11 | print(json.dumps({'error': 'All arguments must be numeric.'})) 12 | sys.exit(1) 13 | 14 | # Calculate the sum of the numbers 15 | result = sum(numbers) 16 | # Output the result as JSON 17 | print(json.dumps(result)) 18 | 19 | if __name__ == '__main__': 20 | main() 21 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | ./tests 10 | 11 | 12 | 13 | 14 | ./app 15 | ./src 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/LaravelPyFacade.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 17 | $this->publishes([ 18 | __DIR__.'/../config/laravelPy.php' => config_path('laravel-py.php'), 19 | ], 'laravel-py'); 20 | } 21 | } 22 | 23 | /** 24 | * Register the application services. 25 | */ 26 | public function register() 27 | { 28 | $this->mergeConfigFrom(__DIR__.'/../config/laravelPy.php', 'laravel-py'); 29 | 30 | $this->app->singleton('LaravelPy', function ($app) { 31 | $config = $app['config']['laravel-py']; 32 | $configManager = new ConfigManager([ 33 | 'scripts_directory' => $config['scripts_directory'], 34 | 'python_executable' => $config['python_executable'], 35 | 'max_timeout' => $config['max_timeout'], 36 | ]); 37 | 38 | return PhpPy::build() 39 | ->setConfig($configManager); 40 | }); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /tests/LaravelPyTest.php: -------------------------------------------------------------------------------- 1 | __DIR__ . '/../example-scripts', 10 | 'python_executable' => '/usr/bin/python3', 11 | 'max_timeout' => 30, 12 | ]); 13 | 14 | $result = PhpPy::build() 15 | ->setConfig($configManager) 16 | ->loadScript('sum_calculator.py') 17 | ->withArguments([10, 20, 30]) 18 | ->run(); 19 | 20 | expect(json_decode($result))->toBe(60.0); 21 | }); 22 | 23 | test('LaravelPy throws exception when try to run script outside allowed path', function () { 24 | 25 | $configManager = new ConfigManager([ 26 | 'scripts_directory' => __DIR__ . '/../example-scripts', 27 | 'python_executable' => '/usr/bin/python3', 28 | 'max_timeout' => 30, 29 | ]); 30 | 31 | $this->expectException(\InvalidArgumentException::class); 32 | $this->expectExceptionMessage('Script path does not exist.'); 33 | 34 | $result = PhpPy::build() 35 | ->setConfig($configManager) 36 | ->loadScript('/fake-path/sum_calculator.py') 37 | ->withArguments([10, 20, 30]) 38 | ->run(); 39 | 40 | expect(json_decode($result))->toBe('Script path does not exist.'); 41 | }); 42 | 43 | test('withEnvironment throws exception for blacklisted environment variables', function () { 44 | 45 | $configManager = new ConfigManager([ 46 | 'scripts_directory' => __DIR__ . '/../example-scripts', 47 | 'python_executable' => '/usr/bin/python3', 48 | 'max_timeout' => 30, 49 | ]); 50 | 51 | $env = [ 52 | 'LD_LIBRARY_PATH' => 'fake value', 53 | ]; 54 | 55 | $this->expectException(\InvalidArgumentException::class); 56 | $this->expectExceptionMessage("Environment variable 'LD_LIBRARY_PATH' is not allowed."); 57 | 58 | $result = PhpPy::build() 59 | ->setConfig($configManager) 60 | ->loadScript('sum_calculator.py') 61 | ->withArguments([10, 20, 30]) 62 | ->withEnvironment($env) 63 | ->run(); 64 | 65 | expect(json_decode($result))->toBe("Environment variable 'LD_LIBRARY_PATH' is not allowed."); 66 | }); 67 | -------------------------------------------------------------------------------- /tests/Pest.php: -------------------------------------------------------------------------------- 1 | in('Feature'); 15 | 16 | /* 17 | |-------------------------------------------------------------------------- 18 | | Expectations 19 | |-------------------------------------------------------------------------- 20 | | 21 | | When you're writing tests, you often need to check that values meet certain conditions. The 22 | | "expect()" function gives you access to a set of "expectations" methods that you can use 23 | | to assert different things. Of course, you may extend the Expectation API at any time. 24 | | 25 | */ 26 | 27 | expect()->extend('toBeOne', function () { 28 | return $this->toBe(1); 29 | }); 30 | 31 | /* 32 | |-------------------------------------------------------------------------- 33 | | Functions 34 | |-------------------------------------------------------------------------- 35 | | 36 | | While Pest is very powerful out-of-the-box, you may have some testing code specific to your 37 | | project that you don't want to repeat in every file. Here you can also expose helpers as 38 | | global functions to help you to reduce the number of lines of code in your test files. 39 | | 40 | */ 41 | 42 | function something() 43 | { 44 | // .. 45 | } 46 | -------------------------------------------------------------------------------- /tests/fake-path/sum_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import sys 3 | import json 4 | import random 5 | 6 | def main(): 7 | # Parse command-line arguments into numbers 8 | try: 9 | numbers = [float(arg) for arg in sys.argv[1:]] 10 | except ValueError: 11 | print(json.dumps({'error': 'All arguments must be numeric.'})) 12 | sys.exit(1) 13 | 14 | # Calculate the sum of the numbers 15 | result = sum(numbers) 16 | # Output the result as JSON 17 | print(json.dumps(result)) 18 | 19 | if __name__ == '__main__': 20 | main() 21 | --------------------------------------------------------------------------------