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

标签 php json api http authentication

我正在尝试使用 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);  

 ?>

我的 creds.txt 文件的文本:

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

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

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

"a JSON-formatted text file with your username and password"

最佳答案

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

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

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

关于php - 使用我的用户名和密码创建一个 JSON 格式的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10394567/

相关文章:

php - 如何从名为 'ford' 的数据库中选择分类为 'topselers' 的所有产品?

c# - 来自数据表和 IList 的嵌套 JSON

javascript - 为什么有些对象文字属性被引用而有些则没有?

c# - 用于社交媒体操作的通用 API

php - 关于 CSSTidy 的问题

php - 多数据库没有值(value)

php - MAMP "Apache couldn' 无法启动,因为端口正在使用 ."AND "无法通过/tmp/mysql.sock 连接到本地 MySQL 服务器

php - 如何更改 Web 服务器上的 FcgidMaxRequestLen?

php - 如何使用 json_encode 更正 php 中的语法

api - 收到致命警报 : handshake_failure when using Groovy HTTPBuilder for server using TLSv1. 2