John Davidson

php curl - Make POST request from php file to another php file

0 comments
Message:


I am trying to send a post request that does the excact same thing as the code below, but from a php file to another php file. In other words I want to make the post request with PHP and not Javascript. I have tried different methods but they all get the content from the php file, and not make the post like ajax.


$.ajax({
url: "./delete.php",
method: "POST",
data: {
id: 1
},
success: data => console.log(data),
error: err => console.log(err)
})


My Answer:
"other_php_file.php",
type: "POST",
data: {key1: value1, key2: value2},
success: function(response) {
console.log(response);
}
});

To make a POST request from one PHP file to another PHP file, you can use the cURL library in PHP. Here is an example code snippet that demonstrates how to make a POST request:

php

// URL of the PHP file you want to send the POST request to
$url = 'http://example.com/other_php_file.php';

// Data to be sent in the POST request
$data = array(
'key1' => 'value1',
'key2' => 'value2'
);

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Output the response
echo $response;

?>


In this code snippet, we first specify the URL of the PHP file we want to send the POST request to and the data to be sent in the POST request. We then initialize a cURL session, set the cURL options (including the URL, POST method, data, and return transfer option), execute the cURL session, and finally output the response.

Rate this post

3 of 5 based on 4261 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us