How to create and update a file in a Github repository with PHP and Github API?

谁都会走 提交于 2019-12-06 09:21:02

Looks like research paid off and I can answer a main part of my own question (which I was not expecting to be able to do) - creating a new file. It looks like the same approach will be useable to update an exisiting file (if not, I'll be back).

This link helped: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

I realised the path referred to in Github API docs (https://developer.github.com/v3/repos/contents/#get-contents) - section Create a File - could be used as the url for curl as:

https://api.github.com/repos/ USER / REPO_NAME /contents/ FILENAME

And some tweaks were needed to allow for JSON to be sent. So I now have:

$curl_url = $url
$curl_token_auth = 'Authorization: token ' . $token;
$ch = curl_init($curl_url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'User-Agent: $username', $curl_token_auth ));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

$response = curl_exec($ch);  
curl_close($ch);
$response = json_decode($response);

return $response;

For the $data, I used the JSON example from the Github API page:

{
  "message": "my commit message",
  "committer": {
    "name": "Mike A",
    "email": "someemail@gmail.com"
  },
  "content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}

After implementing this within a PHP file (on shared hosting), no other frameworks used, I saw the new file in the Github respository.

Maybe it will help to Someone(With SHA feature in addition to update or delete files):

<?php
$file_git = "wall.jpg";
$data_git = array(
'sha'=>file_get_contents("sha.txt"),
'message'=>'image',
'content'=> base64_encode($file_git),
'committer'=> array(
'name'=>'Jacob',
'email' => '45331093+greenandgreen@users.noreply.github.com'
)
);
$data_string_git = json_encode($data_git);
$ch_git = curl_init('https://api.github.com/repos/YOUR_REPO/contents/wall.jpg');
curl_setopt($ch_git, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch_git, CURLOPT_POSTFIELDS, $data_string_git);
curl_setopt($ch_git, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_git, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 YaBrowser/19.9.3.314 Yowser/2.5 Safari/537.36',
'Authorization: token PLACE_YOUR_PERSONAL_TOKEN_HERE'
));
$result_git = curl_exec($ch_git);
echo $result_git;
$p_git = json_decode($result_git);
file_put_contents("sha.txt",$p_git->content->sha);
?>

Tested on PHP 7. If the code is working, then I wouldn’t refuse likes, in gratitude for the little work :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!