PHP Curl помочь с API URL URL Shortner - PullRequest
0 голосов
/ 14 января 2011

Я пытаюсь сократить URL-адрес с помощью ggole api's. Вот мой php-код. Он дает пустую страницу при загрузке

<?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']
     );
 }
?>

Мой HTML-файл:

<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

Ответы [ 5 ]

5 голосов
/ 14 января 2011

Я думаю, что нашел решение вашей проблемы. Поскольку вы подключаетесь к URL-адресу, использующему SSL, вам необходимо добавить некоторые дополнительные параметры в код для CURL. Вместо этого попробуйте следующее:

<?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']
     );
 }
?>
1 голос
/ 14 января 2011

curl_exec() возвращает логическое значение false, если с запросом что-то пошло не так.Вы не проверяете это и предполагаете, что это сработало.Измените ваш код на:

$result = curl_exec($ch);

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

Также вам нужно указать CURLOPT_RETURNTRANSFER - по умолчанию curl запишет все, что получит в вывод PHP.Если этот параметр установлен, он вернет перенос в переменную $ result, а не выписывает ее.

1 голос
/ 14 января 2011

Я думаю, что это придет из вашего HTML.Вы не указали метод формы, поэтому он отправляет данные методом get.

И вы показываете что-то, только если у вас есть post.

Попробуйте сделать в форме method = "post"


Edit

Бобби, главная проблема в том, что у вас нет одной проблемы, а несколько в этом коде.Во-первых, если вы не выполните

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

, то if (isset($_POST['url'])) никогда не вернет true, потому что переменная, отправленная формой, будет GET (или if (isset($_GET['url']))).

Во-вторых, вы вызываете функцию с помощью { $response = shortenUrl('$url'); }. Здесь вы отправляете не значение url, а строку «$ url».Таким образом, ваша переменная $ longUrl всегда равна '$ url'.

В-третьих, вы не используете sprintf так, как должны.

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

Sprintf должен принимать формат строки:

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

Но знаете ли вы, что вы можете сделать напрямую

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

Вы можете объединить строку непосредственно с.в php

0 голосов
/ 30 апреля 2015
// 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);
0 голосов
/ 14 января 2011

Вам необходимо установить опцию CURLOPT_RETURNTRANSFER в вашем коде

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']
     );
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...