简体   繁体   中英

PHP curl rest client works when running on command line but not in webpage

I have written a standalone php script which make a curl post call. The script works fine from command line (run as php script from netbean IDE). But when I put the same code inside php controller and invoke the controller from webpage, it failed. The following is the code:

$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);

the output for the failed request is:

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
)

What can be the reason it fails when being invoked from web page (eg a button which calls the action function), whereas it works when running the standalone script from command line?

Thanks in advance!

Like Mohsin has said, you have missed a single quote in the $base_url variable (line 13 of your example code). So in your case, the syntax is incorrect. You can use php -l filename.php to check if the syntax is correct for a specified PHP file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM