OpenSubtitles API 401 Unauthorized how to fix? - php

I'm trying to fetch subtitles from OpenSubtitles (http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC) like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Opensubtitles listing
function data($request){
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://api.opensubtitles.org/xml-rpc'; // api url
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
return $response;
}
//Get token
$request = xmlrpc_encode_request("LogIn", array('', '', 'eng', 'TemporaryUserAgent'));
$token = data($request)['token'];
//Get listing
$request = xmlrpc_encode_request("SearchSubtitles", array(
'imdb' => '0462499',
'sublanguageid' => 'eng',
'season' => '',
'episode' => '',
'token' => $token
));
$response = data($request);
var_dump($response);
?>
However I keep getting 401 Unauthorized. Does anyone know how to fix this problem? I know it's not a problem with the API because I am able to retrieve the token just fine.

Try using your username/password instead empty string.
And change UserAgent in TemporaryUserAgent in Header as written in
http://trac.opensubtitles.org/projects/opensubtitles/wiki/DevReadFirst

The second request should be in the following format:-
$request = xmlrpc_encode_request("SearchSubtitles", array($token, array(array('sublanguageid' => 'eng', 'imdbid' => 'your_imdbid'))));
Hope this helps.

Related

Can not fetch value of an element using Symfony Dom Crawler

I am fetching a URL using guzzle POST method . its working and returning the page that I want . but the problem is when I want to get the value of an input element in a form in that page, the crawler returns nothing . I don't know why .
PHP:
<?php
use Symfony\Component\DomCrawler\Crawler;
use Guzzle\Http\Client;
$client = new Client();
$request = $client->get("https://example.com");
$response = $request->send();
$getRequest = $response->getBody();
$cookie = $response->getHeader("Set-Cookie");
$request = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$response = $request->send();
$pageHTML = $response->getBody();
//fetch orderID
$crawler = new Crawler($pageHTML);
$orderID = $crawler->filter("input[name=orderId]")->attr('value');//there is only one element with this name
echo $orderID; //returns nothing
What should I do ?
You don't have to create a Crawler:
$crawler = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$orderID = $crawler->filter("input[name=orderId]")->attr('value');
This assumes your POST isn't being redirected, if it is redirected you should add before calling the filter function:
$this->assertTrue($client->getResponse()->isRedirect());
$crawler = $client->followRedirect();

reCAPTCHA v.2 file_get_contents error

I made custom register page on wordpress using google recaptcha. It worked fine, without any errors but when i copied a code to new project it isnt working. No clue why. No secret and sitekey errors.
if(!empty($_POST['g-recaptcha-response']))
{
$gurl = 'https://www.google.com/recaptcha/api/siteverify';
$gdata = array(
'secret' => 'secret',
'response' => $_POST['g-recaptcha-response']
);
// use key 'http' even if you send the request to https://...
$goptions = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($gdata),
),
);
$gcontext = stream_context_create($goptions);
$gresult = file_get_contents($gurl, false, $gcontext);
var_dump($_POST['g-recaptcha-response']);
$gresult=json_decode($gresult);
if(!$gresult->success)
$register_errors[]='Error reCAPTCHA.';
}
UPDATE:
output of var_dump($_POST['g-recaptcha-response']) is some string propably hashed. $gresult = file_get_contents($gurl, false, $gcontext); is giving FALSE on var_dump($gresult);

Cannot login to MediaWiki-API with file_get_contents()

Where did I make a mistake? My PHP-script:
<?php
// Set username and password
$lgname = "someUsername";
$lgpassword = "somePassword";
// First login to receive 1) token, 2) sessionid and 3) cookieprefix
$parameters = array('action' => 'login', 'lgname' => "$lgname", 'lgpassword' => "$lgpassword", 'format' => 'json');
options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($parameters)
),
);
$context = stream_context_create($options);
$result = file_get_contents("http://en.wikipedia.org/w/api.php", false, $context);
// Echo out the answer from MediaWiki-API
echo "$result";
// Put the needed parts of the answer into variables and echo them out
$array = json_decode($result,true);
$token = $array["login"]["token"];
$sessionid = $array["login"]["sessionid"];
$cookieprefix = $array["login"]["cookieprefix"];
echo "</BR>token: $token, sessionid: $sessionid, cookieprefix: $cookieprefix</BR>";
// Second login to 1) post token and 2) send sessionID within the header
$parameters = array('action' => 'login', 'lgname' => "$lgname", 'lgpassword' => "$lgpassword", 'lgtoken' => "$token", 'format' => 'json');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Cookie: " . $cookieprefix . "_session = $sessionid\r\n",
'method' => 'POST',
'content' => http_build_query($parameters)
),
);
$context = stream_context_create($options);
$result = file_get_contents("http://en.wikipedia.org/w/api.php", false, $context);
// Echo out result
echo "$result";
?>
What I get as an answer to my second POST-request is (exactly the same as to my first POST-request) that I need a token (even though I posted the token and even the sessionID in my second POST-request):
{"login": {
"result":"NeedToken",
"token":"82b3f2e1f1aa702ca6ceae473bb16bde",
"cookieprefix":"dewiki",
"sessionid":"531143bd7425722bf1be88e520dea6d5"}
}
The mistake is in using file_get_contents() in the first place. Use a PHP library for the MediaWiki web API, instead.
If you really want to do things yourself, ask a token from meta=tokens.

tmhOauth update_with_media using hashtag forbidden

i am using tmhOauth library to post status to twitter.
why I got 403 when i try update_with_media with a hashtag inside it. below is full code.
session_start();
require 'tmhOAuth.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'MYKEY',
'consumer_secret' => 'MYSECRET',
'curl_ssl_verifypeer' => false
));
if(isset($_GET['oauth_verifier'])){
$tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];
$code = $tmhOAuth->request(
'POST',
$tmhOAuth->url('oauth/access_token', ''),
array(
'oauth_verifier' => $_GET['oauth_verifier']
)
);
if($code == 200){
$_SESSION['access_token'] = $tmhOAuth->extract_params($tmhOAuth->response['response']);
$tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret'];
$base64_data = file_get_contents($_SESSION['twitter_image_data']);
$status = <<<EOD
You can see yourself at Catholic U, too! Go to somelink.com to check out this cool app!
#hashtag
EOD;
echo strlen($status);
$params = array(
'media[]' => "{$base64_data};type=image/jpeg;filename=myimage.jpg",
'status' => $status
);
$response = $tmhOAuth->user_request(array(
'method' => 'POST',
'url' => $tmhOAuth->url("1.1/statuses/update_with_media"),
'params' => $params,
'multipart' => true
));
print_r($response);
if($response == 200){
?>
<pre>Your image has been uploaded to twitter. this window will be closed in 3 seconds...</pre>
<script>
setTimeout(function(){
window.close();
}, 3000);
</script>
<?php
}
unset($_SESSION['oauth']);
unset($_SESSION['twitter_image_data']);
}
}
anyway to debug it? $response only return response number. please help
You are having a 403 error which happens when accessing the page or resource you were trying to reach is forbidden for some reason. You should check for url errors and make sure you're specifying an actual web page file name and extension, not just a directory.

Get Twitter Following Count

Im creating a widget for a Wordpress site and i am trying to get the twitter following count, I can get the followers count which is taken from http://www.wpbeginner.com/wp-tutorials/displaying-the-total-number-of-twitter-followers-as-text-on-wordpress/. Any help would be great.
thanks Pierce
Current code in functions.php:
// Twitter
function getTwitterFollowers($screenName = 'hellowWorld')
{
// some variables
$consumerKey = 'hidden';
$consumerSecret = 'hidden';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}
It was pretty simple if I just read the documentation anyway...
Instead of followers_count i replaced it with friends_count as outlined in the API 1.1 documentation. :)

Categories