Categories
Tools

How to post data to another page using PHP

Last updated on February 8th, 2022 at 07:10 pm

Click to rate this tutorial!
[Total: 19 Average: 3.8]

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.mistonline.in/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.mistonline.in/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'];
?>

Demo

Thanks!!! 🙂

Click to rate this tutorial!
[Total: 19 Average: 3.8]

3 replies on “How to post data to another page using PHP”

Leave a Reply

Your email address will not be published.