PHP: Catch and forward all post variables from script

A PHP proxy script, e.g. for debugging.

Suppose we have a form that sends data to a PHP script. The whole thing via POST. For certain purposes, it may be useful if we interpose. For example, this would allow us to evaluate the data, save it to a database, and then call the original script.

The Script

Here is an example of such a script:

<?php
// Set the URL of the destination PHP script
$destination_url = "https://example.com/destination_script.php";

// Check if any POST variables were sent
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Get all POST variables
  $post_variables = $_POST;

  // Create a new cURL resource
  $curl = curl_init();

  // Set the cURL options
  curl_setopt($curl, CURLOPT_URL, $destination_url);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $post_variables);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  // Execute the cURL request
  $response = curl_exec($curl);

  // Close the cURL resource
  curl_close($curl);

  // Output the response from the destination script
  echo $response;
} else {
  // No POST variables were sent, output an error message
  echo "Error: No POST variables were sent.";
}
?>

How the script works and how to use it

In this script, we first set the URL of the destination PHP script. We then check if any POST variables were sent using $_SERVER[“REQUEST_METHOD”], which will be “POST” if any POST variables were sent. If POST variables were sent, we use cURL to send a POST request to the destination script with the CURLOPT_POSTFIELDS option set to the $post_variables array, which contains all of the POST variables. We also set CURLOPT_RETURNTRANSFER to true to return the response from the destination script. Finally, we output the response from the destination script.

Note that you may need to modify the cURL options depending on the specific requirements of your application.

Leave a Reply

Your email address will not be published. Required fields are marked *