php file_get_content returing 401 on failed - php

I have web app and api and my login system works with api so it retruns: header status 200 if it success(username and password are correctly) otherwise it returns HTTP/1.0 401 Unauthorized and json message e.x: {success: 0 , "wrong username/password"} (tested with POSTMEN plugin in google chrome)
For e.x if i want to make a request:
$method = "login";
$data = array("user"=>"test", "pass"=>"test");
send_re($method, $data);
this is my function send_re
function send_re($method, $data){
$url = "api.location/".$api_method;
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header'=> "Content-Type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
return stripslashes( json_encode( $result) );
}
if my $data are correctly e.x username and password but if they are not I am not getting the error message but this:
A PHP Error was encountered
Severity: Warning
Message: file_get_contents(http://85.10.229.108/home/login): failed to open stream: HTTP request
HTTP/1.0 401 Unauthorized
Filename: libraries/api.php
Is there any way to escape this problem and get the message from api?

function send_re($method, $data){
$url = "api.location/".$api_method;
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header'=> "Content-Type: application/x-www-form-urlencoded\r\n",
'ignore_errors' => true
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
return stripslashes( json_encode( $result) );
}
Just add 'ignore_errors' => true and it's do the trick.
reference: http://php.net/manual/en/context.http.php

Related

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>';
}

Dropbox api get access token PHP

I try to get Dropbox access token using PHP,
https://www.dropbox.com/developers-v1/core/docs#request-token
I made 2 php files,
auth.php:
$Header = array(
"Authorization: OAuth oauth_version=\"1.0\", oauth_signature_method=\"PLAINTEXT\", oauth_consumer_key=\"XXX\", oauth_signature=\"XXX&\"\r\n"
);
$Options = array('http' =>
array(
'method' => 'POST',
'header' => $Header,
)
);
$Context = stream_context_create($Options);
$Result = file_get_contents("https://api.dropbox.com/1/oauth/request_token", false, $Context);
echo '<a target="_blank" href="https://www.dropbox.com/1/oauth/authorize?'.$Result.'&oauth_callback=http://localhost/dropbox/access_token.php">auth</a>';
auth.php file is working good! and redirect me to dropbox site to accept me app
but when redirect to access_token.php file, i can't get my access token!
I got error: failed to open stream: HTTP request failed! HTTP/1.1
access_token.php file:
$Options = array('http' =>
array(
'method' => 'POST',
)
);
$au = $_GET['oauth_token'];
$Context = stream_context_create($Options);
$Result = file_get_contents("https://api.dropboxapi.com/1/oauth/access_token?oauth_token=$au", false, $Context);
print_r($Result);
Check selinux setting for httpd_network_connect in Apache. It seems that file get content fails to open the stream.

Google Short URL API: Forbidden

I have what I think is correctly written code yet whenever I try and call it I'm getting permission denied from Google.
file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
This isn't a rate limit or anything as I currently have zero ever used...
I would have thought this is due to an incorrect API key but I've tried resetting it a number of times. There isn't some downtime while the API is first applied is there?
Or am I missing a header setting or something else just as small?
public function getShortUrl()
{
$longUrl = "http://example.com/";
$apiKey = "MY REAL KEY IS HERE";
$opts = array(
'http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json",
'content' => json_encode(array(
'longUrl' => $longUrl,
'key' => $apiKey
))
)
);
$context = stream_context_create($opts);
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url", false, $context);
//decode the returned JSON object
return json_decode($result, true);
}
It seems I need to manually specify the key in the URL
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url?key=" . $apiKey, false, $context);
This now works. There must be something funny with how the API inspects POST for the key (or lack of doing so).
Edit: For anyone in the future this is my complete function
public static function getShortUrl($link = "http://example.com")
{
define("API_BASE_URL", "https://www.googleapis.com/urlshortener/v1/url?");
define("API_KEY", "PUT YOUR KEY HERE");
// Used for file_get_contents
$fileOpts = array(
'key' => API_KEY,
'fields' => 'id' // We want ONLY the short URL
);
// Used for stream_context_create
$streamOpts = array(
'http' =>
array(
'method' => 'POST',
'header' => [
"Content-type: application/json",
],
'content' => json_encode(array(
'longUrl' => $link,
))
)
);
$context = stream_context_create($streamOpts);
$result = file_get_contents(API_BASE_URL . http_build_query($fileOpts), false, $context);
return json_decode($result, false)->id;
}

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