简体   繁体   English

PHP curl帮助与Google URL Shortner API

[英]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 我正在尝试使用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']
     );
 }
?>

My html file: 我的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

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. 由于要连接到使用SSL的URL,因此需要在代码中为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']
     );
 }
?>

curl_exec() returns boolean false if something didn't go right with the request. 如果某些不正确的请求, curl_exec()返回boolean false。 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. 同样,您需要指定CURLOPT_RETURNTRANSFER-默认情况下,curl会将接收到的所有内容写到PHP输出中。 With this option set, it'll return the transfer to your $result variable, instead of writing it out. 设置此选项后,它将把转移返回到$ result变量,而不是将其写出。

I think it's coming form your html. 我认为它来自您的html。 You didn't put the form methode, so it send data by get. 您没有放置form方法,因此它通过get发送数据。

And you show something only if you have post. 而且只有在有帖子的情况下,您才显示内容。

Try to do in the form method="post" 尝试以method =“ post”的形式进行


Edit 编辑

Bobby the main problem is that you don't have one problem but several in this code. Bobby的主要问题是,在此代码中您没有遇到一个问题,而是多个问题。 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'])) ). if (isset($_POST['url']))永远不会返回true,因为表单发送的变量将是GET(或执行if (isset($_GET['url'])) )。

Secondly you call the function with { $response = shortenUrl('$url'); }. 其次,您可以使用{ $response = shortenUrl('$url'); }. { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. 在这里,您不是发送url值,而是字符串'$ url'。 So your variable $longUrl is always '$url'. 因此,变量$ longUrl始终为“ $ url”。

Thirdly you don't use sprintf like you should. 第三,您不应该像应该那样使用sprintf。

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

Sprintf need to take a string format: Sprintf需要采用字符串格式:

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 在PHP中

You need to set CURLOPT_RETURNTRANSFER option in your code 您需要在代码中设置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']
     );
 }
// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM