底线问题:什么是正确的 PHP,以便我可以在基于 json 的响应对象中包含二进制数据文件?
我有一个与服务器通信的应用程序(iOS,虽然它不重要)。我希望服务器在成功登录时返回一个文件。我不希望此文件可通过浏览器或其他方式下载。因此,文件目录受到保护,不被公开浏览。
我在服务器上有一个如下所示的文件结构:
.../userFiles/
myFile.zip
yourFile.zip
somebodyElsesFile.zip
// all the other files, snip
.../server/
login.php
// other stuff, snip
userFiles/
目录具有 drwxrw-----
权限,并且与 server/
的所有者和组相同,所以我 认为那部分是对的。
我的服务器 PHP 代码有:
// A bunch of stuff, snip.
// by this point, user is already verified valid login.
$filePath = "../userFiles/$username.zip";
if (file_exists($filePath))
{
// get the user's file
$fileData = file_get_contents($filePath);
if ($fileData)
{
$response->addparameters(array('data' => $fileData));
$response->addparameters(array('DEBUG-filePath' => $filePath));
}
else
{
$response->addparameters(array('msg' => "can't read data."));
$response->addparameters(array('DEBUG-filePath' => $filePath));
$response->setStatusCode(500);
}
}
else
{
// deal with non-existent file, snip
}
$response->send();
exit();
当我从我的应用程序登录时,响应 json 如下所示:
myapp[13529:3615028] -[LoginViewController connection:didReceiveData:] ***** Login, but no data:
{
"DEBUG-filePath" = "../userFiles/olie.zip";
data = "<null>";
token = [token redacted];
}
我做错了什么?更重要的是:什么是正确的 PHP,以便我可以在基于 json 的响应对象中包含二进制数据文件?
这应该无关紧要(除了我使用的是应用程序而不是浏览器来访问此 API),但我在 iOS 中运行,一旦这一切正常,我想要的获取文件数据的方式是:
NSData *zipFile = [json objectForKey: @"data"];
// unzip the file, deal with contents, snip.
其他信息:我的 $response
代码是 200,DEBUG-filePath
和 data
参数让我高度确定我在这个特定的代码路径上(与其他地方的一些其他失败相反。)
我相当精通 iOS,但对 PHP 还是个新手。我设法上传并保存文件以供使用,但在下次登录时无法返回它。
如有任何提示,我们将不胜感激。
谢谢!
最佳答案
传输时尝试base64编码内容。例如$data = base64_encode($data);
如果通信协议(protocol)是json,我很确定二进制数据不能直接工作,因此建议使用base64编码传输。
关于php - 如何在 PHP 中安全地返回文件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29975712/