【发布时间】:2014-10-15 15:29:07
【问题描述】:
我正在使用 PHP cURL-multi 在另一台服务器上发出 HTTP 请求。另一台服务器上的脚本在 Perl/CGI 中。如果出现致命错误,我想返回 500 服务器错误(除非有更好的方法)。
这是我的 PHP。请注意,fb() 是对 FirePHP 记录器的程序调用。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://otherserver.com/cgi-bin/myCgiScript.cgi");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
$result = curl_exec($ch);
if ($result === false) {
$errno = curl_errno($ch);
$error = curl_error($ch);
print "errno:\n";
var_dump($errno);
print "error:\n";
var_dump($error);
} else {
print "result:\n";
var_dump($result);
}
$info = curl_getinfo($ch);
print "info:\n";
var_dump($info);
curl_close($ch);
这是来自其他服务器的示例 Perl CGI 文件:
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use Try::Tiny;
my $q = new CGI();
try {
# Code that might die().
print $q->header({
-type => "application/json",
-status => "200 OK"
});
print $results;
} catch {
my $message = $_;
chomp($message);
print $q->header({
-type => "application/json",
-status => "500 Server Error",
-message => $message
});
};
但无论我做什么,我似乎都无法从 cURL 中获取“消息”文本。 (我也无法获得“500 服务器错误”的“服务器错误”部分。我知道我收到了 500 错误,但没有相应的文本。
编辑:
我简化了 PHP 示例。
现在它不遵循“失败”路径...即,如果我有CURLOPT_HEADER = 0,它只是返回"",或者如果CURLOPT_HEADER = 1,则返回500服务器错误的文本:
result:
string(398) "HTTP/1.1 500 Server Error
Date: Fri, 22 Aug 2014 15:32:38 GMT
Server: Apache/2.2.21 (Unix) DAV/2 mod_ssl/2.2.21 OpenSSL/1.0.0e
Message: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at /opt/apache/cgi-bin/CSU_SIGNUP_2.0/getCsuAttributes.cgi line 45
Content-Length: 0
Connection: close
Content-Type: application/json
"
info:
array(20) {
["url"]=>
string(46) "http://otherserver.com/cgi-bin/myCgiScript.cgi"
["content_type"]=>
string(16) "application/json"
["http_code"]=>
int(500)
["header_size"]=>
int(398)
["request_size"]=>
int(113)
["filetime"]=>
int(-1)
["ssl_verify_result"]=>
int(0)
["redirect_count"]=>
int(0)
["total_time"]=>
float(1.117776)
["namelookup_time"]=>
float(0.006001)
["connect_time"]=>
float(0.008552)
["pretransfer_time"]=>
float(0.266607)
["size_upload"]=>
float(0)
["size_download"]=>
float(0)
["speed_download"]=>
float(0)
["speed_upload"]=>
float(0)
["download_content_length"]=>
float(0)
["upload_content_length"]=>
float(0)
["starttransfer_time"]=>
float(1.11773)
["redirect_time"]=>
float(0)
}
【问题讨论】:
-
(1) 将示例归结为有用的东西——Perl 只需要引发 500 错误,不要与 JSON 等混淆。PHP 不需要多个请求或成功处理——只需检查错误代码,然后查找消息。然后,(2) 向我们展示你实际做了什么 得到了回报。
-
将示例编辑为更简单,提供输出。