How to pass variables as stdin into command line from PHP

后端 未结 2 1653
故里飘歌
故里飘歌 2020-11-29 04:00

I am trying to write a PHP script that uses the pdftk app to merge an XFDF with a PDF form and output the merged PDF to the user. According to the pdftk documentation, I can

相关标签:
2条回答
  • 2020-11-29 04:25

    1) Why are you outputting to standard out and then putting that stuff into a file? Why not just have pdftk dump to the file, i.e.

    exec("pdftk blankform.pdf fill_form formdata.xfdf output filledform.pdf");
    

    2) Use proc_open(). Feel free to post any problems you have with the function.

    0 讨论(0)
  • 2020-11-29 04:41

    I'm not sure about what you're trying to achieve. You can read stdin with the URL php://stdin. But that's the stdin from the PHP command line, not the one from pdftk (through exec).

    But I'll give a +1 for proc_open()


    <?php
    
    $cmd = sprintf('pdftk %s fill_form %s output -','blank_form.pdf', raw2xfdf($_POST));
    
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       2 => null,
    );
    
    $process = proc_open($cmd, $descriptorspec, $pipes);
    
    if (is_resource($process)) {
        // $pipes now looks like this:
        // 0 => writeable handle connected to child stdin
        // 1 => readable handle connected to child stdout
    
        fwrite($pipes[0], stream_get_contents(STDIN)); // file_get_contents('php://stdin')
        fclose($pipes[0]);
    
        $pdf_content = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
    
        // It is important that you close any pipes before calling
        // proc_close in order to avoid a deadlock
        $return_value = proc_close($process);
    
    
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename="output.pdf"');
        echo $pdf_content;
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题