Giter Site home page Giter Site logo

curl's Introduction

ixudra/curl

Latest Version on Packagist license Total Downloads

Ixudra Curl

Custom PHP cURL library for the Laravel framework - developed by Ixudra.

The package provides an easy interface for sending cURL requests from your PHP web application. The package provides an intuitive, fluent interface similar the Laravel query builder to easily configure the request. Additionally, There are several utility methods that allow you to easily add certain options to the request. This makes it easier to create and use cURL requests and also makes your code more comprehensible.

The provided functionality is completely framework-independent but also contains a Laravel service provider for easy integration into your Laravel project.

Note before posting an issue: When posting an issue for the package, always be sure to provide as much information regarding the request as possible. This includes the example cURL request you are trying to transfer into the package syntax, your actual package syntax (the full request) and (if possible) an example URL I can use to test the request myself if need be.

Installation

Pull this package in through Composer.

    {
        "require": {
            "ixudra/curl": "6.*"
        }
    }

or run in terminal: composer require ixudra/curl

Laravel 5.5+ Integration

Laravel's package discovery will take care of integration for you.

Laravel 5.* Integration

Add the service provider to your config/app.php file:

    'providers'     => array(

        //...
        Ixudra\Curl\CurlServiceProvider::class,

    ),

Add the facade to your config/app.php file:

    'aliases'       => array(

        //...
        'Curl'          => Ixudra\Curl\Facades\Curl::class,

    ),

Laravel 4.* Integration

Add the service provider to your app/config/app.php file:

    'providers'     => array(

        //...
        'Ixudra\Curl\CurlServiceProvider',

    ),

Add the facade to your app/config/app.php file:

    'facades'       => array(

        //...
        'Curl'          => 'Ixudra\Curl\Facades\Curl',

    ),

Lumen 5.* integration

In your bootstrap/app.php, make sure you've un-commented the following line (around line 26):

$app->withFacades();

Then, register your class alias:

class_alias('Ixudra\Curl\Facades\Curl', 'Curl');

Finally, you have to register your ServiceProvider (around line 70-80):

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register('App\Providers\AppServiceProvider');

// Package service providers
$app->register(Ixudra\Curl\CurlServiceProvider::class);

Integration without Laravel

Create a new instance of the CurlService where you would like to use the package:

    $curlService = new \Ixudra\Curl\CurlService();

Usage

Laravel usage

The package provides an easy interface for sending cURL requests from your application. The package provides a fluent interface similar the Laravel query builder to easily configure the request. There are several utility methods that allow you to easily add certain options to the request. If no utility method applies, you can also use the general withOption method.

Sending GET requests

In order to send a GET request, you need to use the get() method that is provided by the package:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar
    $response = Curl::to('http://www.foo.com/bar')
        ->get();

    // Send a GET request to: http://www.foo.com/bar?foz=baz
    $response = Curl::to('http://www.foo.com/bar')
        ->withData( array( 'foz' => 'baz' ) )
        ->get();

    // Send a GET request to: http://www.foo.com/bar?foz=baz using JSON
    $response = Curl::to('http://www.foo.com/bar')
        ->withData( array( 'foz' => 'baz' ) )
        ->asJson()
        ->get();

Sending POST requests

Post requests work similar to GET requests, but use the post() method instead:

    use Ixudra\Curl\Facades\Curl;

    // Send a POST request to: http://www.foo.com/bar
    $response = Curl::to('http://www.foo.com/bar')
        ->post();
    
    // Send a POST request to: http://www.foo.com/bar
    $response = Curl::to('http://www.foo.com/bar')
        ->withData( array( 'foz' => 'baz' ) )
        ->post();
    
    // Send a POST request to: http://www.foo.com/bar with arguments 'foz' = 'baz' using JSON
    $response = Curl::to('http://www.foo.com/bar')
        ->withData( array( 'foz' => 'baz' ) )
        ->asJson()
        ->post();
    
    // Send a POST request to: http://www.foo.com/bar with arguments 'foz' = 'baz' using JSON and return as associative array
    $response = Curl::to('http://www.foo.com/bar')
        ->withData( array( 'foz' => 'baz' ) )
        ->asJson( true )
        ->post();

Sending PUT requests

Put requests work similar to POST requests, but use the put() method instead:

    use Ixudra\Curl\Facades\Curl;

    // Send a PUT request to: http://www.foo.com/bar/1 with arguments 'foz' = 'baz' using JSON
    $response = Curl::to('http://www.foo.com/bar/1')
       ->withData( array( 'foz' => 'baz' ) )
       ->asJson()
       ->put();

Sending PATCH requests

Patch requests work similar to POST requests, but use the patch() method instead:

    use Ixudra\Curl\Facades\Curl;

    // Send a PATCH request to: http://www.foo.com/bar/1 with arguments 'foz' = 'baz' using JSON
    $response = Curl::to('http://www.foo.com/bar/1')
        ->withData( array( 'foz' => 'baz' ) )
        ->asJson()
        ->patch();

Sending DELETE requests

Delete requests work similar to GET requests, but use the delete() method instead:

    use Ixudra\Curl\Facades\Curl;

    // Send a DELETE request to: http://www.foo.com/bar/1 using JSON
    $response = Curl::to('http://www.foo.com/bar/1')
        ->asJson()
        ->delete();

Sending HEAD requests

HEAD requests work similar to GET requests, but use the head() method instead:

    use Ixudra\Curl\Facades\Curl;

    // Send a HEAD request to: http://www.foo.com/bar/1
    $response = Curl::to('http://www.foo.com/bar/1')
        ->head();
    
    // Send a HEAD request to: http://www.foo.com/bar/1?foz=baz
    $response = Curl::to('http://www.foo.com/bar/1')
        ->withData( array( 'foz' => 'baz' ) )
        ->head();

Sending custom headers

Sending custom headers is easy with the withHeader() method. Multiple calls can be chained together to add multiple headers to the request:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar with 2 custom headers
    $response = Curl::to('http://foo.com/bar')
        ->withHeader('MyFirstHeader: 123')
        ->withHeader('MySecondHeader: 456')
        ->get();

Alternatively, you can use the withHeaders() to combine multiple headers into one method call:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar with 2 custom headers
    $response = Curl::to('http://foo.com/bar')
        ->withHeaders( array( 'MyFirstHeader: 123', 'MySecondHeader: 456' ) )
        ->get();

You can also use key-value when using the withHeaders() method:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar with 2 custom headers
    $response = Curl::to('http://foo.com/bar')
        ->withHeaders( array( 'MyFirstHeader' => '123', 'MySecondHeader' => '456' ) )
        ->get();

For (bearer) authorization headers, you can also use specific utility methods:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar with "Authorization: 123" header
    $response = Curl::to('http://foo.com/bar')
        ->withAuthorization('123')
        ->get();

    // Send a GET request to: http://www.foo.com/bar with "Authorization: Bearer 123" header
    $response = Curl::to('http://foo.com/bar')
        ->withBearer('123')
        ->get();

Note that headers will override each other if you add the same header more than once.

Specifying the content type

Sending custom headers is easy with the withContentType() method. Multiple calls can be chained together to add multiple headers to the request:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar with a json content type
    $response = Curl::to('http://foo.com/bar')
        ->withContentType('application/json')
        ->get();

Using proxies

If you need to send your requests via a proxy, you can use the 'withProxy()' method. The method takes five parameters:

  • proxy url (required)
  • port (optional)
  • type of proxy scheme (optional, e.g. http://, https://, ...)
  • username (optional)
  • password (optional)

Optional parameters will be ignored if not filled in.

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to: http://www.foo.com/bar with a json content type
    $response = Curl::to('http://foo.com/bar')
        ->withProxy('192.168.1.1', 80, 'http://', 'Foo', 'Bar')
        ->get();

Sending files via Curl

For sending files via a POST request, you can use the withFile method to correctly format a request before sending:

    use Ixudra\Curl\Facades\Curl;

    $response = Curl::to('http://foo.com/bar')
        ->withData( array( 'Foo' => 'Bar' ) )
        ->withFile( 'image_1', '/path/to/dir/image1.png', 'image/png', 'imageName1.png' )
        ->withFile( 'image_2', '/path/to/dir/image2.png', 'image/png', 'imageName2.png' )
        ->post();

You can add as many files to the request as you want. A couple of things to keep in mind:

  • When submitting files, the asJson() method and asJsonRequest() method cannot be used. If you do, the files will not be transferred correctly
  • The files are added to the data that was provided in the withData() method using the first parameter of the withFile() method. If this key already exists, it will be overridden.

Downloading files

For downloading a file, you can use the download() method:

    use Ixudra\Curl\Facades\Curl;

    // Download an image from: file http://www.foo.com/bar.png
    $response = Curl::to('http://foo.com/bar.png')
        ->withContentType('image/png')
        ->download('/path/to/dir/image.png');

Using response objects

By default, the package will only return the content of the request. In some cases, it might also be useful to know additional request information, such as the HTTP status code and error messages should they occur. In this case, you can use the returnResponseObject() method, which will return an stdClass that contains additional information as well as the response content:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to http://www.foo.com/bar and return a response object with additional information
    $response = Curl::to('http://www.foo.com/bar')
        ->returnResponseObject()
        ->get();
            
    $content = $response->content;

The response object will look like this:

{
   "content": "Message content here",
   "status": 200,
   "contentType": "content-type response header (ex: application/json)",
   "error": "Error message goes here (Only added if an error occurs)"
}

Response headers

In some cases it might be relevant to return the response headers back to the user. This can easily be done using the withResponseHeaders() method.

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to http://www.foo.com/bar and return a response object with additional information including response headers
    $response = Curl::to('http://www.foo.com/bar')
        ->withResponseHeaders()
        ->returnResponseObject()
        ->get();
            
    $content = $response->content;
    $headers = $response->headers;

The response object will look like this:

{
    "content": "Message content here",
    "status": 200,
    "contentType": "content-type response header (ex: application/json)",
    "error": "Error message goes here (Only added if an error occurs)",
    "headers": {
        "header-type-1": "header-content-1",
        "header-type-2": "header-content-2"
    }
}

It is important to note that the withResponseHeaders() method must be used in conjunction with the returnResponseObject() method in order to see the returned headers

Debugging requests

In case a request fails, it might be useful to get debug the request. In this case, you can use the enableDebug() method. This method uses one parameter, which is the name of the file in which the debug information is to be stored:

    use Ixudra\Curl\Facades\Curl;

    // Send a GET request to http://www.foo.com/bar and log debug information in /path/to/dir/logFile.txt
    $response = Curl::to('http://www.foo.com/bar')
        ->enableDebug('/path/to/dir/logFile.txt')
        ->get();

Using cURL options

You can add various cURL options to the request using of several utility methods such as withHeader() for adding a header to the request, or use the general withOption() method if no utility method applies. The package will automatically prepend the options with the CURLOPT_ prefix. It is worth noting that the package does not perform any validation on the cURL options. Additional information about available cURL options can be found here.

Method Default value Description
withTimeout() 30 seconds Set the timeout of the request (integer or float)
withConnectTimeout() 30 seconds Set the connect timeout of the request (integer or float)
allowRedirect() false Allow the request to be redirected internally
asJsonRequest() false Submit the request data as JSON
asJsonResponse() false Decode the response data from JSON
asJson() false Utility method to set both asJsonRequest() and asJsonResponse() at the same time
withHeader() string Add an HTTP header to the request
withHeaders() array Add multiple HTTP headers to the request
withContentType() none Set the content type of the response
withFile() none Add a file to the form data to be sent
containsFile() false Should be used to submit files through forms
withData() array Add an array of data to sent with the request (GET or POST)
setCookieFile() none Set a file to read cookies from
setCookieJar() none Set a file to store cookies in
withOption() none Generic method to add any cURL option to the request

For specific information regarding parameters and return types, I encourage you to take a look at ixudra\curl\src\Ixudra\Curl\Builder.php. This class has extensive doc blocks that contain all the necessary information for each specific method.

Usage without Laravel

Usage without Laravel is identical to usage described previously. The only difference is that you will not be able to use the facades to access the CurlService.

    $curlService = new \Ixudra\Curl\CurlService();

    // Send a GET request to: http://www.foo.com/bar
    $response = $curlService->to('http://www.foo.com/bar')
        ->get();

    // Send a POST request to: http://www.foo.com/bar
    $response = $curlService->to('http://www.foo.com/bar')
        ->post();

    // Send a PUT request to: http://www.foo.com/bar
    $response = $curlService->to('http://www.foo.com/bar')
        ->put();

    // Send a DELETE request to: http://www.foo.com/bar
    $response = $curlService->to('http://www.foo.com/bar')
        ->delete();

    // Send a HEAD request to: http://www.foo.com/bar
    $response = $curlService->to('http://www.foo.com/bar')
        ->head();

Planning

  • Add additional utility methods for other cURL options
  • Add contract to allow different HTTP providers such as Guzzle

Support

Help me further develop and maintain this package by supporting me via Patreon!!

License

This package is open-sourced software licensed under the MIT license

Contact

For package questions, bug, suggestions and/or feature requests, please use the Github issue system and/or submit a pull request. When submitting an issue, always provide a detailed explanation of your problem, any response or feedback your get, log messages that might be relevant as well as a source code example that demonstrates the problem. If not, I will most likely not be able to help you with your problem. Please review the contribution guidelines before submitting your issue or pull request.

For any other questions, feel free to use the credentials listed below:

Jan Oris (developer)

curl's People

Contributors

760e7dab2836853c63805033e avatar bbiao avatar dalholm avatar elimentz avatar finagin avatar gazben avatar isaackearl avatar jakebathman avatar jantho1990 avatar jaskiratsingh91 avatar kevinvdburgt avatar komalshahgh avatar luizguilhermefr avatar matheus1lva avatar minhphuc429 avatar obeone avatar remicollin avatar robjuz avatar roman4e avatar shirakun avatar thedigit avatar wwwroth 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

curl's Issues

Curl request Error: Undefined index: http_code

(1/1) ErrorExceptionUndefined index: http_code

in Builder.php (line 487)

at HandleExceptions->handleError(8, 'Undefined index: http_code', '/var/www/vendor/ixudra/curl/src/Builder.php', 487, array('content' =>array('status' => 'success', 'shortenedUrl' => 'http://u2s.io/XXuu'), 'responseData' => array(), 'object' => object(stdClass)))in Builder.php (line 487)

at Builder->returnResponse(array('status' => 'success', 'shortenedUrl' => 'http://u2s.io/XXuu'), array())in Builder.php (line 475)

In local , works , but in deploy dont work .. any ideas?

It's a pity that I can't work successfully with your plugin

KERNEL

Linux XPS 4.8.0-30-generic #32-Ubuntu SMP Fri Dec 2 03:43:27 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

LARAVEL

I'am using Laravel 5.3,and I just follow your README to complete the function.However,it went wrong as I tried to display it on my browser。

ERROR MESSAGE

Class 'App\Http\Controllers\Curl' not found

HELP

I'am sure i have done what i should do .I have used composer to install your plugin and have added the alias and provider in my app.php file.However,it has the error message above.Can you give me a solusion?

fopen(ical/1.ics): failed to open stream: No such file or directory

Hi,

I am trying to loop throught a ical field and for each one save it in ical folder with a business id. Of course the file doesn't exist, I want the curl to download the file and save it as a specified name.

Here's the code:

public function handle()
{
    $urls = Business::pluck('ical');
    $ids = Business::pluck('id');
    foreach ($urls as $url) {
        foreach ($ids as $id) {
        $response = Curl::to($url)
            ->download('ical/'.$id.'.ics');
    }   
}
}

Example $url

https://calendar.google.com/calendar/ical/hackoldham%40gmail.com/public/basic.ics

Example $id

1

Response data!

How get response data? Curl::url return the response data?

Ways to make an authentication?

Hello everyone, I'm trying to "get" the data from the (Rest)api that I am using for my project, but I put the credentials to make the authentication and he gives me 'null' value, needless to say, it isn't make the authentication. I put the same values on postman and it can get the data.
What am I doing wrong? here is a sample of my code.
Thanks in advance

$curl = Curl::to($url)
            ->withData([
            'Content-Type' => 'application/json',   
            'EMAIL' => 'email',
            'KEY' => 'key'])
->asJson()
->get();

400 error on DELETE request

I'm running a Laravel project within a Vagrant VM and am attempting to use delete() at an API endpoint I've created. I kept getting false, so I used enableDebug() and uncovered I was getting a 400 error. GET, POST, PUT, PATCH work well. Here's my log.

* Hostname was found in DNS cache
* Hostname in DNS cache was stale, zapped
*   Trying 127.0.53.53...
* Connected to ***-api.***.dev (127.0.53.53) port 80 (#74)
> DELETE /accounts/59/payment-methods/delete/card_**** HTTP/1.1
Host: ***-api.***.dev
Accept: */*

* The requested URL returned error: 400 Bad Request
* Closing connection 74

I removed where I was doing it with your lib and tried the request with PHP's standard CURL lib and it worked fine.

//$response = Curl::to($endpoint)->delete();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);

return json_encode($result);

I'll be looking into the service and trying to see if I can patch it. If I can, I'll submit a PR.

Laravel 5.1 - Class 'Ixudra\Curl\CurlServiceProvider' not found

I don't know if it's only me, but I have Laravel 5.1

Added "ixudra/curl": "^5.1" on composer.js

When I add "Ixudra\Curl\CurlServiceProvider::class" on config/app.php and execute "composer install" the installation stops with the error "Class 'Ixudra\Curl\CurlServiceProvider' not found"

Add allowRedirect() utility method

        $response = \Curl::to($url)
            ->withData( $postData )
            ->withOption('FOLLOWLOCATION', true)
            ->post();

would become

        $response = \Curl::to($url)
            ->withData( $postData )
            ->allowRedirect()
            ->post();

How to treat HTTP status codes?

Suppose I have something like:

$response = Curl::to('localhost/foo/bar')
            ->withData($data)
            ->asJson()
            ->put();

How do I process the incoming status code (200, 400, etc.)?

Add file upload feature

See kaluax@781195b#commitcomment-17537474 for details

Code sample:

function uploadFile($serverPath, $filePath)  {
    $url = 'https://...';

    $cfile = curl_file_create($filePath);

    $data = [
        'action' => 'upload',
        'href' => $serverPath,
        'userfile' => $cfile
    ];

    $curl = Curl::to($url);

    $curl = $curl->withOption('HTTPAUTH', CURLAUTH_BASIC);
    $curl = $curl->withOption('USERPWD', "user:pass");

    $curl = $curl->withData($data);

    $response = $curl->post();

    return $response;
}

withData on GET request uses &

Hi there,

In Builder.php the appendDataToURL method uses http_build_query but doesn't specify an arg_seperator command as it does in the forgeOptions method. This results in GET params being built as GET /some/endpoint/?arg1=someValue&arg2=anotherValue which causes problems for some web services as they expect just a plain '&'.

Is this by design? If not could the code be patched to specify the '&' as it does in the forgeOptions method?

Thanks

Return Null

Hello,
Thanks for being awesome library.

$response = Curl::to($this->base_url."lokasi")
        ->withHeader('Authorization: Bearer '.$this->access_token)
        ->withHeader('Accept: application/json')
        ->get();

That's my code, In local working properly. But when upload to server always return null that's code.
When I check on postman working properly with URL, and acces token on server. Do you have any solutions or suggestion for the best solutions?

Thank you very much

Feature Request: Xdebug param support

Feature reuest.

I found my self extending the libray in my app just to add XDEBUG_SESSION_START param to the URL. I'd be nice to be added automatically by a env param or a second arg to the "to" method.

What I'm doing is to use the APP_DEBUG default env param to know when to add the XDEBUG param and if I need a value for that param then I use a seconds custom env variable to do so.

How to display http response code

I've tried adding curl options like
->withOption('FAILONERROR', true)
->withOption('VERBOSE', true)

so I might get the error response code. But it always return null :(.

Curl::to()->get(); How to wait for response

Hi
I am using your package to send api requests and it seems like it does not "wait" for the repsonse according to the site I am sending the request to .... I am using up all their threads ?????

I need it to wait ....

$response = Curl::to($url.$cmd.'?'.$fields_string) ->get();

Can you please point me in the right direction

can not upload image with curl

im using this
$response = Curl::to($to)
->withData( $data)
->withContentType('multipart/form-data')
->containsFile()
->post();

and when im trying to return this from method of api controller
$request->paymentProof;

its returning a string
'C:\wamp64\tmp\php510E.tmp'

format of data following URL

Hi ... I am struggling to get the body of my get request formatted correctly .... if I send the string maually to the URL it works 100% .....

https://url?
followed by
api_key=xxxxxxxxxxxxxxxxxxxx&entitynr=1&ilikedict=%7B%22debtor_surname%22%3A%22%25test%25%22%7D&operator=&orderby=&orderdirection=&limit=

Here is my array

$arr = [ 'api_key' => 'xxxxxxxxxxxxxxxxxxxx', 'entitynr' =>'1', 'ilikedict' => ['debtor_surname' => '%test%'], 'operator' => '', 'orderby' => '', 'orderdirection' => '', 'limit' => '', ];

Here is the command ...

$response = Curl::to($url) ->withData( $arr ) ->asJson() ->get();

Curl Patch method

How about the curl patch? How would you do it using this? I have this web api that has PATCH. Tried using post and put to suffice the api but it failed. Please help

Unable to access to content

Found a problem, if the server returns the state of the data is 200 so normal access to content, but if not 200, such as the 500,400 status code will not be able to normal access to content

Conditional options

How to add conditional options?
Use case: When project is in local environment, add proxy headers, otherwise not.

Snippet 1 - not working

$response = Curl::to('https://jsonplaceholder.typicode.com/posts');
if (\App::environment('local')) {
  $response->withOption('PROXY', '192.168.10.5')
    ->withOption('PROXYPORT', '8080');
}
$response->get();

Snippet 2 - working

$response = Curl::to('https://jsonplaceholder.typicode.com/posts')
      ->withOption('PROXY', '192.168.10.5')
      ->withOption('PROXYPORT', '8080')
      ->get();

after update asJson() doesn't work.

ErrorException in Builder.php line 265:
json_decode() expects parameter 1 to be string, object given

at HandleExceptions->handleError('2', 'json_decode() expects parameter 1 to be string, object given', '.../vendor/ixudra/curl/src/Ixudra/Curl/Builder.php', '265', array('options' => array('1', '1', '0', '0', '30', '', 'https://graph.facebook.com/10208651500075198/picture?redirect=false&type=large', '0', array('Content-Type: application/json')), 'response' => object(stdClass)))
at json_decode(object(stdClass), false) in Builder.php line 265

      $picture_json = \Curl::to("https://graph.facebook.com/{id}/picture")
            ->withData( array( 'redirect' => 'false' ) )
            ->asJson()
            ->get();

Response Data asJson returns null

i'm Using Laravel 5.2 with ixudra/curl
problem is that when i do

              $api_url="http://www.freecodecamp.com/news/hot";
               $response = Curl::to($api_url)
              ->asJson()
               ->get() ;
                dd($response);//shows null   

But when i do
$api_url="http://www.freecodecamp.com/news/hot";
$response = Curl::to($api_url)
->get() ;
dd($response);
the above shows some html code that still is not what i need what i really need is the information that shows when u acces http://www.freecodecamp.com/news/hot directly from browser how do i get it what am i doing wrong?

Lumen 5.3 integration

i use it on lumen 5.3 and class Curl always not found, please the solution, thank you.

get http headers ?

$c = \Curl::to($url)
->returnResponseObject()
->withHeader('User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')

->withOption('HEADER',1);

http headers and page content are together :

HTTP/1.1 200 OK\r\n
Cache-Control: no-cache, private\r\n
Content-Type: text/html; charset=UTF-8\r\n
Set-Cookie: XSRF-TOKEN=eyJpdiI6IllLYlY4a3R6clhwNmMySmVTOERuUmc9PSIsInZhbHVlIjoicWxrVGdqbDBWSVpGY1J4NkVzbEU2XC9YaVRqRkJkVjdXKytUeFhaT0Q2V0hRRno4dUk2NWpuNFZUOTRYb ▶
Set-Cookie: laravel_session=eyJpdiI6Ik1zR3crXC9HVmxpV3hOSlg3Sm1PRFh3PT0iLCJ2YWx1ZSI6IkNMUXZxR0dINkV3S3NNNnpjM2pacDVsWW9TTVNreFwveU1NUVwvbDhhUlgySjJsVUtxOEswbEJU ▶
Transfer-Encoding: chunked\r\n
Date: Fri, 17 Nov 2017 04:40:29 GMT\r\n
Accept-Ranges: bytes\r\n
Server: LiteSpeed\r\n
Connection: close\r\n
\r\n
<!DOCTYPE HTML>\r\n
<html xmlns="http://www.w3.org/1999/xhtml" lang="fa" dir="rtl">\r\n
<head>\r\n
...
..
.
.
.
.
.

for ex :

$c->content

and

$c->headers

Class Curl does not exist

Hi I have followed the instruction on how to install Ixudra\Curl, but unfortunately I can't make it work.

if I use this bunch of code as test script

$response = Curl::to('http://www.foo.com/bar') ->get(); return $response;

It returns "Class Curl does not exist"

I have tried adding these at the top, but still it is not working.

use Ixudra\Curl\Facades\Curl;

and

use Ixudra\Curl\;

What am I missing? Also, i'm done running the composer update

Json post does not work

Hi guys,
my project code he is working

$vars =array(
'seedShowing' => true,
'rootShowing' => true,
'parentShowing' => true,
'productShowing' => true,
'metaShowing' => true,
'priceShowing' => true,
'uriShowing' => true,
'tagShowing' => true
);

$requestbody = json_encode($vars);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:8000/new/products/list");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestbody);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = array(
'Accept:application/json',
'Content-Type:application/json',
'Authorization:Bearer '.$token
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$responsebody = curl_exec($ch);

curl_close($ch);


You are code not working on my project, Where do i make mistakes

$vars =array(
'seedShowing' => true,
'rootShowing' => true,
'parentShowing' => true,
'productShowing' => true,
'metaShowing' => true,
'priceShowing' => true,
'uriShowing' => true,
'tagShowing' => true
);

$headers = array(
'Accept:application/json',
'Authorization:Bearer '.$token
);
$product = Curl::to('http://127.0.0.1:8000/new/products/list')
->withData($vars)
->withHeaders($headers)
->withContentType('application/json')
->asJson()
->post();

Multithreading?

Is it also possible to do multithreading and proxies with this library?

Authentication credentials were not provided

i m using laravel 5.4 and following all the instruction in this package , but i did not found any place where i have to enter Authentication credentials.
i m getting this error when hitting the target link by ixudra/curl
"Authentication credentials were not provided"

Laravel 5.4 Support

Seems that only one update needs to be made to support Laravel 5.4:

src/Ixudra/Curl/CurlServiceProvider.php(18)

$this->app['Curl'] = $this->app->share

to

$this->app['Curl'] = $this->app->singleton

Keep getting 400 bad request

Hi, using this pack I have 'translated' this:

$ curl \
 -H 'Authorization: Bearer $TOKEN' \
 -H 'Accept: application/vnd.wit.20160526+json' \
  'https://api.wit.ai/message?q=Bonjour'

to the Pack way like so:

Curl::to('https://api.wit.ai/message')
        ->withData([
                'q' => 'Bonjour',
                'access_token' => 'token',
        ])
        ->asJson()
        ->get();

And it all works fine.
But when I try to 'translate':

$ curl -XPOST 'https://api.wit.ai/converse?v=20160526&session_id=123abc&q=Bonjour' \
      -H "Content-Type: application/json" \
      -H "Accept: application/json" \
      -H 'Authorization: Bearer $TOKEN'

to Curl syntacs like so:

Curl::to('https://api.wit.ai/converse')
        ->withData([
                'v' => '20170114',
                'session_id' => '123abc',
                'q' => 'Bonjour',
        ])
        ->withContentType('application/json')
        ->withHeaders([
                'access_token' => 'token',
            ])
        ->asJson()
        ->post();

I get The requested URL returned error: 400 Bad Request.

Can you please help to represent the above code with this pack.
Thank you.

How to use Curl if url have redirect ?

$inv = Curl::to('https://steamcommunity.com/profiles/76561198015712695/inventory/json/730/2/')
->get();

this code dont wort because redirect help pls

Update curl file upload to use new PHP7 CurlFile feature

PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
See: https://wiki.php.net/rfc/curl-file-upload for details

function getCurlFileValue($filename, $contentType, $postname) 
{
    if (function_exists('curl_file_create')) {
        return curl_file_create($filename, $contentType, $postname);
    }
    // Use the old style if using an older version of PHP
    $value = "@{$filename};filename=" . $postname;
    if ($contentType) {
        $value .= ';type=' . $contentType;
    }
    return $value;
}

Facing error - 400 bad request

Hi,

I have a code to which I have converted according to your way that looks more elegant and easier to understand but that is giving error.

The original code is
$data = [ 'recipient'=>['id'=>$sender], 'message'=>['text'=>$message_to_reply]];

//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
$jsonDataEncoded = json_encode ($data);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

$fp = fopen('errorlogfb.txt', 'w');

curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $fp);

//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}

and the one using your package is:

$response = Curl::to($url)
->withData($jsonData)
->withContentType('application/x-www-form-urlencoded')
->asJson()
->enableDebug('curlLogFile.txt')
->post();

The error that I am getting is:

  • Hostname graph.facebook.com was found in DNS cache
  • Trying 31.13.93.3...
  • Connected to graph.facebook.com (31.13.93.3) port 80 (#0)

POST /v2.6/me/messages?access_token=iZALJPHCXDqZC9ZCTZAiT6Td4tBiZALJPHCXDqZC9ZCTZAiT6Td4tBiZALJPHCXDqZC9ZCTZAiT6Td4tBiZALJPHCXDqZC9ZCTZAiT6Td4tBiZALJPHCXDqZC9ZCTZAiT6Td4tBiZALJPHCXDqZC9ZCTZAiT6Td4tBiZALJPHCXDqZC9ZCTZAiT6Td4tBHTTP/1.1
Host: graph.facebook.com
Accept: /
Content-Type: application/x-www-form-urlencoded
Connection: Keep-Alive
Content-Type: application/json
Content-Length: 143

  • upload completely sent off: 143 out of 143 bytes
  • The requested URL returned error: 400 Bad Request
  • Closing connection 0

Kindly can you guide me what I am doing wrong?

missing-input-response and missing-input-secret

        $captcha = Curl::to('https://www.google.com/recaptcha/api/siteverify')
            ->withData(array(
                'secret' => 'my_secret', 
                'response' => $recaptcha_response,
                'remoteip' => $_SERVER['REMOTE_ADDR']
            ))->asJson(true)->post();

I get...

[error-codes] => Array
        (
            [0] => missing-input-response
            [1] => missing-input-secret
        )

I can get this working using curl-less code... so I am not sure why this seems to not send my post data?

Proxy Support.

Hi
I would first thank you for the great work. I know I should not put this as an issue, but I did not know where to write it.

I want to ask if you have any plans to support making requests through a proxy ?

Thanks.

issues with authentication on API

Hey,

Love this plugin so far but having some issues with getting an api to authenticate. i have it working in PHP with the following:

 $ch = curl_init();

    // prepare cookie file
    $cookie_file_path = "unifi_cookie.txt";
    $fp = fopen ($cookie_file_path , "wb");
    fclose ($fp);

    // log into the API
    curl_setopt($ch, CURLOPT_URL, $baseurl.'/api/login');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    $data = array( "username" => $username, "password" => $password );
    $data_json = json_encode($data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
    $contents = curl_exec ($ch);

    /**
     * Close cURL session
     */
    curl_close ($ch);

My code so far with the plugin is as follows:

        Curl::to($this->baseURL().'/api/login')
            ->withData(array( "username" => $username, "password" => $password ))
            ->asJson()
            ->returnResponseObject()
            ->withOption('RETURNTRANSFER','1')
            ->withOption('VERBOSE', 'true')
            ->withOption('SSL_VERIFYPEER', 'false')
            ->withOption('SSL_VERIFYHOST', 'false')
            ->withOption('SSLVERSION', '1')
            ->setCookieFile("/var/tmp/unifi_cookie.txt")
            ->setCookieJar("/var/tmp/unifi_cookie.txt")
            ->enableDebug('/var/log/nginx/unifiapi.txt')
            ->post();

i have tried multiple different things,i have json encoded the array manually and put it as data but still says it cant login:

{#235 \u25bc
  +"data": []
  +"meta": {#237 \u25bc
    +"msg": "api.err.LoginRequired"
    +"rc": "error"
  }
}

Use Basic Auth

Hi, I'm trying to access an api, and they gave me the following command:

curl -u 123login:456passwd https://someurl
When I use cmd, I just replace 123login and 456passwd by my credentials.

I have tried to pass the credentials in my headers, as follow
$headers = array("Authorization"=>"login:passwd","CacheControl"=>"no-cache");
$response = Curl::to('http://url)
->withHeaders($headers)
->withData($someData);

But I keep getting a 401 error thrown at me because the authentication is incorrect.
However, the api works perfectly with the same credentials in Postman.
I have also tried to base64_encode my credentials and pass them as the auth value without any success.

XML by post

Why "withData" parameter must be type of array ?

I need to send an XML by post, but it's not possible as array, and can't user "withPackageOption" because is a protected function.

Thanks

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.