简体   繁体   中英

Can't get data from API using PHP+cURL

I'm trying to get some data from the web service here (a botanical taxonomic database). First I tried from the client side (Javascript/AJAX), but was getting a cross-domain restriction . Then I switched to server side (PHP/cURL), but it's not working, my session drops during the request. I followed the suggestions here , but still it doesn't work.

What I'm doing: I call a file through AJAX, like

getMOBOT.php?genus=Ocotea&sp=guianensis

The getMOBOT.php file:

<?php
include_once '../../includes_pl/db_connect.php';
include_once '../../includes_pl/functions.php';
sec_session_start();
if (isset($_GET['genus'])) {
    $genus = $_GET['genus'];
    if (isset($_GET['sp'])) {
        $sp = $_GET['sp'];
        $curl = curl_init("http://services.tropicos.org/Name/Search?name=$genus+$sp&type=wildcard&apikey=[...]&format=xml");
        $curl_response = curl_exec($curl); // error!
        curl_close($curl);
        echo "It works!";
    }
}
?>

I've read that I need to close the session (session_write_close()) before the curl_exec attempt (where my session is dropped), and reopen it later (session_start()), but:

1) I have a special function for secure sessions, the one called sec_session_start(). No matter if I use it, or the default session_start() (after curl_exec), none of them works.

2) Since there's no need to use the session in this file, I removed the two include_once lines, and also the sec_session_start(). Still doesn't work, I just get a blank response (HttpReq.readyState == 4, HttpReq.status != 200 and HttpReq.statusText == '').

3) If I type the URL in the browser it works, which means my key is valid (which I can't show here, it's substituted by the [...]).

EDIT: Changed the "curl_exec" line for:

if (!curl_exec($curl)) {
    die('Erro: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
} else {
    echo "It works!";
}

but still get nothing. What am I doing wrong, please?

EDIT 2: I'm behind a corporate proxy. Maybe is this (again!) the problem?

Yes, it was the proxy (again)!

I only needed to add

$proxy = 'address:port';
$proxyauth = 'user:password';
curl_setopt($curl, CURLOPT_PROXY, $proxy);
curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyauth);

in the right places.

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