Gọi cURL gián tiếp qua một hàm khác thì không chạy được?

Em có hàm POST request như sau:

function sendAPI($url, $data){
    $ch = curl_init($url);
    $jsonDataEncoded = $data;
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    if(!empty($input['entry'][0]['messaging'][0]['message'])){
        $result = curl_exec($ch);
    }
}

Rồi em gọi nó:
sendAPI($someUrl, $someData);
thì nó không chạy, còn em dùng trực tiếp:

    $ch = curl_init($someUrl);
    $jsonDataEncoded = $someData;
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    if(!empty($input['entry'][0]['messaging'][0]['message'])){
        $result = curl_exec($ch);
    }

thì nó lại chạy bình thường. Ai giúp em với ạ :((

function mà ko return thì sao xuất kết quả được bạn ??

function sendAPI($url, $data){


return $result;
}
$result = sendAPI($someUrl, $someData);
2 Likes

Hàm không bắt buộc phải return mà bạn : http://stackoverflow.com/questions/7656685/does-php-functions-needs-return-any-value

Mình thử thêm cả return nhưng vẫn không chạy bạn ạ :((

1 Like

Haha, cái này nhiều người cũng cóc biết tại sao, cách của chủ topic không chạy, nhưng này thì chạy:

function sendAPI(){
    $ch = curl_init('http://http://daynhauhoc.com/t/goi-curl-gian-tiep-qua-mot-ham-khac-thi-khong-chay-duoc/30896');
    $jsonDataEncoded = 'đa ta gì thì chơi luôn vào đây';
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    if(!empty($input['entry'][0]['messaging'][0]['message'])){
        $result = curl_exec($ch);
    }
}

sendAPI();

Còn không thì gọi cái này:

`curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);``

trước khi gọi các curl_xxx nào khác.

2 Likes

À em fix được rồi ạ, do em chưa global cái $input @@ Cám ơn mọi người :smiley:

1 Like

Biến trong function là biến cục bộ mà bạn, cứ return cho lành =))

1 Like

Ok cám ơn bạn :smiley: Mình sẽ lưu í :smiley:

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?