2

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

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

这是我正在尝试使用的代码。首先有一个我用来发帖的功能。然后我为我的数据文件创建一个变量,并为我的身份验证服务的 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);  

 ?>

我的 creds.txt 文件的文本:

{“身份验证”:{“用户名”:“我的用户名”,“密码”:“我的密码”}}

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

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

“带有您的用户名和密码的 JSON 格式的文本文件”

4

2 回答 2

1

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

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

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

于 2012-05-01T07:17:32.133 回答
0

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

尝试:

$authkey = do_post_request($url, file_get_contents($data));
于 2012-05-01T07:17:11.917 回答