PHP & Others

PHP - detect http request type in PHP (GET, POST, PUT, DELETE)

컨텐츠 정보

본문

출처 : https://dirask.com/posts/PHP-detect-http-request-type-in-PHP-GET-POST-PUT-DELETE-BDd8oD



backend.php


<?php


$method = $_SERVER['REQUEST_METHOD'];


function parseInput()

{

$data = file_get_contents("php://input");


if($data == false)

return array();


parse_str($data, $result);


return $result;

}


switch ($method)

{

case 'GET':

echo "GET request method\n";

echo print_r($_GET, true);

break;

case 'POST':

echo "POST request method\n";

echo print_r($_POST, true);

break;

case 'PUT':

$_PUT = parseInput();


echo "PUT request method\n";

echo print_r($_PUT, true);

break;

case 'DELETE':

$_DELETE = parseInput();


echo "DELETE request method\n";

echo print_r($_DELETE, true);

break;

default:

echo "Unknown request method.";

break;

}




ajax.htm


<!doctype html>

<html lang="en">

<head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>

<body>

<pre id="response"></pre>

<script>


var handle = document.getElementById('response');


$.ajax({

type: 'GET', // 'POST', 'PUT', 'DELETE'

url: '/backend.php',

data: {

name: 'John',

age: 25

},

success: function (data) {

handle.innerHTML = 'Response:\n' + data;

},

error: function(error) {

handle.innerText = 'Error: ' + error.status;

}

});


</script>

</body>

</html>



관련자료

댓글 0
등록된 댓글이 없습니다.
Today's proverb
누군가가 나에게 일러주었네. 나는 난쟁이보다 작지도 않고 거인보다 크지도 않음을...(난쟁이가 쏘아 올린 공중에서)