使用file_get_contents在php文件中定义变量


Using file_get_contents in php file to define variable

我正在使用ServerPilot API将自签名SSL证书应用于ServerPilot应用程序。我已经准备好了csr, key和crt文件。现在我使用下面提供的脚本将密钥和crt txt文件的内容保存到一个变量,然后可以在脚本中使用该变量保存到ServerPilot应用程序。

#!/usr/bin/php
<?php
$clientid = "redacted";
$apikey = "redacted";
$appid = file_get_contents("temp_serverpilot-appid_filtered.txt");
$vardomainname = file_get_contents("temp_serverpilot-domainname.txt");
$sslkey = file_get_contents("/root/certs/$vardomainname/ssl.key");
$sslcert = file_get_contents("/root/certs/$vardomainname/ssl.crt");
$data = array(
    "key" => $sslkey,
    "cert" => $sslcert,
    "cacerts" => null
);
$data_string = json_encode($data);
$ch = curl_init("https://api.serverpilot.io/v1/apps/$appid/ssl");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$clientid:$apikey");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
curl_close($ch);
echo json_encode(json_decode($result), JSON_PRETTY_PRINT);

有两个问题:1. 在$sslkey和$sslcert变量上使用file_get_contents会在路径中添加另一个变量。当我运行php脚本时,它返回如下内容:

PHP Warning:  file_get_contents(/root/certs/mydomainredacted.com/ssl.key): failed to open stream: No such file or directory in /root/serverpilot-ssl-apply.php on line 11
Warning: file_get_contents(/root/certs/mydomainredacted.com/ssl.key): failed to open stream: No such file or directory in /root/serverpilot-ssl-apply.php on line 11
  • 如果我手动在$sslkey和$sslcert变量中输入域名进行测试。PHP警告不会发生,但是脚本不会执行。
  • 如果我测试回显变量,则两个ssl文件的文件内容将正常返回到屏幕。

    第一期

    $vardomainname的字符串不正确。缺少字符,字符太多,隐藏字符,或者只是简单的错误;idk .

    "/root/certs/$vardomainname/ssl.key"不存在

    您无权访问"/root/certs/$vardomainname/ssl.key"


    问题# 2

    改变:

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    

    根据curl_setopt()CURLOPT_POSTFIELDS部分,您需要提供PHP数组或适当的urlencode()数组为字符串。JSON在这里不合适。


    最后但同样重要的是

    没有curl_errnocurl_error()你是盲人