simplyblue
simplyblue

Reputation: 2339

php curl help with google url shortner api

Im trying to shorten a url using ggole api's.Here is my php code .It gives a blank page when i load

<?php
    define('GOOGLE_API_KEY', 'GoogleApiKey');
    define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');

    function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );

        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );

        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);

        // decode and return the JSON response
        return json_decode($result, true);
    }
    if (isset($_POST['url'])) {  
    $url = $_POST['url'];
    $response = shortenUrl('$url');

    echo sprintf(
        $response['longUrl'],
        $response['id']
     );
 }
?>

My html file:

<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>

<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">

<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">

</FORM>
</body>
</html

Upvotes: 0

Views: 1683

Answers (5)

Amol Gholap
Amol Gholap

Reputation: 111

// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
    curl_setopt($ch,CURLOPT_URL,$apiURL);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
    curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);

Upvotes: -1

Simon marc
Simon marc

Reputation: 1003

I think it's coming form your html. You didn't put the form methode, so it send data by get.

And you show something only if you have post.

Try to do in the form method="post"


Edit

Bobby the main problem is that you don't have one problem but several in this code. First if you don't do

<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">

the if (isset($_POST['url'])) will never return true, because the variable send by the form will be GET (or do a if (isset($_GET['url']))).

Secondly you call the function with { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. So your variable $longUrl is always '$url'.

Thirdly you don't use sprintf like you should.

echo sprintf(
        $response['longUrl'],
        $response['id']
     );

Sprintf need to take a string format:

echo sprintf("%s %s" // for example
    $response['longUrl'],
    $response['id']
 );

But do you know that you can do directly

echo $response['longUrl'] . ' ' . $response['id'];

You can concatenate string directly with . in php

Upvotes: 1

Eypeon
Eypeon

Reputation: 202

I think I have found a solution to your problem. Since you are connecting to a URL that uses SSL, you will need to add some extra parameters to your code for CURL. Try the following instead:

<?php
    define('GOOGLE_API_KEY', 'GoogleApiKey');
    define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');

    function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );

        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );

        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

        // extra parameters for working with SSL URL's; eypeon (stackoverflow)
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);

        // decode and return the JSON response
        return json_decode($result, true);
    }
    if (isset($_POST['url'])) {  
    $url = $_POST['url'];
    $response = shortenUrl('$url');

    echo sprintf(
        $response['longUrl'],
        $response['id']
     );
 }
?>

Upvotes: 5

Marc B
Marc B

Reputation: 360692

curl_exec() returns boolean false if something didn't go right with the request. You're not testing for that and assuming it worked. Change your code to:

$result = curl_exec($ch);

if ($result === FALSE) {
    die("Curl error: " . curl_error($ch);
}

As well, you need to specify CURLOPT_RETURNTRANSFER - by default curl will write anything it receives to the PHP output. With this option set, it'll return the transfer to your $result variable, instead of writing it out.

Upvotes: 1

shankhan
shankhan

Reputation: 6571

You need to set CURLOPT_RETURNTRANSFER option in your code

function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );

        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );

        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));


        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));


        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);


        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);

        // decode and return the JSON response
        return json_decode($result, true);
    }
    if (isset($_POST['url'])) {  
    $url = $_POST['url'];
    $response = shortenUrl('$url');

    echo sprintf(
        $response['longUrl'],
        $response['id']
     );
 }

Upvotes: 0

Related Questions