Twitter API 无法在托管上工作 [在本地主机上工作正常]


Twitter APIs not working on hosting [Works fine on localhost]

我正在开发一个应用程序,以显示给定地理位置(纬度和经度)1英里半径内的推文。这是我的PHP代码,

<?php
// $lat = $_GET['lat'];
$lat = 26.511740;
// $long = $_GET['long'];
$long = 80.234973;
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$notweets = 100;
$consumerkey = "XXXX";
$consumersecret = "XXXX";
$accesstoken = "XXXX-XXXX";
$accesstokensecret = "XXXX"; 
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
} 
$connection = getConnectionWithAccessToken($consumerkey,$consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?geocode=".$lat.",".$long.",5mi&result_type=recent&count=".$notweets);
// echo $tweets;
echo json_encode($tweets);
?>

我正在使用Wamp服务器(PHP V5.5.12),我的代码在上面工作正常。但是当我在一些免费托管站点上托管我的应用程序时(我已经尝试过 hostinger.in 和 000webhost.com),此脚本失败并且仅打印"null"。

请帮我解决这个问题。

提前谢谢。

我已经尝试过,hostinger和000webhost以及其他几个。它们不起作用的原因是连接到 Twitter 的库使用 php curl,许多免费托管都禁用了 curl,或者传出连接或 Twitter 拒绝来自免费托管服务器的 ips 的 curl 连接。对于我在互联网上读到的内容,这可能是因为许多黑客一直在搞乱Twitter并从免费托管帐户托管。因此,找到一个与 Twitter API 配合使用的 cpanel 的免费托管是一个挑战,我已经尝试了 20 多个,但它们不起作用,其中一些会自动删除帐户或文件或阻止 ftp 访问,如果您尝试卷曲到 Twitter

可能与您可用的库有关。

error_reporting(E_ALL)添加到脚本顶部。

检查cURL是否安装在廉价的主机上,因为我相信这是twitteroauth唯一需要的php库。

你的TwitterOAuth版本是什么?您的代码似乎非常旧,与最新版本不兼容。

  • https://twitteroauth.com/

 

<?php
require "vendor/autoload.php";
use Abraham'TwitterOAuth'TwitterOAuth;
$lat = 26.511740;
$long = 80.234973;
$notweets = 100;
$ck = "XXXX";
$cs = "XXXX";
$ot = "XXXX-XXXX";
$os = "XXXX"; 
$to = new TwitterOAuth($ck, $cs, $ot, $os);
$tweets = $to->get('search/tweets', [
    'geocode' => "$lat,$long",
    'result_type' => 'recent',
    'count' => $notweets,
]);
if (isset($tweets->errors[0]->message)) {
    echo 'Error: ' . $tweets->errors[0]->message;
} elseif (!is_array($tweets)) {
    echo 'Unknown Error';
} else {
    echo '<pre>';
    var_dump($tweets);
    echo '</pre>';
}

或者,您可以使用 TwistOAuth 而不是 TwitterOAuth 。我是这个图书馆的作者。这个库几乎与TwitterOAuth兼容,但支持严格的异常处理。错误原因总是要清楚的。

  • https://github.com/mpyw/TwistOAuth

 

<?php
require 'TwistOAuth.phar'; // Or 'vendor/autoload.php' for composer
$lat = 26.511740;
$long = 80.234973;
$notweets = 100;
$ck = "XXXX";
$cs = "XXXX";
$ot = "XXXX-XXXX";
$os = "XXXX"; 
try {
    $to = new TwistOAuth($ck, $cs, $ot, $os);
    $tweets = $to->get('search/tweets', [
        'geocode' => "$lat,$long",
        'result_type' => 'recent',
        'count' => $notweets,
    ]);
    echo '<pre>';
    var_dump($tweets);
    echo '</pre>';
} catch (TwistException $e) {
    echo 'Error: ' . $e->getMessage();
}

你喜欢哪个代码?