Home >Backend Development >PHP Tutorial >How to Send POST Data to a URL in PHP Without Using HTML Forms?
Posting Data to a URL in PHP
Sending POST data to a URL in PHP is a common task, especially when working with web services or submitting forms from scripts. In this article, we'll explore a method for doing this without utilizing HTML forms.
Curl to the Rescue
PHP provides the curl library, which allows us to interact with web requests. We'll use curl to send our POST data.
// Sample data to send (in a real application, these variables will be dynamic) $myVar1 = 'value 1'; $myVar2 = 'value 2'; // URL to post data to $url = 'http://www.example.com/form.php'; // Create a cURL handle $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_POST, 1); // Set as POST request curl_setopt($ch, CURLOPT_POSTFIELDS, "myVar1=$myVar1&myVar2=$myVar2"); // Set POST data curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Follow redirects curl_setopt($ch, CURLOPT_HEADER, 0); // Do not return headers in response curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string // Execute the cURL request $response = curl_exec($ch); // Close the cURL handle curl_close($ch); // Process the response // In this example, a successful response would likely indicate that the form on the target page was submitted
This script will send the POST data to the specified URL, and the response from the server will be stored in $response. Remember to replace $myVar1, $myVar2, and $url with your actual data and target URL.
The above is the detailed content of How to Send POST Data to a URL in PHP Without Using HTML Forms?. For more information, please follow other related articles on the PHP Chinese website!