Skip to content

Instantly share code, notes, and snippets.

@n3rada
Created June 28, 2024 14:45
Show Gist options
  • Save n3rada/ddefa221f0a99761f824aaa68f1fed73 to your computer and use it in GitHub Desktop.
Save n3rada/ddefa221f0a99761f824aaa68f1fed73 to your computer and use it in GitHub Desktop.
import subprocess
import os
import tempfile
def run_php_code(php_code: str, *args) -> str:
"""
Executes a given PHP code string as a standalone PHP script. This function writes the code to a file,
executes it, captures the output, and performs cleanup.
Args:
php_code (str): A string containing the PHP code to be executed.
*args (tuple): Variable length argument list, where each argument is passed to the
PHP script as command line arguments. All arguments are converted to strings.
Returns:
str: The stdout captured from the PHP script after successful execution. If execution fails,
returns None and prints an error message to the standard output.
Raises:
This function does not raise any exceptions directly but will print error messages
to standard output in case of execution errors.
"""
# Create a temporary file to hold the PHP code
with tempfile.NamedTemporaryFile(delete=False, suffix=".php", mode="w", encoding="utf-8") as php_file:
php_file.write(php_code)
php_filename = php_file.name
try:
# Prepare the command to run the PHP script, converting all arguments to strings
run_command = ["php", php_filename] + [str(arg) for arg in args]
# Execute the PHP script
run_result = subprocess.run(
run_command,
capture_output=True,
text=True,
check=False, # Handling error checking manually
)
if run_result.returncode != 0:
print(f"[x] Execution failed:\n{run_result.stderr}")
return None
return run_result.stdout
finally:
# Clean up: remove the PHP file
if os.path.exists(php_filename):
os.remove(php_filename)
# Example usage:
php_code = """
<?php
echo "Hello, World!";
?>
"""
output = run_php_code(php_code)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment