douhuan1950 2017-09-19 04:08
浏览 49
已采纳

将值从Bash脚本传递给PHP

In Bash script, I call something like that

# !/bin/bash
output=$(curl -L -H "Authorization: token MY_TOKEN" https://MY_GITHUB_ENTERPRISE/api/v3/repos/USER_NAME/REPO/pulls/123/files)
echo $output

I receive a string from output. I want to pass this string into php code to use json_decode function. What should I do?

I'm going to write code in PHP part like this. Is it ok? Sorry for the numb question because I'm a newbie in both Bash script and PHP

#!/usr/bin/php
$json = json_decode($DATA_FROM_CURL, true);
// Some logic in php

// continue with bash script
#!/usr/bin/bash
echo ABC

**Note: I have to write all codes in a Bash script file.

UPDATE 1 Thank for Felipe Valdes's suggestion, I updated my code like this. However, I got the return

{"message":"Bad credentials","documentation_url":"https://developer.github.com/enterprise/2.8/v3"}

My code:

#!/usr/bin/php
<?php
// create curl resource 
$ch = curl_init();
$TOKEN = 'abclaldslsl';

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: token'.TOKEN;

// set url 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_URL, "https://MY_GITHUB_ENTERPRISE/api/v3/repos/USER_NAME/REPO/pulls/123/files");

//return the transfer as a string 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string 
$output = curl_exec($ch);

// close curl resource to free up system resources 
curl_close($ch);

print_r($output);
?>
  • 写回答

2条回答 默认 最新

  • doufu5747 2017-09-19 08:17
    关注

    You forgot an $ before your TOKEN variable.

    Your script could look something like this:

    #!/usr/bin/php
    <?php
    // create curl resource 
    $ch = curl_init();
    
    $host = 'https://MY_GITHUB_ENTERPRISE'; // your host
    $path = "/api/v3/repos/USER_NAME/REPO/pulls/123/files"; // your path
    $access_token = 'abclaldslsl'; // your access token
    
    // set url 
    curl_setopt($ch, CURLOPT_URL, $host . $path);
    curl_setopt($ch, CURLOPT_HTTPHEADER, 
    [
        'Accept: application/json', // inform the server you want a json response
        'Authorization: token '. $access_token, // set the access token
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    // check for errors
    if(!$response = curl_exec($ch)) 
    {
        die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }
    
    print_r(json_decode($output, true));
    

    You can use the argument vector (argv) to set your path and token if you wish:

    $path = $argv[1] ?? "/api/v3/repos/USER_NAME/REPO/pulls/123/files";
    $access_token = $argv[2] ?? 'abclaldslsl';
    

    That would allow you do override the default path and access token which would allow to user your command like this:

    $ myscript.php /api/v3/repos/USER_NAME/REPO/pulls/123/files MY_ACCESS_TOKEN
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?