使用我的用户名和密码创建一个 JSON 格式的文本文件


Create a JSON-formatted text file with my username and password?

我正在尝试使用 PHP 对 Web 服务进行身份验证,方法是使用包含 JSON 格式的用户名和密码的.txt文件发布到身份验证方法。

它不起作用,我很难弄清楚为什么不工作。

这是我尝试使用的代码。 首先,我正在使用一个函数来发布。 然后,我为数据文件创建一个变量,为我的 AUTH 服务的 URL 创建另一个变量。

<?php 

function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
           'method' => 'POST',
          'content' => $data
        ));
  if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
   if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}
// Let's get logged in and get an authkey 
$url = 'http://service.com/auth';
$data= 'creds.txt';
$authkey = do_post_request($url, $data);  
      
        print_r($authkey);  
 ?>

我的信用.txt文件的文本:

{
  "auth": {
      "username": "myusername",
      "password": "mypassword"
  }
}

我做错了什么? 我收到无效数据错误。 我是否需要使用文本文件的完整 URL? 文本文件的格式不正确吗?

该服务的文档只说我需要:

"包含您的用户名和密码的 JSON 格式的文本文件"

$data= 'creds.txt';应该是这样的:

$data= file_get_contents('creds.txt');

我没有看到您在任何地方打开creds.txt,我相信您应该以 jSON 格式发送。

如果不透露" service.com "或有关网站本身的更多详细信息,将很难找到解决方案,因为它可以是很多事情,但您永远不会传递实际数据(仅传递文件路径)。

尝试:

$authkey = do_post_request($url, file_get_contents($data));