Github API 在 PHP 中更新一个文件


Github API update a file in PHP

我正在尝试使用github API,并尝试从我的网站更新文件(http://developer.github.com/v3/repos/contents/)

我可以设法获取我要更新的文件的最后一个提交SHA,并且一切都已设置。我关注了github库上的文档。

当代码运行时,它会打印出除 curl 调用响应之外的所有内容。我尝试了所有可能的修复方法:对PUT方法使用其他方法,检查是否启用了curl,更改不同类型的输入数据。但我无法让它工作。

可能我觉得我对 cURL 做错了什么,这就是为什么我没有得到回复的原因。我正在使用hostable.com

这是我的代码,请花点时间帮助我。非常感谢!

function editFileOnRepo($username, $password, $message, $path, $bodyContent, $repo, $sha){
$c = curl_init();
$url = "/repos/$username/$repo/contents/$path";
//PUT /repos/:owner/:repo/contents/:path
echo $url."'n";
curl_setopt($c, CURLOPT_VERBOSE, "false"); 
curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($c, CURLOPT_USERPWD, "$username:$password"); 
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_USERAGENT, "testacc01");
curl_setopt($c, CURLOPT_HEADER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($c, CURLOPT_PUT, true);
$data = array();
$data['path'] = $path;
$data['message'] = $message;
$data['content'] = $bodyContent;
$data['sha'] = $sha;
$content = json_encode($data, JSON_FORCE_OBJECT);
$headers = array(
    'X-HTTP-Method-Override: PUT', 
    'Content-type: application/json',
    'Content-Length: ' . strlen($content)
);
curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
echo $content;

$fp = fopen('php://temp/maxmemory:256000', 'w');
if (!$fp) {
    die('could not open temp memory data');
}
fwrite($fp, $content);
fseek($fp, 0); 
echo $fp;
curl_setopt($c, CURLOPT_BINARYTRANSFER, true);
curl_setopt($c, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($c, CURLOPT_INFILESIZE, strlen($content));   
error_log($url);
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($c);
echo "'nresponse:".$response;
curl_close($c);
}

您没有获得任何输出,因为您的 URL 缺少域部分。

$url = "/repos/$username/$repo/contents/$path";

应该是

$url = "https://api.github.com/repos/$username/$repo/contents/$path";

为了将来能够捕获此类问题,请使用curl_error功能

$response = curl_exec($c);
if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}

PS:这是一个8个月前未回答的问题,但仍然回答希望它能帮助其他人。