只允许使用HTTPS访问API [复制]

问题描述 投票:-3回答:1

这个问题已经在这里有一个答案:

我使用此代码为我的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方法请求并检查内容类型设置为应用/ JSON。我怎么能允许访问API只使用HTTPS?

   //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个回答
0
投票

谢谢,

加入receive.php此代码。

我有send.php(在服务器上没有HTTPS连接)和receiving.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://';
© www.soinside.com 2019 - 2024. All rights reserved.