How to POST Data to a URL in PHP (Without a Form)
Sending POST data to a URL in PHP without a form can be useful when you want to complete and submit a form through your code.
Solution: Using cURL
To achieve this, you can utilize cURL, a powerful library for handling URL transfers. Here's how it's done:
$url = 'http://www.someurl.com'; $myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch);
This code initializes a cURL session with the specified URL. It then sets the CURLOPT_POST option to 1 to indicate that POST data will be sent. The CURLOPT_POSTFIELDS option specifies the POST variables in a string format.
Additional options are configured to enable following redirects, suppress headers, and return the response content in $response. Once the session is executed, the response from the URL will be stored in this variable.
The above is the detailed content of How to Send POST Data to a URL in PHP Without a Form?. For more information, please follow other related articles on the PHP Chinese website!