My code is below. The URL shortening service works, but it doesn't when I insert my $POST
. Does anyone know how to fix this my looking at the code?
// This is the URL you want to shorten
$longUrl = 'http://www.mysite.com/XXXXX/XX/$_POST['qrname']';
// Get API key from : http://code.google.com/apis/console/
$apiKey = 'MyAPIKey';
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
// Change the response json string to object
$json = json_decode($response);
curl_close($curlObj);
echo 'Shortened URL is: '.$json->id;
Try with this code. I is working for me.
Try as below
$longUrl = 'http://www.mysite.com/XXXXX/XX/'.$_POST['qrname'];
The above will work.
you are passing the php variable between the single quotes so it will not be parsed. pass it between double quotes like
OR concatinate like this
replace
$longUrl = 'http://www.example.com/XXXXX/XX/$_POST['qrname']';
with the following
$longUrl = 'http://www.example.com/XXXXX/XX/{$_POST['qrname']}';
You have a key, but you are not using it correctly
You should append it to the url, don't send the key in the post
Please check https://developers.google.com/url-shortener/v1/url/insert