Execute php file from another php

Execute php file from another php

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

The Silent Failure of exec() in PHP

When you attempt to run a standalone PHP script from within another using exec('/opt/lampp/htdocs/stuff/name.php'), you expect the logic inside that file to execute just as it would if accessed via a browser. Instead, you often encounter cryptic errors like "cannot open ?: No such file" or syntax parsing failures on lines containing functions. The root cause isn't a bug in PHP's execution engine; it is a fundamental misunderstanding of how the language parses code versus how the command-line interface (CLI) processes it.

The primary issue lies in the presence of the <?php opening tag at the very beginning of your target file (name.php). In a web server context, this tag tells the PHP interpreter where to begin processing. However, when you pass that path directly to exec(), you are invoking the CLI SAPI (Server API) on a specific process. While modern PHP versions are generally forgiving about extra whitespace or missing tags in some contexts, relying on <?php being stripped automatically is not guaranteed behavior across all environments, especially older setups like the one implied by your /opt/lampp path.

More critically, the error messages you are seeing—"Syntax error: '('"—strongly suggest that the CLI process is not reading the file as a PHP script in the expected manner, or it is treating the <?php tag as plain text data rather than an instruction to switch modes. When the CLI encounters unexpected characters at the start of a script where none are anticipated (or if the shebang logic isn't invoked), it fails before reaching your function definitions.

The Correct Approach: Including vs. Executing

If your goal is to reuse code, such as a database connection helper, you should generally avoid spawning a new process entirely unless isolation is strictly required. Using include, require, or require_once allows the current PHP script to load the logic of another file into its own execution context. This preserves variable scope, error reporting levels, and the flow of the request without the overhead of forking a new process.

If you need to isolate environments—for example, running a specific cron job or batch process—you must ensure the target file is executable by the shell. The standard convention for CLI scripts is to start with #!/usr/bin/env php (the shebang) instead of <?php. This line tells the operating system which interpreter to use when you run the script from the command line.

Here is how you should structure your standalone script if it must be called via exec():

#!/usr/bin/env php
<?php

function connection() {
    // Statements
}

connection();

And in your calling script:

$filename = '/opt/lampp/htdocs/stuff/name.php';
$output = [];
$return_var = 0;

// Ensure the path is absolute and executable
if (is_executable($filename) || file_exists($filename)) {
    exec("php " . escapeshellarg($filename) . " 2>&1", $output, $return_var);
    
    if ($return_var !== 0) {
        error_log("Script failed with status: " . $return_var);
    }
    
    // Process $output here
} else {
    error_log("File does not exist or is not readable.");
}

Notice the shift from exec($filename) to php $filename. Passing the path directly assumes the file has a shebang that the OS can resolve correctly, but explicitly invoking the php binary ensures the interpreter is used regardless of the file's first line. Additionally, wrapping the filename in escapeshellarg() prevents shell injection vulnerabilities if the path contains spaces or special characters.

Trade-offs and Pitfalls

There are significant trade-offs between including a file and executing it as a separate process. Including a file is lightweight and maintains the current stack trace for debugging; errors in the included file appear as if they happened in the main script. However, this couples your logic tightly. If name.php relies on global state set by the calling script, including it works seamlessly.

Executing via exec() creates a new process. This means any variables defined in the parent script are lost unless passed explicitly as arguments. Furthermore, you lose the ability to stop execution immediately upon an error in the child script without checking the return code and parsing output strings. If your target file outputs data, you must parse that string output in the parent script, which can be messy if the output contains newlines or complex formatting.

Another subtle pitfall involves the <?php tag itself. While some PHP versions ignore it when running via CLI if a shebang is missing, relying on this behavior is fragile. If you switch PHP versions or update from a version like 7.x to 8.x, strictness regarding script headers may change. Always use a shebang for standalone scripts to ensure portability.

Finally, consider whether you are trying to solve the wrong problem. If name.php contains logic that should be part of your application's core, refactor it into a class or library file and include it. Only spawn a new process if you need to run independent tasks asynchronously or if the target script must function in both CLI and Web contexts without modification.

Our network