Home > Backend Development > PHP Tutorial > How to Send POST Data to a URL in PHP Without a Form?

How to Send POST Data to a URL in PHP Without a Form?

Patricia Arquette
Release: 2024-11-16 16:16:03
Original
565 people have browsed it

How to Send POST Data to a URL in PHP Without a Form?

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template