Skip to content

Instantly share code, notes, and snippets.

@travstoll
Created January 15, 2017 16:29
Show Gist options
  • Save travstoll/d6d72855b4184fbfc30f3a20a9adbb4c to your computer and use it in GitHub Desktop.
Save travstoll/d6d72855b4184fbfc30f3a20a9adbb4c to your computer and use it in GitHub Desktop.
Create GitHub Issue in PHP with File_Get_Contents using GitHub API
<?
//personal auth token from your github.com account. doing this will eliminate having to use oauth everytime
$token = "zzzzzzzzYourPersonalGithubAccessTokenzzzzzzzz";
//post url, https://developer.github.com/v3/issues/
$url = "https://api.github.com/repos/octocat/some_repo/issues?access_token=" . $token;
//request details, removing slashes and sanitize content
$title = htmlspecialchars(stripslashes("Test Title''\s"), ENT_QUOTES);
$body = htmlspecialchars(stripslashes("Test Body'\'$%'s"), ENT_QUOTES);
//build json post
$post = '{"title": "'. $title .'","body": "'. $body .'"}';
//set file_get_contents header info
$opts = [
'http' => [
'method' => 'POST',
'header' => [
'User-Agent: PHP',
'Content-type: application/x-www-form-urlencoded'
],
'content' => $post
]
];
//initiate file_get_contents
$context = stream_context_create($opts);
//make request
$content = file_get_contents($url, false, $context);
//decode response to array
$response_array = json_decode($content, true);
//issue number
$number = $response_array['number'];
echo "Issue " . $number . " generated.";
?>
@ffd8
Copy link

ffd8 commented Feb 6, 2021

This is great, thanks! FYI, github is deprecating use of the access_token in the url.
Instead you should add auth to the post header:

$opts = [
	'http' => [
			'method' => 'POST',
			'header' => [
					'User-Agent: PHP',
					'Content-type: application/x-www-form-urlencoded',
					'Authorization: token '.$token,
			],
			'content' => $post
	]
];

I'm planning to use this to auto create issues from a form and realized it's best create a 'bot account', so the personal auth token only has write access to specific repos rather than all of main account. As mentioned, not an issue when only used on private repos).

@kas5986
Copy link

kas5986 commented Feb 6, 2021

thanks for the updates looking forward to seeing your form solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment