如何在不破坏标题重定向PHP的情况下设置会话变量

时间:2017-06-07 13:56:44

标签: php

我知道我设置会话变量的一行是阻止标题重定向关闭。然后问题就变成了在不破坏标题重定向的情况下设置它的位置。

这是基于Microsoft Graph REST API的代码:

<?php
ob_start();

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$provider = array (
    'client_id' => '', //blank here for security reasons
    'client_secret' => '',
    'redirect_uri' => '', //blank here for security reasons
    'authority_url' => 'https://login.microsoftonline.com/common',
    'authorize_endpoint' => '/oauth2/v2.0/authorize',
    'token_endpoint' => '/oauth2/v2.0/token',
    'resource_id' => 'https://graph.microsoft.com',
    'sendmail_endpoint' => '/v1.0/me/sendmail',
    'scopes' => 'openid profile mail.send',
    'authorization_url' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
    'parameters' => '?client_id=xxxxxxx&response_type=code&redirect_uri=xxxx&response_mode=query&scope=openid profile mail.send&state=', //client id/redirect uri xx'ed here for security reason
);

if ($_SERVER['REQUEST_METHOD'] === 'GET' && !isset($_GET['code'])) {
    $_SESSION['state'] = Base64.encode(generateRandomString()); //this line caused the header to break
    header('Location: ' . $provider['authorization_url'].$provider['parameters'].$_SESSION['state']);
    exit();
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['code'])) {
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['state'])) {
        unset($_SESSION['state']);
        exit('State value does not match the one initially sent');
    }
}

1 个答案:

答案 0 :(得分:0)

我的直觉是删除环绕session_start()的条件语句,并无条件地使用该函数调用。我还会在重定向浏览器的header()之前使用session_write_close()。

您还想将Base64.encode更改为PHP base64_encode()函数。