【问题标题】:properly endcoding & for twitter post正确结束编码和推特帖子
【发布时间】:2010-12-07 01:42:22
【问题描述】:

当我的更新字符串中包含 & 时,我对 Twitter API 的自动调用会导致问题。

在使用 CURL 调用 Twitter API 之前,如何正确编码包含 & 的更新字符串 $update

// Set username and password for twitter API
        $username = '***';
        $password = '***';

        // The twitter API address
        $url = 'http://twitter.com/statuses/update.xml';

        // Alternative JSON version
        // $url = 'http://twitter.com/statuses/update.json';

        // Set up and execute the curl process
        $curl_handle = curl_init();

        curl_setopt($curl_handle, CURLOPT_URL, "$url");
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_handle, CURLOPT_POST, 1);
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$update");
        curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");

        $buffer = curl_exec($curl_handle);

        curl_close($curl_handle);

        // check for success or failure

        if (empty($buffer)) 
        {
            echo 'error?!';
        } 

【问题讨论】:

  • 通过不安全的 HTTP 线路传递您的 Twitter 用户名和密码是一个非常糟糕的主意。
  • 告诉我一个安全的方法,我会使用它。 :)

标签: php api encoding curl twitter


【解决方案1】:

您有两个选择,urlencode()http_build_query()

// Using urlencode()
$update = 'this & that';
echo "status=" . urlencode( $update );

// Using http_build_query()
$postFields = array(
  'status' => $update
);
echo http_build_query( $postFields );

【讨论】:

    【解决方案2】:

    通过urlencode() 运行它或使用http_build_query()

    curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=" . urlencode($update));
    
    // or
    
    curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query(array("status" => $update));
    

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2019-01-05
      • 2015-04-22
      相关资源
      最近更新 更多