Last active
November 12, 2020 03:05
-
-
Save syuji-higa/112a5fa212c4ab49a76bcfde25e566fe to your computer and use it in GitHub Desktop.
PHP - get data with Ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// リクエスト形式によってはヘッダーに入ってこないので削除 | |
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || | |
$_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') { | |
die(json_encode(array('status' => "Invalid call."))); | |
} | |
setlocale(LC_ALL, 'ja_JP.UTF-8'); | |
// application/json の POST リクエストの場合は、$_POST に入ってこないので以下から取得 | |
// $params = json_decode(file_get_contents('php://input'), true); | |
if($_SERVER['REQUEST_METHOD'] !== 'POST') { | |
die(json_encode(array('status' => 'Not POST.'))); | |
} | |
if(!isset($_POST['name'])) { | |
die(json_encode(array('status' => "Not 'name' data."))); | |
} | |
$url = 'http://api.xxx/xxx'; | |
$body = array( | |
'key' => '01234567890123456789', | |
'name' => $name, | |
); | |
$res = file_get_contents($url . '?' . http_build_query($body)); | |
preg_match('/HTTP\/1\.[0|1|x] ([0-9]{3})/', $http_response_header[0], $matches); | |
$status_code = $matches[1]; | |
if($status_code !== '200') { | |
die(json_encode(array('status' => "Request error."))); | |
} | |
$res = json_decode($data, true); | |
header('Content-Type: application/json; charset=UTF-8'); | |
header('X-Content-Type-Options: nosniff'); | |
echo json_encode($res, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment