Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP and Python run as separate processes, so a PHP variable must cross that boundary as a command-line argument, bytes written to the Python process’s standard input, or data in a file. For one or two simple values, use separate arguments; for arrays, objects, or larger payloads, send JSON through a pipe. Prefer PHP 7.4+ array-form proc_open() to avoid shell parsing, and check the process exit code.

Choose how PHP will send the data

Method Best for Key trade-off
Separate command-line arguments A few small scalar values, such as an ID or a name Simple to read in Python, but arguments are strings and may be visible to other local processes.
JSON through standard input Arrays, objects, multiline text, or many values Keeps the payload out of shell syntax and supports a clear request/response format; requires pipe handling.
Temporary file A payload better handled as a file Adds file creation, permissions, and cleanup; use a fixed server-generated path rather than a user-supplied path.

The table’s guidance on payload shape and confidentiality is practical engineering judgment. PHP documents the process pipes and argument handling; it does not prescribe JSON or a particular file protocol. See the PHP proc_open() manual.

Pass a simple value as a command-line argument

With PHP 7.4 or later, pass the executable, script path, and each value as its own element in a command array. PHP’s array form launches the command directly rather than through a shell and handles argument escaping.

<?php
$value = 42;
$command = ['/usr/bin/python3', '/srv/app/script.py', (string) $value];
$descriptors = [
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w'],
];

$process = proc_open($command, $descriptors, $pipes);
if (!is_resource($process)) {
    throw new RuntimeException('Could not start Python');
}

fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);

if ($exitCode !== 0) {
    throw new RuntimeException('Python failed: ' . $stderr);
}
echo $stdout;

Replace both paths with locations valid on the server. In Python, the first value after the script name is available as sys.argv[1]; command-line values arrive as text, so validate and convert them before using them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import sys

value = int(sys.argv[1])
print(value * 2)

For more than one value, append each as a distinct array element in PHP; Python can read them at successive positions in sys.argv. Avoid combining several values into one manually delimited string, since delimiters may also occur in the data.

Send structured data as JSON on standard input

For arrays, objects, or a group of fields, write one JSON payload to the child’s stdin. Python reads and decodes it, then can return JSON on stdout. Keep diagnostic messages on stderr so they do not corrupt the machine-readable response.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
<?php
$payload = json_encode(
    ['name' => $name, 'count' => $count],
    JSON_THROW_ON_ERROR
);

$process = proc_open(
    ['/usr/bin/python3', '/srv/app/script.py'],
    [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
    $pipes
);
if (!is_resource($process)) {
    throw new RuntimeException('Could not start Python');
}

fwrite($pipes[0], $payload);
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);

if ($exitCode !== 0) {
    throw new RuntimeException('Python failed: ' . $stderr);
}
$result = json_decode($stdout, true, 512, JSON_THROW_ON_ERROR);
import json
import sys

payload = json.load(sys.stdin)
result = {'message': f"Hello, {payload['name']}", 'count': payload['count']}
print(json.dumps(result))

This defines a small protocol: PHP sends JSON to stdin; Python writes a JSON response to stdout; errors go to stderr and are accompanied by a nonzero exit status. Check the exit code before treating stdout as a successful result.

Use a shell command string only when needed

If legacy code or another constraint requires a string passed to exec(), quote every dynamic value as an individual argument with escapeshellarg():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
$command = escapeshellarg('/usr/bin/python3') . ' '
         . escapeshellarg('/srv/app/script.py') . ' '
         . escapeshellarg((string) $value);
exec($command, $output, $exitCode);

if ($exitCode !== 0) {
    throw new RuntimeException('Python exited with status ' . $exitCode);
}

Do not concatenate untrusted input into shell syntax, and do not use escapeshellcmd() as a replacement for quoting each argument. The PHP manuals explain the distinction in the documentation for escapeshellarg() and exec().

Platform behavior matters: PHP documents that on Windows exec() starts cmd.exe, and escapeshellarg() handles some characters differently than on Unix-like systems. Review the quoting rules for the actual host rather than assuming a Unix shell.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Read Python output and diagnose failures

Use stdout for results and stderr for diagnostics. exec() captures stdout lines in its output array and can return the exit status through its third argument; it does not put stderr in that array. Its return value is the last output line. Choose proc_open() when PHP needs to write to stdin or capture stdout and stderr separately.

  • Python will not start: Use the absolute path to the interpreter available to the web-server process. PHP’s array-form proc_open() searches PATH for a simple executable name, but a server’s environment may differ from an interactive terminal.
  • The script cannot be found: Pass an absolute script path. If it depends on a working directory, set that directory using proc_open()’s working-directory argument.
  • Python prints nothing: Check stderr and the exit status; empty stdout alone does not show whether the process succeeded.
  • Execution is denied or disabled: Verify that the web-server account can execute the interpreter and read the script, and check the host’s PHP policy.
  • The process appears to hang: Close stdin after writing and drain stdout and stderr before waiting for completion. For background commands, PHP’s exec() documentation warns that output must be redirected to avoid PHP waiting for the command to finish.

For exact behavior and platform options, consult the PHP manuals for proc_open() and exec().

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Security and deployment checks

  • Do not put secrets in command-line arguments: depending on the operating system and deployment, local processes may be able to see process arguments.
  • Use the Python executable that has the required dependencies installed; a developer’s virtual environment is not necessarily available to PHP on the server.
  • For temporary-file transfer, create the file with safe permissions, use a fixed server-generated path, and remove it when finished.
  • Keep input validation in Python even when PHP has validated the original value; the process boundary does not make input trustworthy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.