【问题标题】:Allow to access API only using HTTPS [duplicate]仅允许使用 HTTPS 访问 API [重复]
【发布时间】:2019-06-29 05:29:00
【问题描述】:

我正在将此代码用于我的 api 应用程序。

//send.php
$url = 'http://example.com/api/';
$ch = curl_init($url);
$jsonData = array(
    'username' => 'MyUsername',
    'password' => 'MyPassword'
);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

我只能允许 POST 方法请求并检查设置为 application/json 的内容类型。 如何允许仅使用 HTTPS 访问 API?

   //receive.php  
        if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
            throw new Exception('Request method must be POST!');
        }

        $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
        if(strcasecmp($contentType, 'application/json') != 0){
            throw new Exception('Content type must be: application/json');
        }

        $content = trim(file_get_contents("php://input"));
        $decoded = json_decode($content, true);
        if(!is_array($decoded)){
            throw new Exception('Received content contained invalid JSON!');
        }   

谢谢

【问题讨论】:

标签: php json api post https


【解决方案1】:

谢谢,

在receive.php 中添加此代码。

我有 send.php(在没有 https 连接的服务器上)和接收.php(在有 https 连接的服务器上)

结果是:'https'

相反,我需要检查 send.php 的连接

   $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
            !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
                strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;

    echo ($https) ? 'https://' : 'http://';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 2020-05-03
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多