我写了一个独立的php脚本,可以进行curl调用。该脚本可以从命令行正常运行(从netbean IDE作为php脚本运行)。但是,当我将相同的代码放入php控制器并从网页调用该控制器时,它失败了。以下是代码:
$data = '{"active":"true","state":["2" ,"1"],
"cat_item_Name":"IT Network Data Center",
"limit":2500,
"fields":["request","cat_item","number","active","state"],
"variables":"true",
"children":"true",
childOptions":{"limit":100,
"fields":["number","description","active","assignment_group","assigned_to"]
}}';
//decoded json object
$jsonDataObject = json_decode($data, true);
try {
$base_url = 'https://anotherwebsite;
$curl = curl_init($base_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); //$jsonDataObject);
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("username:password")
);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
close($curl);
失败请求的输出是:
Array
(
[url] => https://anotherwebsite
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0
[namelookup_time] => 0.224197
[connect_time] => 0.278377
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0
[redirect_time] => 0
)
从网页(例如,调用动作功能的按钮)调用时失败,而从命令行运行独立脚本时却起作用的原因是什么?
谢谢!
答案 0 :(得分:0)
就像Mohsin所说的那样,您错过了$ base_url变量中的单引号(示例代码的第13行)。因此,在您的情况下,语法不正确。您可以使用php -l filename.php
检查指定的PHP文件的语法是否正确。