kong / unirest-php Goto Github PK
View Code? Open in Web Editor NEWUnirest in PHP: Simplified, lightweight HTTP client library.
Home Page: http://unirest.io/php
License: MIT License
Unirest in PHP: Simplified, lightweight HTTP client library.
Home Page: http://unirest.io/php
License: MIT License
How to get the http code when catch exception in response?
Please tag your composer release.
This is required for it to be used in redistributable libraries.
When passing through a query with an array parameter in the GET string, for example,
?user_id[]=1&user_id[]=2
I am only getting the results for user_id = 2. When I look in the result object, I see my results for user_id=2 repeated twice.
When I look in the raw_body, I see only one result ( user_id=2 ).
When using file_get_contents with the same query, I get both results as expected. I have tried with multiple parameters and my server code with file_get_contents handles the request as expected.
I suspect that somehow a query with:
"?user_id[]=1&user_id[]=2"
is somehow getting parsed as "?user_id[]=2&user_id[]=2".
The same effect happens with three parameters -
"?user_id[]=1&user_id[]=2&user_id[]=3" will only return the results for user_id = 3.
When processing the key/value pairs in the QueryString into an array, any values in the pairs which contain equal signs are truncated. When exploding the key/value pairs, the optional parameter should be set to 2 in order to make sure that everything beyond the first equal sign is considered part of the value portion. Otherwise the returned array has 3+ items, of which only the first and second are used, leaving part of the value from the QueryString unassigned.
Always get 403 error, its works with CURL but Unirest is not working
i try from CLI and from WebServer
here is the code:
$response = Unirest\Request::post("https://community-neutrino-ip-info.p.mashape.com/ip-info",
array(
"X-Mashape-Key" => "XXXX",
"Content-Type" => "application/x-www-form-urlencoded",
"Accept" => "application/json"
),
array(
"ip" => "5.29.224.80",
"reverse-lookup" => true
)
);
$Response = Unirest::get('http://google.com');
$headers = $Response->headers;
echo '<pre>';
print_r($headers);
echo '</pre>';
For this I get an array:
Array
(
[Location] => http://www.google.com/
)
Although, for all of my internal server REST calls I get an array like this:
Array
(
[Date] => Wed, 19 Jun 2013 20:12:30 GMT
)
When it should dump something like this:
Array
(
[Date] => Wed, 19 Jun 2013 20:15:23 GMT
[Server] => Apache/2.2.22 (Ubuntu)
[X-Powered-By] => PHP/5.4.6-1ubuntu1.2
[Cache-Control] => no-cache
[Transfer-Encoding] => chunked
[Content-Type] => application/json
)
I looked at the HttpResponse->get_headers_from_curl_response()
method, and it looked a little odd. I cleaned it up and it works great for me (returns all 6 of my headers). Will post a pull request in a minute.
Setting the URL of the HTTP request to a relative path / file will throw an exception as scheme
won't exist in the array returned from parse_url
Unirest.PHP...
$url_parsed = parse_url($url);
$scheme = $url_parsed['scheme'] . '://'; //Will not exist in a relative path URL
$host = $url_parsed['host'];
Doing the following:
$response = Unirest::get('http://xxxxx', array(
'user-agent' => '',
));
Gets this error:
PHP Fatal error: Cannot break/continue 1 level in ...vendor/mashape/unirest-php/lib/Unirest/Unirest.php on line 262
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Cannot break/continue 1 level","file":".../vendor/mashape/unirest-php/lib/Unirest/Unirest.php","line":262}}{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Cannot break/continue 1 level","file":".../vendor/mashape/unirest-php/lib/Unirest/Unirest.php","line":262}}
Hi,
I installed Unirest from source. Is there no way to use it with PHP 5.3.x? I noticed Request:426 calls hex2bin()
, which is missing from PHP 5.3.x. Are there other incompatibilities with 5.3.x? It would be nice if the PHP version requirement were made clearer on the README.md.
Thank you
While using the current build of Laravel 4, I get a class collision on HttpResponse. This was easily fixed by adding a namespace of Unirest to the 3 class files. Is there a reason this hasn't been done?
curl_setopt_array(): CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set...
[ROOT/vendors/unirest/src/Unirest/Request.php, line 423]
I have a client who needs something that I think Unirest would work fantastic - I haven't been able to get Unirest to work on a Wordpress install - is this because the HTTP headers can't be modified once Wordpress is instantiated, am I on the right track?
My code:
$response = Unirest\Request::post("https://textanalysis.p.mashape.com/nltk-sentence-segmentation",
array(
"X-Mashape-Key" => <key>,
"Content-Type" => "application/x-www-form-urlencoded",
"Accept" => "application/json"
),
array(
"text" => "Natural language processing (NLP) deals with the application of computational models to text or speech data. Application areas within NLP include automatic (mach
)
);
Response:
Unirest\Response Object
(
[code] => 400
[raw_body] => <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
[body] => <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
[headers] => Array
(
[0] => HTTP/1.1 400 BAD REQUEST
[Content-Type] => text/html
[Date] => Wed, 24 Feb 2016 15:33:40 GMT
[Server] => Mashape/5.0.6
[X-RateLimit-requests-Limit] => 1000
[X-RateLimit-requests-Remaining] => 974
[Content-Length] => 192
[Connection] => keep-alive
)
)
cURL works fine:
curl -X POST --include 'https://textanalysis.p.mashape.com/spacy-named-entity-recognition-ner'
-H 'X-Mashape-Key: '
-H 'Content-Type: application/x-www-form-urlencoded'
-H 'Accept: application/json'
-d 'text=Rami Eid is studying at Stony Brook University in New York'
I thought it might be a SSL problem, so I disabled peer verification with:
Unirest\Request::verifyPeer(false);
Is there a way to see all the curl options from unirest? Or debug the request somehow?
Is it possible to have the output to an array instead of an object? Casting it is an option but it's not pretty.
Please create versioned releases so that we can properly depend on specific versions using composer.
I don't think I'm able to set the CURLOPT_INTERFACE
option within Unirest.
A way to make this possible within Unirest will be very helpful.
I'm submitting a GET request with Unirest to my server.
The url of this GET request contains a token (it is needed to authorize the request). The server checks if this token is in the session, if it is the request is authorized.
The problem is that if I submit the request with Unirest the request is unauthorized.
If I take the same url, with the same token, and I submit this url to the browser, the request is authorized and the response is returned.
It's like Unirest makes some manipulation on the url string.
Do you have some clue to explain this behaviour?
Does this support async HTTP requests?
Hi,
When i call the http delete request with multiple parameters, i'm receiving the request on the other end as raw POST:
------------------------------4a8b2889f9f5
Content-Disposition: form-data; name="amount"
0.25
This does not happen when calling the post method.
I have tried updating the headers to be:
$headers = array(
"Accept" => "application/json",
"Content-type" => "application/x-www-form-urlencoded"
);
But the issue still happens.
Any thought on the issue?
I was testing the unirest-php by making a request to my local SOLR server and when using highlighting you will have to use the parameters hl.fl , hl.simple.post and hl.simple.pre
Unfortunately probably do to the encoding it replaces the dots in the parameters to underscores. Resulting in highlighting not working fully since it turns hl.fl, hl.simple.post and hl.simple.pre into hl_fl, hl_simple_post and hl_simple_pre.
I can work around this but it's quite annoying so I hope it can be fixed :-)
Example request:
$response = Unirest::get("http://localhost:8983/solr/collection1/select",
array("Accept" => "application/json"),
array(
"q" => '*'.$safe_query.'*',
"rows" => 10,
"wt" => "json",
"indent" => "true",
"fl" => "name",
"df" => "name",
"hl" => "true",
"hl.fl" => "name",
"hl.simple.post" => "</strong>",
"hl.simple.pre" => "<strong>"
)
);
Example result:
"responseHeader":{
"status":0,
"QTime":1,
"params":{
"df":"name",
"fl":"name",
"indent":"true",
"q":"*test*",
"hl_simple_post":"</strong>",
"hl_simple_pre":"<strong>",
"wt":"json",
"hl":"true",
"hl_fl":"name",
"rows":"10"}}
Using latest files but running into issues calling the File function. Below is my usage:
$body = array("content" => Unirest\File::add("/emails/basic.html");
$response = Unirest\Request::post($GLOBALS['restUrl'], $headers = '', $body);
I'd love to have the OAuth 1.0a support in this PHP version of Unirest (without using the PECL OAuth extension).
Hi.
When I call API from php using unirest, I always get 403 error.
I have copied and paste the code from API page, including my API key.
Console curl works well.
I am trying to use Unirest in my project, but it returns this error all the time:
Parse error: syntax error, unexpected T_STRING in /home/a3698007/public_html/lib/Unirest/HttpMethod.php on line 1
Why is this happening?
I am just doing this, like it suggests in the documentation:
require_once './lib/Unirest.php';
Hi...
Could be a problem between the monitor and keyboard, but if you pass a nested array as the payload, eg:
array('key'=>'value','items'=>array('item1','item2'));
.. as the unirest::request() $body argument, you get an 'Array to string conversion' conversion notice from line 134:
https://github.com/Mashape/unirest-php/blob/master/lib/Unirest/Unirest.php#L134
Essentially curl_setopt doesn't like nested arrays as payload...
http://php.net/manual/en/function.curl-setopt.php#107621
Tx...
curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead
line 187:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
I use it with Laravel 4.1 (up2date), PHP 5.5.11-3+deb.sury.org~precise+1
Yesterday night I created a PHP script using Unirest and everything worked just fine.
Today, I ran the exact same script and it is returning this error:
Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\tests\lib\Unirest\Unirest.php on line 100
I am using WAMP and just acessing some info from an API from Mashape. Any idea why it returns this error?
Hi,
I've returned to an Laravel application having not worked on it since October 2014. I am using a different laptop, and have pulled my repo from git, only to find that Unirest class is not found in my app anymore.
I have checked and double checked my composer.json files, and ran update several times, but there is no success. My colleague has just run a composer self-update, and it seems his app is now broken with the same error - not being able to find Unirest. There are no problems with any other dependancies.
Are there any known issues around this? We are using Laravel 4.2
I get INVALID_REQUEST on args like address=Çorovodë, Albania, Europe
You should use a Safe UTF-8 version of the parse_url func, as seen here.
Cheers,
Recommend implementing basic auth support, and timeout for curl.
$timeout = 10;
$username = 'foo';
$password = 'bar';
curl_setopt($curl_object, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($curl_object, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl_object, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
If a url of form "https://foo.com:123/a/b/" is used, then the library tries to connect to url "https://foo.com123/a/b/"
Fix: in file Unirest/Unirest.php
function encodeUrl
Change line:
$port = (isset($url_parsed['port']) ? $url_parsed['port'] : null );
to be
$port = (isset($url_parsed['port']) ? ':' . $url_parsed['port'] : null );
Thanks,
Larry
ps, sorry that I don't yet have git set up on my new machine to give you a proper pull request. Thanks again for the library.
My app on heroku uses unirest library(v 1.2.1
) for http requests. When I make a HTTP POST
request to a remote script I set Unirest::timeout(5)
(because I don't care about data returning from request).
But if it fails to get the data from the request, it complains about: Operation timed out after 5000 milliseconds with 0 bytes received
and some times it doesn't even process the remote script.
How do I get rid of that error message? Or is there a better way to achieve this?
Thanks.
i have problems with php unirest pls help me . i have code :
require_once 'vendor/autoload.php';
Unirest\Request::verifyPeer(false);
$response = Unirest\Request::post("https://savedeo.p.mashape.com/download",
array(
"X-Mashape-Key" => "Mykey",
"Content-Type" => "application/x-www-form-urlencoded",
"Accept" => "application/json"
),
array(
"url" => "https://vimeo.com/87374427"
)
);
print_r($response);
?>
and i have Revice error :
Unirest\Response Object ( [code] => 403 [raw_body] => {"message": "Invalid url: None"} [body] => stdClass Object ( [message] => Invalid url: None ) [headers] => Array ( [0] => HTTP/1.1 403 FORBIDDEN [Content-Type] => application/json [Date] => Sun, 08 Feb 2015 13:12:52 GMT [Server] => Mashape/5.0.6 [X-RateLimit-requests-Limit] => 200 [X-RateLimit-requests-Remaining] => 189 [Content-Length] => 32 [Connection] => keep-alive ) )
How to fix it .... Pls help my thank so much
The only reason one would want to set this option is when one's server is unable to check that certificates are signed by trusted authorities. This is uncommon, it happens only when the CA is not known in curl's default repository.
Since it means never checking certificates, setting this option to false exposes your users to man in the middle attacks or forged certificates.
Shashi Ranjan at Mashape support suggested I request your help and said he cc'd you on the issue already.
I keep getting this error when I do a get, and I'm getting no response with my post:
Missing Mashape application key. Go to http:\/\/docs.mashape.com\/api-keys to learn how to get your API application key.
I've put in my application key, I got it, put it in, should be good.
I am using the pdf2jpg api.
I'm trying to convert the file:
http://patersonconnect.com/_img/text.pdf (you can see it's there).
I'm running this script from the same folder. You can run it yourself:
http://patersonconnect.com/_img/x1.php
here's what's in it:
<?php
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
require_once 'src/Unirest.php';
echo '<br>start: ';
// These code snippets use an open-source library. http://unirest.io/php
$response = Unirest\Request::post("https://pdf2jpg-pdf2jpg.p.mashape.com/convert_pdf_to_jpg.php",
array(
"X-Mashape-Key" => "I use my API key but don't want to post it here"
),
array(
"pdf" => Unirest\file::add("text.pdf"),
"resolution" => 300
)
);
echo json_encode($response);
?>
I'm not getting any errors, just nothing.
I also have a second script which runs the "get" here. I can't put in the necessary response key's from the first script as they are not appearing, but I still shouldn't be getting an issue with the API key, right?
<?php
echo 'response:<br>';
require_once 'src/Unirest.php';
// These code snippets use an open-source library. http://unirest.io/php
$response = Unirest\Request::get("https://pdf2jpg-pdf2jpg.p.mashape.com/convert_pdf_to_jpg.php?id=8084&key=8f1c364d1be4e0a951e67e652cc25325e0dbdff7",
array(
"X-Mashape-Key" => "I use my API key but don't want to post it here",
"Accept" => "application/json"
)
);
var_dump($response);
?>
You can run this script for yourself here:http://patersonconnect.com/_img/x2.php
Why would be getting this error? It shouldn't be an SSL thing, right?
Please help.
Thank you.
file: src/Unirest/Request.php
line: 116
return array_merge(self::$curlOpts, $opts);
Change it to:
return self::$curlOpts = array_merge(self::$curlOpts, $opts);
I'd like to load big data and my internet connention is slow, how to add an additional time or change the timeout to maximize excecution time?
Thanks in advance.
Hi folks,
I got a lot of time the following error message from PHP:
PHP Notice: Undefined offset: 1 in Unirest/Unirest.php on line 239
Please take a look at this line.
Thanks!
Kind regards,
Melroy van den Berg
I would really like to add asynchronous request support to Unirest-PHP, so that it can match the feature set of the other Unirest libraries (http://unirest.io).
PHP doesn't natively support threads, and it doesn't seem to be a standard practice for achieving this. I would like to encourage a discussion to share some ideas for a possible async implementation.
Right now there doesn't seem to be an option to decode json responses as arrays all the time. There should be an option for putting settings on the JSON decode.
Hi there, trying to use this with the Mashape API, and get this lovely exception when trying to make a request to an API endpoint:
Fatal error: Uncaught exception 'Exception' with message 'SSL certificate problem: self signed certificate in certificate chain' in C:*_\unirest\lib\Unirest\Unirest.php:166 Stack trace: #0 C:*_\unirest\lib\Unirest\Unirest.php(47): Unirest::request('GET', 'https://yoda.p....', NULL, Array, NULL, NULL) #1 C:*_\yoda.php(9): Unirest::get('https://yoda.p....', Array, NULL) #2 {main} thrown in C:*_**\unirest\lib\Unirest\Unirest.php on line 166
I could not use the library when it is not in ./lib
Please see my StackOverflow question:
http://stackoverflow.com/questions/16267405/using-unirest-php-lib-that-has-a-namespace
Thank you.
Hey, I'm trying to use unirest first i tried manual installation but it give error like this so i tried composer still same error
Fatal error: Uncaught exception 'Exception' with message 'Problem (2) in the Chunked-Encoded data' in C:\wamp\www\lol\lib\Unirest\Unirest.php on line 103
( ! ) Exception: Problem (2) in the Chunked-Encoded data in C:\wamp\www\lol\lib\Unirest\Unirest.php on line 103
Call Stack
1 0.0002 249632 {main}( ) ..\index.php:0
2 0.0017 371168 Unirest::get( ) ..\index.php:9
3 0.0017 371344 Unirest::request( ) ..\Unirest.php:16
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.