Web Developer
I have a custom LAMP stack application on a DigitalOcean droplet. But I now need to run a python script to do a PDF conversion :
python src/exportpdf/export_pdf_to_docx.py
How do I set this up in such a way that, on clicking a button on the PHP served webpage, I get this python script to be called and download the DOCX ?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
Hi there,
You can call the Python script from PHP using shell_exec()
or exec()
, but you should be very careful. Running system commands from a web app has security implications.
But a basic example of this would be:
$output = shell_exec('python3 /var/www/app/scripts/export_pdf_to_docx.py 2>&1');
To let users download the DOCX, have the Python script save it to a secure, known directory, and then use PHP to serve the file using header()
:
$filepath = '/var/www/app/generated/output.docx';
if (file_exists($filepath)) {
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="export.docx"');
readfile($filepath);
exit;
}
On the security side, make sure to always use absolute paths in both PHP and Python to avoid unexpected behavior.
Also, never, but really never, pass user input directly to the shell command.
You could also make sure the Python script can’t be modified by external users. For example, rRun the script under limited permissions, eg. avoid giving www-data
full access to your system.
You can also store the generated files outside of your web root if possible.
Also double-check that your Droplet has Python, the required packages, and environment variables configured properly for the PDF SDK to work:
- Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.