php - PHP http 代码 0 无法读取自定义标头
问题描述
我有一个在 Angular 项目中调用的 php 脚本。我总是得到响应代码为 0。我可以在 chrome 调试部分找到请求标头,但是当我在脚本中看到它总是空的。此外,使用请求方法“options”和“get”调用了 php 脚本两次。我无法进一步了解详情。我正在 Windows、PHP7、iis 服务器上工作。
<?php
ob_start();
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing'); //testing, production
ini_set('display_errors', '1');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: api-method,api-url,authorization,token, Content-Type');
header('Content-Length: 0');
header('Content-Type: text/plain');
die();
}else{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
header("Content-Type: application/json");
}
echo "header " .getallheaders()['api-method'] . '<br>';
if ((empty(getallheaders()['api-method']) || empty(getallheaders()['api-url'])) && $_SERVER['REQUEST_METHOD'] === 'POST') {
echo json_encode(['msg' => 'Invalid request']);
exit;
}
$params = [];
$api_url = getallheaders()['api-url'];
$api_method = getallheaders()['api-method'];
if ($api_method == 'post') {
$params = json_decode(file_get_contents('php://input'), TRUE);
if (empty($params)) {
$params = $_POST;
}
$headers = ["Content-Type: application/x-www-form-urlencoded", "Cache-Control: no-cache"];
} else {
$headers = [];
}
//read headers
foreach (getallheaders() as $name => $value) {
$key = strtolower($name);
if (strtolower($name) == 'mobilenumber') {
array_push($headers, "$key: $value");
} else if (strtolower($name) == 'branch') {
array_push($headers, "$key: $value");
} else if (strtolower($name) == 'authorization') {
array_push($headers, "$key: $value");
}
}
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $api_url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($handle, CURLOPT_TIMEOUT, 400);
echo 'Curl error: ' . curl_error($handle);
if ($api_method == 'post') {
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($params));
}
$response = curl_exec($handle);
$contentType = curl_getinfo($handle, CURLINFO_CONTENT_TYPE);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
print curl_error($handle);
if (ENVIRONMENT == 'testing') {
$log = 'Request Date:' . date("Y-m-d H:i:s") . '<br>';
$log .= 'Request url: ' . $api_url . '<br>';
$log .= 'Request Method: ' . $api_method . '<br>';
$log .= 'Content Type: ' . $contentType . '<br>'; $log .= 'Http Code: ' . $code . '<br>';
$log .= '<code>response: ' . $response . '</code>';
write_log($log);
}
if ($code == 200) {
http_response_code($code);
if (checkjson($response)) {
echo $response;
} else {
if (strpos($api_url, 'AddUser') !== false) {
if ($response == "error") {
http_response_code(200);
echo json_encode(['status' => 'success']);
exit;
}
}
if (strpos($api_url, 'EditUser') !== false) {
if ($response == "error") {
http_response_code(200);
echo json_encode(['status' => 'success']);
exit;
}
}
if ($response == "error") {
http_response_code(404);
echo json_encode(['status' => $response]);
} else if ($response == "success") {
http_response_code(200);
echo json_encode(['status' => $response]);
} else if ($response == "user already exist") {
http_response_code(409);
echo json_encode(['status' => $response]);
} else {
echo json_encode(['data' => $response]);
}
}
} else {
http_response_code($code);
echo json_encode(['msg' => 'empty response'.$code.$handle]);
}
if ($code == 0) {
print_r(curl_getinfo($handle));
exit;
}
function write_log($data = '')
{
file_put_contents("log.html", '<div style="max-width:100%;border:1px solid #ccc; padding:5px">' . $data . '</div><br>', FILE_APPEND | LOCK_EX);
}
function checkjson($str)
{
return json_decode($str, true);
}
解决方案
您可以使用将自定义标题作为数组调用
$headersArray = array();
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
$headersArray[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
参考:https ://stackoverflow.com/a/11709337/11298876 ,这个答案真的很有帮助。现在您可以使用 headers 数组来调用每个标头(注意它将是驼峰式的)
$api_url = $headersArray['ApiUrl'];
$api_method = $headersArray['ApiMethod'];
$mobile = $headersArray['Mobilenumber'];
$brand = $headersArray['Branch'];
$auth = $headersArray['Authorization'];
获取实际的标题。
然后最后你可以像这样使用array_push(因为你已经在你的脚本中使用了它)
array_push($headers, "mobilenumber: ".$headersArray['Mobilenumber'], "branch: ".$headersArray['Branch'],"authorization: ".$headersArray['Authorization']);
发送标题。
推荐阅读
- cmake - Visual Studio 上的 CMake ExternalProject_Add 接收错误 MSB1009(但库构建)
- windows - LoadCursor 和混合 DPI 多显示器
- javascript - 本地图片的动态导入/加载
- python - 循环遍历动态 WTForm 中的字段
- javascript - 用javascript绘制像素化线?
- sql - 如何在 SQL 中选择某些字段采用 2 个不同值的那些 id?
- excel - 着色位于其自身工作表中的饼图切片 - excel vba
- c# - 将无符号字符值从 C++ dll 返回到 C# 的问题
- amazon-web-services - AWS Step Functions 输入
- solidity - solidity,如何将元组数组数据发送到合约