我正在将一些Perl代码转换为PHP。 但是,我对Perl知之甚少,所以我必须用粗略的意思对它进行编码。
而且,我不明白以下Perl代码意味着什么......
$req2->content(<<"POST_DATA")
和--$boundary
是什么意思?
我搜索了Perl documentation,但它很难找到。
PHP代码:
...
$boundary= 'Nobody-has-the-intention-to-erect-a-wall';
$req2 = curl_init($search_url);
curl_setopt($req2, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($req2, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($req2, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($req2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req2, CURLOPT_COOKIE, $cookie);
curl_setopt($req2, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data;boundary='.$boundary,
'Content-Length: ' . strlen($data_string))
);
$result= curl_exec($req2);
...
Perl代码:
...
my $boundary= 'Nobody-has-the-intention-to-erect-a-wall';
$req2->content_type('multipart/form-data;boundary='.$boundary);
$req2->header("Cookie"=>"access_token_cookie=$access_token_cookie; csrf_access_token=$csrf_access_token");
$req2->content(<<"POST_DATA"); #what means this?
--$boundary
Content-Disposition: form-data; name="num_result"
Content-Type: text/plain
$num_result
--$boundary
Content-Disposition: form-data; name="img"; filename="search.jpg"
Content-Type: image/jpeg
$image
--$boundary--
POST_DATA
my $res = $ua->request($req2);
...
实际上与PHP没有什么不同。
<<
Heredoc,也出现在PHP,略有不同:
echo (<<<"POST_DATA"
First line
Second line
POST_DATA
);
--
变量减少,如<?php $a=2; echo --$a;
注意:
当然,在Heredoc --
里面只是文字。
建议:
如果您不完全理解Perl,请尝试运行它(它不是恶意代码)。
my $boundary = 'Nobody-has-the-intention-to-erect-a-wall';
print(<<"POST_DATA");
--$boundary
Content-Disposition: form-data; name="num_result"
Content-Type: text/plain
$num_result
--$boundary
Content-Disposition: form-data; name="img"; filename="search.jpg"
Content-Type: image/jpeg
$image
--$boundary--
POST_DATA
将产量:
--Nobody-has-the-intention-to-erect-a-wall
Content-Disposition: form-data; name="num_result"
Content-Type: text/plain
--Nobody-has-the-intention-to-erect-a-wall
Content-Disposition: form-data; name="img"; filename="search.jpg"
Content-Type: image/jpeg
--Nobody-has-the-intention-to-erect-a-wall--
$req2->content(<<"POST_DATA"); #what means this?
<<"POST_DATA"
开始一个HERE document,基本上是一个长串。双引号""
告诉Perl做string interpolation。这意味着字符串中的变量将被其内容替换。当解析器遇到分隔符时,字符串结束,在这种情况下,分隔符是字符串POST_DATA
。
你所指的--
不是运营商。它用在字符串里面。该程序通过HTTP发送multipart/formdata
表单。如果您对技术细节感兴趣,请查看RFC 7578。实质上,请求主体的每个部分代表一个文档。它可以是多行的,包含大量信息。边界可以在HTTP标头中设置,并且通常是一个长的随机字符串,不会出现在任何正文部分中。有关更详细的说明,请参阅this answer。