Skip to content

Instantly share code, notes, and snippets.

@coderbyheart
Last active December 18, 2017 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderbyheart/5047852 to your computer and use it in GitHub Desktop.
Save coderbyheart/5047852 to your computer and use it in GitHub Desktop.
PHP stream context POST redirect problem
<?php
$base64cred = '<your auth data here>'; // base64_encode('username:password');
/** @var string Contains the redirect url */
$redirectUrl = null;
/**
* Used to catch the redirect location
*/
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max)
{
global $redirectUrl;
switch ($notification_code) {
case STREAM_NOTIFY_REDIRECTED:
$redirectUrl = $message;
break;
}
}
// Create, will fail with a 401 error
$options = array(
'http' => array(
'method' => 'POST',
'follow_location' => false,
'header' => array(
'Content-Type: application/json',
'Authorization: Basic ' . $base64cred,
),
'content' => '{"scopes":["repo"],"note":"Composer Debug","note_url":"https:\/\/getcomposer.org\/"}'
),
);
$ctx = stream_context_create($options, array("notification" => "stream_notification_callback"));
$result = file_get_contents('https://api.github.com/authorizations', null, $ctx);
// GET the created auth will work
$getOptions = array(
'http' => array(
'method' => 'GET',
'header' => array(
'Content-Type: application/json',
'Authorization: Basic ' . $base64cred,
),
),
);
$ctx = stream_context_create($getOptions);
$result = file_get_contents($redirectUrl, null, $ctx);
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment