Giter VIP home page Giter VIP logo

unirest-php's Introduction

Unirest for PHP Build Status version

Downloads Code Climate Coverage Status Dependencies Gitter License

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.

Features

  • Utility methods to call GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH requests
  • Supports form parameters, file uploads and custom body entities
  • Supports gzip
  • Supports Basic, Digest, Negotiate, NTLM Authentication natively
  • Customizable timeout
  • Customizable default headers for every request (DRY)
  • Automatic JSON parsing into a native object for JSON responses

Requirements

Installation

Using Composer

To install unirest-php with Composer, just add the following to your composer.json file:

{
    "require-dev": {
        "mashape/unirest-php": "3.*"
    }
}

or by running the following command:

composer require mashape/unirest-php

This will get you the latest version of the reporter and install it. If you do want the master, untagged, version you may use the command below:

composer require mashape/php-test-reporter dev-master

Composer installs autoloader at ./vendor/autoloader.php. to include the library in your script, add:

require_once 'vendor/autoload.php';

If you use Symfony2, autoloader has to be detected automatically.

You can see this library on Packagist.

Install from source

Download the PHP library from Github, then include Unirest.php in your script:

git clone [email protected]:Mashape/unirest-php.git 
require_once '/path/to/unirest-php/src/Unirest.php';

Usage

Creating a Request

So you're probably wondering how using Unirest makes creating requests in PHP easier, let's look at a working example:

$headers = array('Accept' => 'application/json');
$query = array('foo' => 'hello', 'bar' => 'world');

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $query);

$response->code;        // HTTP Status code
$response->headers;     // Headers
$response->body;        // Parsed body
$response->raw_body;    // Unparsed body

JSON Requests (application/json)

A JSON Request can be constructed using the Unirest\Request\Body::Json helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::json($data);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Notes:

  • Content-Type headers will be automatically set to application/json
  • the data variable will be processed through json_encode with default values for arguments.
  • an error will be thrown if the JSON Extension is not available.

Form Requests (application/x-www-form-urlencoded)

A typical Form Request can be constructed using the Unirest\Request\Body::Form helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::form($data);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Notes:

  • Content-Type headers will be automatically set to application/x-www-form-urlencoded
  • the final data array will be processed through http_build_query with default values for arguments.

Multipart Requests (multipart/form-data)

A Multipart Request can be constructed using the Unirest\Request\Body::Multipart helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::multipart($data);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Notes:

  • Content-Type headers will be automatically set to multipart/form-data.
  • an auto-generated --boundary will be set.

Multipart File Upload

simply add an array of files as the second argument to to the Multipart helper:

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');
$files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg');

$body = Unirest\Request\Body::multipart($data, $files);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

If you wish to further customize the properties of files uploaded you can do so with the Unirest\Request\Body::File helper:

$headers = array('Accept' => 'application/json');
$body = array(
    'name' => 'ahmad', 
    'company' => 'mashape'
    'bio' => Unirest\Request\Body::file('/path/to/bio.txt', 'text/plain'),
    'avatar' => Unirest\Request\Body::file('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg')
);

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Note: we did not use the Unirest\Request\Body::multipart helper in this example, it is not needed when manually adding files.

Custom Body

Sending a custom body such rather than using the Unirest\Request\Body helpers is also possible, for example, using a serialize body string with a custom Content-Type:

$headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized');
$body = serialize((array('foo' => 'hello', 'bar' => 'world'));

$response = Unirest\Request::post('http://mockbin.com/request', $headers, $body);

Authentication

First, if you are using Mashape:

// Mashape auth
Unirest\Request::setMashapeKey('<mashape_key>');

Otherwise, passing a username, password (optional), defaults to Basic Authentication:

// basic auth
Unirest\Request::auth('username', 'password');

The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.

If more than one bit is set, Unirest (at PHP's libcurl level) will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. For some methods, this will induce an extra network round-trip.

Supported Methods

Method Description
CURLAUTH_BASIC HTTP Basic authentication. This is the default choice
CURLAUTH_DIGEST HTTP Digest authentication. as defined in RFC 2617
CURLAUTH_DIGEST_IE HTTP Digest authentication with an IE flavor. The IE flavor is simply that libcurl will use a special "quirk" that IE is known to have used before version 7 and that some servers require the client to use.
CURLAUTH_NEGOTIATE HTTP Negotiate (SPNEGO) authentication. as defined in RFC 4559
CURLAUTH_NTLM HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft.
CURLAUTH_NTLM_WB NTLM delegating to winbind helper. Authentication is performed by a separate binary application. see libcurl docs for more info
CURLAUTH_ANY This is a convenience macro that sets all bits and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.
CURLAUTH_ANYSAFE This is a convenience macro that sets all bits except Basic and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.
CURLAUTH_ONLY This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe for un-restricted auth and if not, only that single auth algorithm is acceptable.
// custom auth method
Unirest\Request::proxyAuth('username', 'password', CURLAUTH_DIGEST);

Previous versions of Unirest support Basic Authentication by providing the username and password arguments:

$response = Unirest\Request::get('http://mockbin.com/request', null, null, 'username', 'password');

This has been deprecated, and will be completely removed in v.3.0.0 please use the Unirest\Request::auth() method instead

Cookies

Set a cookie string to specify the contents of a cookie header. Multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")

Unirest\Request::cookie($cookie)

Set a cookie file path for enabling cookie reading and storing cookies across multiple sequence of requests.

Unirest\Request::cookieFile($cookieFile)

$cookieFile must be a correct path with write permission.

Request Object

Unirest\Request::get($url, $headers = array(), $parameters = null)
Unirest\Request::post($url, $headers = array(), $body = null)
Unirest\Request::put($url, $headers = array(), $body = null)
Unirest\Request::patch($url, $headers = array(), $body = null)
Unirest\Request::delete($url, $headers = array(), $body = null)
  • url - Endpoint, address, or uri to be acted upon and requested information from.
  • headers - Request Headers as associative array or object
  • body - Request Body as associative array or object

You can send a request with any standard or custom HTTP Method:

Unirest\Request::send(Unirest\Method::LINK, $url, $headers = array(), $body);

Unirest\Request::send('CHECKOUT', $url, $headers = array(), $body);

Response Object

Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.

  • code - HTTP Response Status Code (Example 200)
  • headers - HTTP Response Headers
  • body - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
  • raw_body - Un-parsed response body

Advanced Configuration

You can set some advanced configuration to tune Unirest-PHP:

Custom JSON Decode Flags

Unirest uses PHP's JSON Extension for automatically decoding JSON responses. sometime you may want to return associative arrays, limit the depth of recursion, or use any of the customization flags.

To do so, simply set the desired options using the jsonOpts request method:

Unirest\Request::jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);

Timeout

You can set a custom timeout value (in seconds):

Unirest\Request::timeout(5); // 5s timeout

Proxy

Set the proxy to use for the upcoming request.

you can also set the proxy type to be one of CURLPROXY_HTTP, CURLPROXY_HTTP_1_0, CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A, and CURLPROXY_SOCKS5_HOSTNAME.

check the cURL docs for more info.

// quick setup with default port: 1080
Unirest\Request::proxy('10.10.10.1');

// custom port and proxy type
Unirest\Request::proxy('10.10.10.1', 8080, CURLPROXY_HTTP);

// enable tunneling
Unirest\Request::proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);
Proxy Authenticaton

Passing a username, password (optional), defaults to Basic Authentication:

// basic auth
Unirest\Request::proxyAuth('username', 'password');

The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.

If more than one bit is set, Unirest (at PHP's libcurl level) will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. For some methods, this will induce an extra network round-trip.

See Authentication for more details on methods supported.

// basic auth
Unirest\Request::proxyAuth('username', 'password', CURLAUTH_DIGEST);

Default Request Headers

You can set default headers that will be sent on every request:

Unirest\Request::defaultHeader('Header1', 'Value1');
Unirest\Request::defaultHeader('Header2', 'Value2');

You can set default headers in bulk by passing an array:

Unirest\Request::defaultHeaders(array(
    'Header1' => 'Value1',
    'Header2' => 'Value2'
));

You can clear the default headers anytime with:

Unirest\Request::clearDefaultHeaders();

Default cURL Options

You can set default cURL options that will be sent on every request:

Unirest\Request::curlOpt(CURLOPT_COOKIE, 'foo=bar');

You can set options bulk by passing an array:

Unirest\Request::curlOpts(array(
    CURLOPT_COOKIE => 'foo=bar'
));

You can clear the default options anytime with:

Unirest\Request::clearCurlOpts();

SSL validation

You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint:

Unirest\Request::verifyPeer(false); // Disables SSL cert validation

By default is true.

Utility Methods

// alias for `curl_getinfo`
Unirest\Request::getInfo()

// returns internal cURL handle
Unirest\Request::getCurlHandle()

Made with ♥ from the Mashape team

unirest-php's People

Contributors

andreyvital avatar cristianp6 avatar esseguin avatar frankdee avatar furgas avatar hutchic avatar irfanevrens avatar jasir avatar jskrivseth avatar mircobabini avatar motdotla avatar nijikokun avatar nikkobautista avatar qpleple avatar rusinovig avatar samsullivan avatar shatsar avatar sonicaghi avatar subnetmarco avatar thenetexperts avatar thibaultcha avatar vlakarados avatar xcopy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unirest-php's Issues

Always get 403

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.

Parameters which contain equal signs as part of the value are not handled correctly

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.

how to use API mashape with PHP unirest

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

SSL certificate problem

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

Support basic auth and timeout

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);

Arrays in GET string are corrupted

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.

setting CURLOPT_SSL_VERIFYPEER as false is a potential security risk

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.

Asynchronous requests

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.

'Array to string conversion' notice from line 134 of Unirest.php with nested arrays in $body

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...

HttpResponse->$headers only returns one header

$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.

Unirest in Wordpress plugin development

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?

"Missing Mashape application key." even with my API key

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.

url with port specified does not work

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.

Release tagging

Please tag your composer release.

This is required for it to be used in redistributable libraries.

OAuth 1.0a support

I'd love to have the OAuth 1.0a support in this PHP version of Unirest (without using the PECL OAuth extension).

Dots in parameters are converted to underscores causing issues

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"}}

Relative paths cause 'url_parsed' error

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

403

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
)
);

Operation Timeout error when using Unirest::timeout(5)

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.

Maximum execution time of 30 sec, line 100

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?

Unirest not being found by Laravel

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

Errors from time to time

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

Fatal error Unirest\Unirest.php on line 103

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

Time Memory Function Location

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

Unirest doesn't automatically store cookies to send them on subsequent requests

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?

PHP 5.3.x support

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

400 Bad request issue

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?

Parse error: syntax error, unexpected T_STRING

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

Class collision without namespaces.

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?

Release Versioning

Please create versioned releases so that we can properly depend on specific versions using composer.

Raw php Data with delete/put request

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?

PHP Error: Undefined offset

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

Setting "user-agent" or "expect" header causes error

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

curl_setopt_array()

curl_setopt_array(): CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set...

[ROOT/vendors/unirest/src/Unirest/Request.php, line 423]

Fatal error: Class 'Unirest\File' not found

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);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.