Search code examples
phppdftk

Get full error from PDFTK when using PHP exec


I'm using PHP exec() in a script to merge PDF files with PDFTK.

From PHP docs: exec function says the second argument, if provided, will list each line from the console output. All I get is an empty array though.

Example of code being used:

exec(pdftk "file1.pdf" "file2.pdf" Merged_File.pdf, $output = array(), $result);

I can successfully get errors if I run the code in the console, but I'd like for my application to have access to the full text errors.


Solution

  • You are probably looking to get messages from stderr using proc_open. Something like this:

    <?php
    
    $cmd = "/path/to/script arguments here";
    $cwd = dirname(__FILE__);
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin
       1 => array("pipe", "w"),  // stdout
       2 => array("pipe", "w"),  // stderr
    );
    
    if ( ($process = proc_open($cmd, $descriptorspec, $pipes, $cwd, null)) !== false )
    {
      // Standard output
      $stdout = stream_get_contents($pipes[1]);
      fclose($pipes[1]);
    
      // Errors
      $stderr = stream_get_contents($pipes[2]);
      fclose($pipes[2]);
    
      proc_close($process);
    }
    
    ?>