使用 php (curl)(无库)以编程方式更新 github 代码

Update github code programatically using php (curl) (no library)

如何在不使用任何外部库的情况下使用 php(最好是 curl)和 github api 以编程方式创建、更新和删除 github 代码(文件)?

我找不到任何相关信息。这可能吗?

可能 safest/most 正确的解决方案是使用 Github API。您可以在此处找到有关创建提交的文档:https://developer.github.com/v3/git/commits/#create-a-commit

我知道你不想使用图书馆,但这个图书馆可能会让这更容易:https://packagist.org/packages/knplabs/github-api

如果您不使用库,则需要了解如何确保您的请求得到正确验证:https://developer.github.com/v3/#authentication

终于解决了

<?php
  function pushFile($username,$token,$repo,$branch,$path,$b64data){
    $message = "Automated update";
    $ch = curl_init("https://api.github.com/repos/$repo/branches/$branch");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent:Php/Automated'));
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $token);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $data = curl_exec($ch);
    curl_close($ch);
    $data=json_decode($data,1);

    $ch2 = curl_init($data['commit']['commit']['tree']['url']);
    curl_setopt($ch2, CURLOPT_HTTPHEADER, array('User-Agent:Php/Ayan Dhara'));
    curl_setopt($ch2, CURLOPT_USERPWD, $username . ":" . $token);
    curl_setopt($ch2, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, TRUE);
    $data2 = curl_exec($ch2);
    curl_close($ch2);
    $data2=json_decode($data2,1);

    $sha='';
    foreach($data2["tree"] as $file)
      if($file["path"]==$path)
        $sha=$file["sha"];
    
    $inputdata =[];
    $inputdata["path"]=$path;
    $inputdata["branch"]=$branch;
    $inputdata["message"]=$message;
    $inputdata["content"]=$b64data;
    $inputdata["sha"]=$sha;

    echo json_encode($inputdata);

    $updateUrl="https://api.github.com/repos/$repo/contents/$path";
    echo $updateUrl;
    $ch3 = curl_init($updateUrl);
    curl_setopt($ch3, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'User-Agent:Php/Ayan Dhara'));
    curl_setopt($ch3, CURLOPT_USERPWD, $username . ":" . $token);
    curl_setopt($ch3, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch3, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch3, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch3, CURLOPT_POSTFIELDS, json_encode($inputdata));
    $data3 = curl_exec($ch3);
    curl_close($ch3);

    echo $data3;
  }
  //pushFile("your_username","your_personal_token","username/repository","repository_branch","path_of_targetfile_in_repository","base64_encoded_data");
?>