如何在PHP

时间:2015-04-30 19:03:25

标签: php ios json downloading

底线问题:什么是正确的PHP,以便我可以在基于json的响应对象中包含二进制数据文件?

我有一个(iOS,虽然它不应该是重要的)应用程序与服务器进行通信。我希望服务器在成功登录时返回文件。我 NOT 希望通过浏览器或其他方式下载此文件。因此,文件目录不受公共浏览的影响。

我在服务器上有一个如下所示的文件结构:

.../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来说却很陌生。我成功上传了&amp;保存文件,但在下次登录时无法返回。

任何提示都将非常受欢迎。

谢谢!

1 个答案:

答案 0 :(得分:2)

在传输过程中尝试base64编码内容。例如$data = base64_encode($data);

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