php - 如何在 PHP 中安全地返回文件数据

标签 php ios json download

底线问题:什么是正确的 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-filePathdata 参数让我高度确定我在这个特定的代码路径上(与其他地方的一些其他失败相反。)

我相当精通 iOS,但对 PHP 还是个新手。我设法上传并保存文件以供使用,但在下次登录时无法返回它。

如有任何提示,我们将不胜感激。

谢谢!

最佳答案

传输时尝试base64编码内容。例如$data = base64_encode($data);

如果通信协议(protocol)是json,我很确定二进制数据不能直接工作,因此建议使用base64编码传输。

关于php - 如何在 PHP 中安全地返回文件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29975712/

相关文章:

iphone - 这是将 objective-c 数组设置为彼此相等的最佳方法吗?

php - 如何通过经纬度查找20公里以内的用户

php - 使用透明登录过程跨多个站点进行相同登录

javascript - 您无法直接访问此页面 - HybridAuth Social Login

ios - 如何停止从另一个 ViewController 播放音频?

java - 使用 java 从动态 json 中查找键的值

php - 循环语法错误 : unexpected identifier (jquery+html+php) 中的 html 连接

php - 在 openlayers 3 中单击标记时显示弹出窗口

php - Auth::user() 在 Laravel 5.8 中返回 null

ios - 将 UIImage 转换为 CIImage 以裁剪为 CGRect。 AV基金会