如何在PHP中提取通过Python发送的gzip POST请求
我正在尝试用我的Python脚本获取的结果来填充一个数据库。我是通过POST请求发送压缩过的数据。
一个PHP脚本在中间充当网络服务,需要提取这些压缩数据,并获取'sql-query',然后进行后续处理。
这是我在Python这边尝试做的:
Sending a POST request using urllib:
# Data to be sent in POST request, it can be a SQL UPDATE/INSERT or SELECT
dictheaders = {'sql': "UPDATE 'logs' SET 'some_value' = Failed"}
# Encode the data
data = urllib.urlencode(dictheaders)
# Gzip compress the encoded data
IO = StringIO.StringIO()
gzip_data = gzip.GzipFile(fileobj=IO, mode='w')
gzip_data.write(data)
gzip_data.close()
gzip_data = IO.getvalue()
# This is the POST request being sent to a PHP web services file which
# needs to extract the gzipped query and then execute the query on SQL
f = urllib2.urlopen('http://x.x.x.x/example.php', gzip_data)
以下是我在PHP这边尝试过的修改:
$postdata = file_get_contents("php://input");
$a = gzinflate(substr(substr($postdata, 10), 0, -8));
$sql = $a['sql'];
上面的代码似乎和我的Python代码不兼容。这是提取PHP中gzip POST请求的正确方法吗?
2 个回答
1
试着把这个替换成这个:
# Gzip compress the encoded data
IO = StringIO.StringIO()
gzip_data = gzip.GzipFile(fileobj=IO, mode='w')
gzip_data.write(data)
gzip_data.close()
gzip_data = IO.getvalue()
用这个替换:
gzip_data = zlib.compress(data)
其实你不需要生成一个gzip文件,当你真正想要的只是压缩数据。
PHP那边的代码是好的,只需要去掉substr
,因为它们已经不需要了。不过,你把未压缩的字符串当成数组来处理,这样是行不通的。你需要在PHP那边解码查询字符串。我个人通常会用JSON来处理这些事情。
3
你用了 gzip.GzipFile
,这个方法会写入一个 gzip 文件头。在把数据传给 gzinflate
之前,你需要把这个文件头去掉;根据你的代码来看,你可能想要做的事情类似于 parse_str。
$str = gzinflate(substr($postdata, 10, -8));
parse_str($str, $a);
echo $a['sql'];
另外,在你的 Python 代码中,这一行可能有个拼写错误或者根本性的错误:
dictheaders = {'sql', 'SELECT * FROM employees'}
试试这样写:
dictheaders = {'sql': 'SELECT * FROM employees'}