I'm experimenting with some PHP code, not so expert...
I'm a beginner in PHP so please forgive me.
I wrote this simple code:
<?php
echo("test");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
var_dump($name);
} else {
echo $name;
}
} else {
echo("IS A GET");
}
?>
i'am using postman to send a POST request but looks like the parm I send Is always NULL.
is it something wrong on my code?
My Answer:
php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
if ($data) {
echo "Received data: " . print_r($data, true);
} else {
echo "No data received";
}
} else {
echo "This is not a POST request";
}
This code checks if the request method is POST and then tries to decode the JSON data from the request body using `file_get_contents('php://input')`. If the data is successfully decoded, it will be printed out. If no data is received, it will output "No data received".
Make sure you are sending a valid JSON payload in your POST request. You can test this code by sending a POST request with JSON data using tools like Postman or cURL.
Rate this post
3 of 5 based on 8372 votesComments