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