user3219795
user3219795

Reputation: 1

Var_Dump (Error 400 - Bad Request)

I am working on a little project for a programming course here on my university. It involves getting data from the google api (JSON) and providing some of that information to the user.

function compare($city, $start, $destination)
{
    // merge city with start and destination
    $city_start = $start . ', ' . $city;
    $city_destination = $destination . ', ' . $city;

    // reject symbols that start with ^
    if (preg_match("/^\^/", $city) OR preg_match("/^\^/", $start) OR preg_match("/^\^/", $destination))
    {
        return false;
    }

    // reject symbols that contain commas
    if (preg_match("/,/", $city) OR preg_match("/,/", $start) OR preg_match("/,/", $city))
    {
        return false;
    }

    // determine url
    $url = "http://maps.googleapis.com/maps/api/directions/json?origin=$city_start&destination=$city_destination&sensor=false&mode=bicycling";
    echo $url;

    // open connection to google maps
    $curl_session = curl_init($url);
    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_session, CURLOPT_HEADER, 0);

    // get data from json output
    $json = curl_exec($curl_session);
    curl_close($curl_session);
    var_dump($json);
}

The above code returns a 400 error at var_dump, where $city, $start and $destination are respectively starting adress, destination adress and the city where the addresses belong to. The url stored in $url works alright and returns JSON output when entered in a browser.

Can anyone tell me what I am doing wrong?

Cheers,

D.

Upvotes: 0

Views: 243

Answers (1)

superphonic
superphonic

Reputation: 8074

You could try and urlencode the variables:

$city_start = urlencode($start . ', ' . $city);
$city_destination = urlencode($destination . ', ' . $city);

Upvotes: 1

Related Questions