从PHP的POST响应下载ZIP文件

时间:2018-07-02 22:01:26

标签: php curl post php-curl

在Python中,我可以编写以下代码:

def func(url, configuration_username, configuration_pass):
    with requests.Session() as session:
        params = {
            'configuration_username': configuration_username,
            'configuration_pass': configuration_pass,
        }
        if response.status_code == 200:
            if 'Login error' not in response.text:
                print('OK: Login success')
                downloaded_zip = zipfile.ZipFile(io.BytesIO(response.content))
                downloaded_zip.extractall()
            else:
                print('ERROR: Login error')
        else:
            print('ERROR: Received status code %d' % response.status_code)

基本上,有一个网站登录。输入凭据并按Submit时,它将发送带有相应凭据的POST请求。响应是一个.ZIP文件,但它也会发送登录页面源。在Python中,我可以执行此操作,因为response.content具有以字节为单位的ZIP文件数据,而response.text是页面源代码。这样,我可以检查response.text中是否存在来自网页的任何错误,然后将response.content中的字节写入ZIP并将其提取。我想用PHP重写它,但是我也不想接收页面源代码。

<?php
ob_start();
session_start();
header("X-XSS-Protection: 0");

$configuration_username = "myusername";
$configuration_pass = "mypass";
$params = array(
    "configuration_username" => $configuration_username,
    "configuration_pass" => $configuration_pass
);
$server_url = "http://myurl.com";
$ch = curl_init($server_url);
$destination_file = "/var/www/html/filetest.zip";
$file_resource = fopen($destination_file, "w");
$curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FILE, $file_resource);
$response = curl_exec($ch);

if ((curl_errno($ch)) or (!$response)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
fclose($file_resource);

ob_end_flush();
?>

上面的代码将响应字节写入文件,但是结果是页面源代码之外的ZIP字节。有什么解决办法吗?

0 个答案:

没有答案