Warm tip: This article is reproduced from serverfault.com, please click

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

(其他 - Update github code programatically using php (curl) (no library))

发布于 2020-10-13 13:51:16

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

我对此一无所获。这可能吗?

Questioner
Ayan Dhara
Viewed
0
Ayan Dhara 2020-11-28 17:44:30

终于我解决了。

<?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");
?>