Get form fields in PHP and trigger file download
-
Hello, I’m trying to code a solution with PHP that would generate a text file, partially with user input from WPForms, partially with static data. After the user selects the options and submits the form, I want the user’s browser to start downloading this file.
Please, can you assist me on how to retrieve user submitted data in PHP, and how do I trigger the file download on submit button?
-
Hi @visedfaq Here is a code that will help you to achieve this but this might not be the perfect solution and you might need to modify the code according to your needs.
Add a Custom Function to Handle Form Submission:
You can add this code to your theme’sfunctions.php
file or use a plugin that allow to insert code something like WPCode.// Handle Form Submission add_action('wpforms_process_complete', 'generate_text_file_on_submission', 10, 4); function generate_text_file_on_submission($fields, $entry, $form_data, $entry_id) { // Check if it's the specific form ID you want to target if ($form_data['id'] == 8) { // Replace 8 with your form ID // Extract data from the form fields $first_name = $fields[0]['first']; // Replace 0 with your field ID $last_name = $fields[0]['last']; // Replace 0 with your field ID $email = $fields[1]['value']; // Replace 1 with your field ID $message = $fields[2]['value']; // Replace 2 with your field ID // Static data $static_data = "This is some static data.\n"; // Combine data $file_content = "Name: $first_name $last_name\n"; $file_content .= "Email: $email \n"; $file_content .= "Message: $message \n"; $file_content .= $static_data; // Generate text file $text_file_name = 'generated_file.txt'; $upload_dir = wp_upload_dir(); $text_file_path = $upload_dir['basedir'] . '/' . $text_file_name; file_put_contents($text_file_path, $file_content); // Create ZIP file $zip = new ZipArchive(); $zip_file_name = 'generated_file.zip'; $zip_file_path = $upload_dir['basedir'] . '/' . $zip_file_name; if ($zip->open($zip_file_path, ZipArchive::CREATE) === TRUE) { $zip->addFile($text_file_path, $text_file_name); $zip->close(); } // Store the ZIP file path in a session variable session_start(); $_SESSION['file_path'] = $zip_file_path; // Clean up the text file after adding to ZIP unlink($text_file_path); // Redirect to a URL that triggers the download $redirect_url = add_query_arg('download_file', '1', site_url()); wp_redirect($redirect_url); exit; } }
Add another function to serve the file for download.
// Handle File Download add_action('init', 'handle_file_download'); function handle_file_download() { if (isset($_GET['download_file']) && $_GET['download_file'] == '1') { session_start(); if (isset($_SESSION['file_path'])) { $file_path = $_SESSION['file_path']; if (file_exists($file_path)) { header('Content-Description: File Transfer'); header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename="' . basename($file_path) . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file_path)); readfile($file_path); unlink($file_path); // Delete the file after download exit; } } } }
Important Considerations:
- Security: Sanitize and validate user inputs to prevent security vulnerabilities.
- Sessions: Ensure your server supports sessions and they are properly configured in
php.ini
. - Unique Filenames: Consider using unique filenames to prevent overwriting files and manage file cleanup.
This code should serve as a solid starting point. Adjust the field IDs and static data as needed to match your form and requirements.
Hi @jahidhasan018 , first of all thank you for such a comprehensive answer! I didn’t expect it to be so detailed, I very much appreciate it.
Can you please clarify one thing for me – why do you move the file to a ZIP archive in your code?
Again, thanks for your advanced help!
Hi @visedfaq,
Yes, here is why I am archiving the .txt file after generating it. Basically, when I was testing the code, I noticed that the .txt file wasn’t downloaded automatically, but a .zip file did the trick. I didn’t dig into why the .txt file couldn’t be downloaded, but you might want to investigate that further and see if there’s a workaround.
I hope this clarifies the question.
Hi @visedfaq,
I apologize as customizations like this are outside of our scope for support. You will need custom code, and you can start by hooking into the wpforms_process_complete action that is triggered after form processing.
In case the great example provided by @jahidhasan018 does not achieve your goal, we highly recommend using Seahawk.
Thanks!
Hi @jahidhasan018,
We truly appreciate you taking the time to provide the code snippet and details.
Thanks!
- The topic ‘Get form fields in PHP and trigger file download’ is closed to new replies.