Last updated on February 8th, 2022 at 07:10 pm
PHP Post Data To Another Webpage Using PHP and cURL
We are using PHP with the help of CURL to post data to another webpage. In order to do this you should be knowing the URL to which you should post the request, The fields used in the POST page are for example I have used fields like “firstname“, “lastname” and “email“.
Once the data is posted. We can even display the return data using the curl_exec function. Please find the code below and I have tried to explain all the variables used here.
<?php
$urltopost = "https://demo.webtutorials.dev/curlphp/post.php";
$datatopost = array ("firstname" => "James",
"lastname" => "Anderson","email" => "[email protected]",);
$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
echo "Output <hr>".$returndata;
?>
$urltopost
The url where you want to post your data to
$datatopost
The post data as an associative array. The keys are the post variables
$ch = curl_init ($urltopost);
Initializes cURL
curl_setopt ($ch, CURLOPT_POST, true);
Tells cURL that we want to send post data
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
Tells cURL what are post data is
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
Tells cURL to return the output of the post
$returndata = curl_exec ($ch);
Executes the cURL and saves theoutput in $returndata
As you can see from the above code that I am posting data to a page “https://demo.webtutorials.dev/curlphp/post.php” , This page is simple and we are just echoing the POST values,
<?php
echo "First Name ".$_POST['firstname'];
echo "<br>Last Name ".$_POST['lastname'];
echo "<br>Email ".$_POST['email'];
?>
Thanks!!! 🙂
Can you explain what we will do if we dont know the table structure of remote database ??
Hi how to fetch database table using curl, can you help me
Hello Siva,
You can load the web page into a DOM Object and parse it to get specific data.