Twitter API works only with one method - php

$key = 'fd2fdfsdfsdfdsf';
$secret = 'fdsfdsfdsfdsfdsfsdf';
$basic_credentials = base64_encode($key.':'.$secret);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Authorization: Basic '.$basic_credentials."\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => 'grant_type=client_credentials'
)
);
$context = stream_context_create($opts);
$pre_token = file_get_contents('https://api.twitter.com/oauth2/token', false, $context);
$token = json_decode($pre_token, true);
if (isset($token["token_type"]) && $token["token_type"] == "bearer")
{
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Authorization: Bearer '.$token["access_token"]
)
);
$context = stream_context_create($opts);
$data = file_get_contents('https://api.twitter.com/1.1/search/users.json?q=twitter', false, $context);
var_dump($data); die();
The code above returns false. I have no idea why. When I change the url into:
https://api.twitter.com/1.1/statuses/user_timeline.json?count=200&user_id=43243243
It works perfectly and returns the whole JSON.
Why is that so? I can't get it to work with any other API methods other than this one. The key and secret are the same in each situation. Nothing should be changed.

Related

PHP: Using file_get_contents to access an API - Empty Response

Sorry for the messy code in advance. I want to write a code which returns me infos from the official Blizzard API, which I can then print out on my homepage. The code doesn't throw any errors but it doesn't print out something either. For Starters:
I would also prefer using CURL, but my homepage is on a Wordpress Hosting Site and I don't know how to install the CURL Library that way
allow_furl_open is on
$url = "https://eu.battle.net/oauth/token";
$data = array('grant_type' => 'client_credentials');
//HTTP options
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array ('Content-type: multipart/form-data', 'Authorization: Basic ' .
base64_encode("$client_id:$client_pass")),
'content' => json_encode($data)
)
);
//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
$accessToken = $json['access_token'];
$tokenURL = "https://us.api.blizzard.com/data/wow/token/?namespace=dynamic-eu";
$opts2 = array('http' =>
array(
'method' => 'POST',
'header' => array('Content-type: multipart/form-data', 'Authorization: Bearer ' . $accessToken),
)
);
$context2 = stream_context_create($opts2);
$json2 = file_get_contents($tokenURL,false,$context2);
$result2 = json_decode($json2, true);
$tokenprice = $result2['price'];
echo "<p>Tokenpreis:" .$tokenprice. "</p>";
I didn't add the $client_id and $client_pass into the code snippet, but this exists obviously. I used this PHP CURL Snippet as template. And this is a short explanation on blizzard's site on how is this supposed to work:
Anyone got any ideas what went wrong? I am really out of ideas here and would love anyone who could help.
Thanks in advance
Based on the curl example from the linked API docs, the content type should be application/x-www-form-urlencoded, and so for the initial request to https://eu.battle.net/oauth/token you should be able to follow the example here.
In your case this will look something like:
$url = 'https://eu.battle.net/oauth/token';
$data = array('grant_type' => 'client_credentials');
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array (
'Content-type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode("$client_id:$client_pass")
),
'content' => http_build_query($data)
)
);
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
Also, in your code you are storing the raw result from the initial request in $json, then the decoded array in $result, but attempting to get the access_token from the initial request, instead of the decoded array.

PHP sends GET instead of POST

I have to post some data, but the same adress have some GET and POST functions. My PHP is sending a GET instead of a POST.
$apiURL = 'https://myAPI.com.br/api';
$data = http_build_query(array('postdata' => 10));
$uriRequest = $apiURL.'/main';
$options = array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
'https' => array(
'header' => 'Content-type: application/x-www-form-urlencoded',
'method' => 'POST',
'content' => $data
),
);
$context = stream_context_create($options);
$result = file_get_contents($uriRequest, false, $context);
if ($result === FALSE) {
return var_dump($result);
}
return var_dump($result);
I know the ssl part it isnt safe, but it is just for prototyping purpose.
I cant get PHP to POST intestead of GET on the adress 'https://myAPI.com.br/api/main'.
Judging from http://php.net/manual/de/function.stream-context-create.php#74795 the correct way to create a stream context for a https secured page is:
<?php
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
As you can see we are using 'http' => array... instead of https.

How to add Content-length To http request in php

I want to use octoparse API.
AND I have error when I want to clear data in octoparse API.
AND this my code
ini_set('max_execution_time', 300);
$url = 'https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>';
$options = array(
'http' => array(
'header' => "Authorization: bearer <mykey>",
'method' => 'POST'
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo 'error';
}
var_dump($result);
My result
Warning: file_get_contents(https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required
And I try to add Content-length But It have an error My new code:
ini_set('max_execution_time', 300);
$url = 'https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>';
$a=strlen($url);
$options = array(
'http' => array(
'header' => "Authorization: bearer <my key>",
'method' => 'POST',
'header' => sprintf('Content-Length: %d', $a)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo 'error';
}
var_dump($result);
My result
Warning: file_get_contents(https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>): failed to open stream: HTTP request failed!
Can anyone know how to solve my problem.
Thank.
you are using multiple headers in HTTP. if you are using multiple headers then follow this process
'header' => array(
"Authorization: bearer <my key>",
sprintf('Content-Length: %d', $a)
),
And you can also used this code
$requestHeaders = array(
'Content-type: application/x-www-form-urlencoded',
'Authorization: bearer <my key>',
sprintf('Content-Length: %d', strlen($url));
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $requestHeaders),
)
);

recaptcha error; Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in

I am using recaptcha 2 and getting this weird error:
Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in ... on line 38.
the code is:
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
$page="contact";
include("includes/navbar.php");
echo '<div id="wrapper">';
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LfJnWQUAAAAANMRQApsnetVjggDqnn4hx7Ltbyz',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<h1>You did not prove you are human.</h1><h2> Please go back and complete the form!</h2>";
exit();
}
else if ($captcha_success->success==true) {
more code here to execute if captcha successfull
line 38 that triggers the error message is:
$verify = file_get_contents($url, false, $context);
The error message appears whether or not the robot box has been ticked. If the box has not been ticked, the "You did not prove you are human" message appears and if the robot box has been ticked the code is correctly processed, although the error message still appears.
How can I remove the error message? The site has an SSL certificate so I tried changing :
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
to:
$options = array(
'https' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
and that removes the error message, but then the "You did not prove you are human" message appears, even if the robot box is checked.
I am stumped.
Regards
Tog
Yes, I fixed it with:
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
$page="contact";
include("includes/navbar.php");
echo '<div id="wrapper">';
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LfJnWQUAAAAANMRQApsnetVjggDqnn4hx7Ltbyz',
'response' => $_POST["g-recaptcha-response"]
);
$query = http_build_query($data);
$options = array(
'http' => array (
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => 'POST',
'content' => $query
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<h1>You did not prove you are human.</h1><h2> Please go back and complete the form!</h2>";
exit();
}
else if ($captcha_success->success==true) {
more code here to execute if captcha successfull
I think there is a parameter missing inside your options, try something like this:
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'Content-Type: application/x-www-form-urlencoded'
)
);
$secretKey = '------------Your S-Key---------------';
$token = $_POST["g-token"];
$ip = $_SERVER['REMOTE_ADDR'];
/* ======================= POST METHOD =====================*/
$url = "https://www.google.com/recaptcha/api/siteverify?";
$data = array('secret' => $secretKey, 'response' => $token, 'remoteip'=> $ip);
// use key 'http' even if you send the request to https://...
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'Content-Type: application/x-www-form-urlencoded'
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if($response->success)
{
echo '<center><h1>Validation Success!</h1></center>';
}
else
{
echo '<center><h1>Captcha Validation Failed..!</h1></center>';
}

PHP - Content-type not specified assuming application/x-www-form-urlencoded

For 2 days I'm having trouble with my PHP script on my server. I've changed nothing and suddenly it didn't work anymore.
Here is the code:
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n",
'method' => "POST",
'content' => $query,
),
);
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n",'method' => 'POST',
'content' => http_build_query($data),));
$contexts = stream_context_create($opts);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $contexts, -1, 40000);
I'm getting these error messages:
Notice: file_get_contents(): Content-type not specified assuming
application/x-www-form-urlencoded in
Warning: file_get_contents(https://mobile.dsbcontrol.de): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server
Error in
But when I try the script locally it works perfectly.
You are passing $contexts to file_get_contents() and that only contains the User-Agent header in the $opts array. All other headers and options are in the $options array which you add in to $context but aren't using. Try:
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => "POST",
'content' => $query,
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context, -1, 40000);
While the existing answers did not work for me, I managed to solve the problem like this:
The PHP Manual says params must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($postdata)
);
$packet['method'] = "POST";
$packet['header'] = implode("\r\n", $header);
$packet['content'] = $postdata;
$transmit_data = array('http' => $packet);
$context = stream_context_create($transmit_data);
i'm using this
$url = '';
$result = json_decode(file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => http_build_query($dataQuery)
)
))), true);

Categories