Coder Social home page Coder Social logo

yii2-curl's People

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

yii2-curl's Issues

Curl not giving me any response

I am trying to use a GET method to carry of some data from the a URL. I am trying to get a code from a URL by following this Zoho Link

Below is my code

`$curl = new curl\Curl();
    $response = $curl->setGetParams([
        'scope' => 'ZohoBugTracker.projects.ALL,ZohoBugTracker.bugs.ALL',
        'client_id' => '1000',
        'response_type' => 'code',
        'access_type' => 'offline',
        'redirect_uri' => 'http://11.111.111.111:7000/api/oauth/zoho_auth',
    ])
        ->get('https://accounts.zoho.com/oauth/v2/auth');

    if ($curl->errorCode === null) {
        echo $response;
    } else {

        echo '<pre>';print_r($curl->errorCode);
    }
    exit();`

I am using POSTMAN for testing my API but all I see a empty screen. I have also put this question on StackOverFlow.

Can anyone please help me out

not going into timeout case

Hi,

I have tried the example shown in your main page.

public function actionGetAdvancedExample()
{
        //Init curl
        $curl = new curl\Curl();

        //get http://example.com/
        $response = $curl->post('http://www.google.com:81/');

        // List of status codes here http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
        switch ($curl->responseCode) {

            case 'timeout':
                //timeout error logic here
                break;

            case 200:
                //success logic here
                break;

            case 404:
                //404 Error logic here
                break;
        }
}

but its not going into timeout case its going into default case only.

kindly help me on this i tried with both get and post.

regards,

response always is empty string

in the version 1.0.3, the response always is empty string; when debug, theCURLOPT_WRITEFUNCTION not run

$this->setOption(CURLOPT_WRITEFUNCTION, function ($curl, $data) use (&$body) {
    $body .= $data;
    return mb_strlen($data, '8bit');
});

but modify the function getOptions to version 1.0.2, is work

public function getOptions()
 {
     return $this->_defaultOptions + $this->_options;
 }

myCurl version, my code use ssl

$ php -r 'var_dump( curl_version());'
array(9) {
  'version_number' =>
  int(465408)
  'age' =>
  int(3)
  'features' =>
  int(50813)
  'ssl_version_number' =>
  int(0)
  'version' =>
  string(6) "7.26.0"
  'host' =>
  string(19) "x86_64-pc-linux-gnu"
  'ssl_version' =>
  string(14) "OpenSSL/1.0.1e"
  'libz_version' =>
  string(5) "1.2.7"
}

other Issue, when i want modify the _defaultOptions(eg:CURLOPT_CONNECTTIMEOUT),no way.

为什么原来程序正常,现在不通了

//Init curl
$curl = new curl\Curl();

    //get http://example.com/
    $response = $curl->get('http://example.com/');

为什么得到的$response是个空串啊,

{"reason":"短信发送成功","result":{"count":1,"fee":1,"sid":1754675453},"error_code":0}string(0) ""
string(0) ""
这个是我返回的内容,下面的我的程序,原来都没有问题的程序啊,今天不通了
$curl = new Curl();
$result = $curl->get($getUrl,true);

Problem with get

I have upgraded linslin/yii2-curl from 1.0.3 to 1.1.1

My request

        $curl = new Curl();
        $curl->setOption(CURLOPT_HEADER, 'Accept:application/json');
        $response = $curl->get($url);

in function _httpRequest we have

        //extract header / body data if CURLOPT_HEADER are set to true
        if (isset($curlOptions[CURLOPT_HEADER]) && $curlOptions[CURLOPT_HEADER]) {
            $this->response = $this->_extractCurlBody($response);
            $this->responseHeaders = $this->_extractCurlHeaders($response);
        } else {
            $this->response = $response;
        }

and

protected function _extractCurlBody ($response)
    {
        return substr($response, $this->getInfo(CURLINFO_HEADER_SIZE));
    }

in my response I have

'getInfo(CURLOPT_HEADER)' => false
'getInfo(CURLINFO_HEADER_SIZE)' => 503

Then cURL returns my response without half of it
But without

$curl->setOption(CURLOPT_HEADER, 'Accept:application/json');

I have full response

What am i doing wrong?

我要怎么关闭上面那个curl获取的json

$curl = new curl\Curl();
$response = $curl->get('http://example.com/');

$response 是json字符串,这个是返回,为什么会又直接输出个json到console里面,我现在用ajax,
正常应该返回{"status":1,"msg":"验证码发送成功"},为什么现在是
{"reason":"操作成功","result":{"sid":"","fee":1,"count":1},"error_code":0}{"status":1,"msg":"验证码发送成功"},我要怎么关闭上面那个curl获取的json

Not installed on PHP 5.6

Your requirements could not be resolved to an installable set of packages.

Problem 1
- sebastian/recursion-context 3.0.0 requires php ^7.0 -> your PHP version (5.6.30) does not satisfy that requirement.
- sebastian/recursion-context 3.0.0 requires php ^7.0 -> your PHP version (5.6.30) does not satisfy that requirement.
- sebastian/recursion-context 3.0.0 requires php ^7.0 -> your PHP version (5.6.30) does not satisfy that requirement.
- Installation request for sebastian/recursion-context (locked at 3.0.0) -> satisfiable by sebastian/recursion-context[3.0.0].

curl request failed: SSL certificate problem: self signed certificate in certificate chain

I am unable to know why the extension shows this error "curl request failed: SSL certificate problem: self signed certificate in certificate chain" whenever I want to try to initiate https request like "https://test.payu.in/_payment"
Please know what I will do if it necessary to go with https.
I already tried by setting the option CURLOPT_SSL_VERIFYPEER but it is not working... showing same error
My curl is : linslin\yii2\curl\Curl::_httpRequest('POST', 'https://test.payu.in/_payment', true)

this is my code :
$curl = new Curl();
$curl->setOption(
CURLOPT_POSTFIELDS,
CURLOPT_SSL_VERIFYPEER,
http_build_query([
$payu->hashstring()
])
)->post($payu->payment_url);

Thanks is advance

Empty response when error code 302 redirect

The response should ALWAYS, always, always, return something. No matter what URL I try to "get", your '$curl->get()` should always return something.

$curl = new curl\Curl();
$hash = md5('[email protected]');
$response = $curl->get('https://www.gravatar.com/' . $hash . '.json');
die('<pre>' . print_r($response, true) . '</pre>');
return $response;

Note, the die() is being used for testing. This should work, and does work when I jump out early and use like die('here'); just fine. So there are no issues with the route or controller or anything.

When I looked deeper using, die('<pre>' . print_r($curl->statusCode, true) . '</pre>');, it returned 302, which is a redirect.

You should add CURLOPT_FOLLOWLOCATION = true to the default options, with the ability to change it if they need to.

I know that in order to get this to work:

$response = $curl->get('https://www.gravatar.com/' . $hash . '.json');
die($response->statusCode);    // <-- notice I am using $response not $curl!

Would take some recoding on your end. You would need to create an official release version to not break people's current versions. However, it should return the basic info:

$response = $curl->get('https://www.gravatar.com/' . $hash . '.json');

$response should contain all the info I need in an array:

[
    'data' => null, // the data from the get() function
    'statusCode' => 200,
    'errorCode' => 0,  // not sure what default with no error is?
    'headers => [],  // an array of the headers returned
    // maybe more here?
]

Then we would do this:

public function actionGravatarProfile($email)
{
    $curl = new curl\Curl();
    $hash = md5(trim($email));
    $response = $curl->get('https://www.gravatar.com/' . $hash . '.json');
    
    if ( $response->statusCode === 200 ) {
        // success
        return $response->data;
    } else if ($response->statusCode === 404 ) {
        // user not found
        die('User not found');  // crude but just example
    } else {
        // error
        die('Error was ' . $response->statusCode); // crude but just example
    }
}

This will better allow us to handle errors, utilize Angular or jQuery if needed, etc.

For example, look at the jQuery AJAX function. It returns not just the data, but the status, headers, everything we need for post process handling.


However, without changing the code, in it's current form, we need to do this to follow redirects:

$response = $curl->setOption(CURLOPT_FOLLOWLOCATION, true)->get('https://www.yoururlhere.com');

I hope you will consider at least setting follow location to true as your default options, and maybe even improving your logic handling as I laid out in this thread.

fields[email]

Can i set params like?
'fields[email]' => $model->email,

https

Hello)
Is it possible to work with https requests?

Pass options to constructor

Could you add a functionality to pass options to constructor function.
So I could do something like that:

$curl = curl\Curl([
    CURLOPT_POSTFIELDS => http_build_query(['myPostField' => 'value'])
]);
$response = $curl->post('http://example.com/');

Simply to skip a line for adding options on simple requests.

Also it would be nice if you added PHP highlighting in readme.md. :)

POST Request Body Array

I'm using this extension to communicate with the mapquest api .The documentation for the direction routing tells the POST Request Body has to be in the following format:

{ "locations": [
        "Clarendon Blvd, Arlington, VA",
        "2400 S Glebe Rd, Arlington, VA"
    ],
    "options": {
        "unit": "m",
    }
} 

So i configured this extension as following:

$params = ["locations" =>
   ["Clarendon Blvd, Arlington, VA", "2400 S Glebe Rd, Arlington, VA"],
   "options" => ["unit" => "k"]
];

$response = $curl->setGetParams(
               [
                   'key' => 'your_key_here',
                   "outFormat" => "json",
       ])
       ->setRequestBody($params)
       ->post("http://www.mapquestapi.com/directions/v2/route");

This configuration returns me the following error message from mapquest:

The LocationCollection must contain at least two locations.

If i use curl directly everything works just fine:

$data = array("locations" => ["Clarendon Blvd, Arlington, VA", "2400 S Glebe Rd, Arlington, VA"]);
$data_string = json_encode($data);

$ch = curl_init("http://www.mapquestapi.com/directions/v2/route?key=your_key_here");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json",
    "Content-Length: " . strlen($data_string))
);
Yii::$app->response->format = Response::FORMAT_JSON;
return json_decode(curl_exec($ch));

So do i configurate this extension wrong?

Can't get it to work via composer

Hello I have yii2 basic project.
The extension was installed through composer.
Right after that I try as per example do the stuff:

use linslin\yii2\curl;
...
$curl = new curl\Curl();

And there is an exception "Class 'linslin\yii2\curl\Curl' not found".
It seems the Curl.php is in a right place as well as all the stuff inside composer.json.
What goes wrong for me?
May be I need to execute some additional command in order to get the Curl into the classmap?

How to set custom header.

Hello I like this Extension, it is really awesome work, I know there is must be some way to set custom header in it, can you please guide me in it.

Current curl response error json formatting error. json_decode($response, true) failed.

Hello,

I have used this extension in my yii 2 application. When I had started working on using this extension the response was working fine and after json_decode() I was getting array.

After 10 months when I updated the composer.json and project dependencies the application broke.
gettype(json_decode($response, true)) is returning NULL instead of array now, but same application on another computer with old dependencies is working fine (same code).

When using php's curl the code is working fine. Ex

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://hayageek.com");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response=curl_exec($ch);
curl_close($ch);

gettype(json_decode($response)) returns array

Attached are the old and new composer.json and composer.lock files.

Regards
Ismail.

OldComposer.lock.txt
OldComposer.json.txt
composer.lock.txt
composer.json.txt

Do not reinitialize curl resource. Make several request with the same session/cookies.

I need to login on site and make several request as logined user. But for each request method _httpRequest make curl_init($this->getUrl()), so for each request i am new user.
My code:

$curl
    ->setOption(CURLOPT_COOKIESESSION, 1)
    ->setOption(CURLOPT_COOKIEJAR, '/tmp/cookies.txt')
    ->setPostParams($loginParams)
    ->post(LOGIN_URL);
$curl->setPostParams($anotherParams)->post(ANOTHER_URL);

After first request i am loginned, all good. On second request i got error that i am not logined...

I porpose make some changes to _httpRequest method:
replace line 603
to

if ($this->curl === null) {
    $this->curl = curl_init();
}
curl_setopt($this->curl, CURLOPT_URL, $this->getUrl());

Download file with GET request?

I have a GET URL that returns binary data.
How do I get hold of that binary data?

Something like:
$data = $this->curl->get('myurl');

Post json string

Sometimes it is useful to post simple json string:

curl http://youdomain.com/api --data '["whatever here", "again"]'

In this case this would not work:

/**
 * Set get params
 *
 * @param array $params
 * @return $this
 */
public function setPostParams($params)
{
    if (is_array($params)) {
        $this->setOption(
            CURLOPT_POSTFIELDS,
            http_build_query($params)
        );
    }
    return $this;
}

it is required to change it to this to make method accept plain strings as well:

/**
 * Set get params as array or as plain string, such as JSON.
 *
 * @param array|string $params
 * @return $this
 */
public function setPostParams($params)
{
    $this->setOption(
        CURLOPT_POSTFIELDS,
        is_array($params) ? http_build_query($params) : $params
    );
    return $this;
}

Undefined offset: 1

We are facing a problem since the last update while Curl is trying to extract additional params.
https://github.com/linslin/Yii2-Curl/blob/master/Curl.php:

if (preg_match('~^charset=(.+?)$~', trim($possible_charset), $matches) && isset($matches[1])) {
    $this->responseCharset = strtolower($matches[1]);
}

shouldn't we use array_key_exists(1,$matches) instead of isset($matches[1])?

how to do this by yii2-curl

how to do this by yii2-curl

curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '
{
  "name": "John Doe"
}'

Issues when setting CURLOPT_RETURNTRANSFER explicitly as true

Your latest changes broke my code. I have some idea why.

I was explicitly setting CURLOPT_RETURNTRANSFER to true:

$response = $curl ->setOption(CURLOPT_RETURNTRANSFER, true) ->get($url)

This was working but now it is not. Now $response comes back as true, rather than as the data. However when I remove the setOption line, I get the data.
What appears to be happening is that cURL has issues with the order of setting CURLOPT_RETURNTRANSFER and CURLOPT_WRITEFUNCTION.

Your current code sets CURLOPT_WRITEFUNCTION into the options array in _httpRequest() then adds the default options after in getOptions(). With no explicit setting of CURLOPT_RETURNTRANSFER, this means that CURLOPT_WRITEFUNCTION is set ahead of CURLOPT_RETURNTRANSFER in the array and when calling curl_setopt_array(). What happens now, is that the CURLOPT_WRITEFUNCTION callback anonymous function does not get called. The data is returned correctly in $body.

If CURLOPT_RETURNTRANSFER is explicitly set as in my code, then the order in the array changes, CURLOPT_RETURNTRANSFER is set first and hence set first with curl_setopt_array(). Now the callback function is called and messes up the data.

Why cURL exhibits this behavior I don't know and I haven't tried digging through the code. There is an interesting comment here an=bout using them together: http://php.net/manual/en/function.curl-setopt.php just search.

I don't understand the need for the callback function. I can't work out in what case it might be needed and it now seems to mess with your latest changes. I would suggest that it be completely removed unless I am missing something. That certainly makes my code work.

Of course the other way to "fix" this is to not set CURLOPT_RETURNTRANSFER explicitly.

How to post with Authorization as header?

What am I doing wrong here:

$response = $curl ->setHeaders(CURLOPT_HTTPHEADER,[ 'Authorization' => 'Client-ID c5ddfba8180e164' ]) ->get('https://api.imgur.com/3/account/hndev2/albums/');

How to execute GET-request with params?

I need to run the following GET-request:

curl --request GET \
--url 'https://usX.api.mailchimp.com/3.0/campaigns' \
--user 'anystring:apikey' \
--include

Issue Server Response not get

I have request to server using following code
$response = $curl ->setHeaders(['accept' => 'application/json']) ->setPostParams($parameters) ->post($url);
After this i have print curl Information
$curl->getInfo()
It give me following response

Array
(
[url] =>url is write but i have not share here
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 250
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.013403
[namelookup_time] => 0.012373
[connect_time] => 0.012944
[pretransfer_time] => 0.012975
[size_upload] => 52
[size_download] => 0
[speed_download] => 0
[speed_upload] => 3879
[download_content_length] => -1
[upload_content_length] => 52
[starttransfer_time] => 0.013394
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => ip is write but i have not share here
[certinfo] => Array
(
)
[primary_port] => 80
[local_ip] => 10.0.27.188
[local_port] => 36376
)

I found a bug in your code - Wrong function patch()

Hi, I found a bug in your code in the file Curl.php. Wrong function patch(). The function should return $this->_httpRequest('PATCH',$raw); Otherwise, I could not launch a request with the patch method. At now moment, you return $this->_httpRequest('POST',$raw);

Not Getting latest version

i am using Yii2 v 2.0.15.1 and whenever i try to install the extension it always installs the v 1.0.3 which is too old and does not have the setGetParms function and hence I am unable to run the simplest get request example with parameters.

in composer.json i have minimum-stability:stable what should I do that it updates to the latest version rather than the older.

curl_getinfo

please provide the informations as an associative array from curl_getinfo

see: http://php.net/manual/de/function.curl-getinfo.php
-> 'If opt is given, returns its value. Otherwise, returns an associative array with the following elements (which correspond to opt)'

i need 'CURLINFO_REDIRECT_COUNT' for better parsing the response ;-)

Always return true

Hello!
When i use get method i have in an answer true, but if i comment this part
$this->setOption(CURLOPT_WRITEFUNCTION, function ($curl, $data) use (&$body) { $body .= $data; return mb_strlen($data, '8bit'); }); i see right answer (json).

Https

How to handle the Https API's..?
curl request failed: SSL certificate problem: unable to get local issuer certificate

responseHeaders with ':' truncated

In r 1.1.1
line
list ($key, $value) = explode(': ', $line);
_extractCurlHeaders

was changed to
list ($key, $value) = explode(':', $line);

': ' with space -> ':' without space.
So header Location: http://foo.bar bocomes:
'Location'=>'http'

Getting errors from failed requests

At the moment, there is no easy way to get errors from failed requests. For example our request fails, with code 400 and body:

{"email": ["Email is already in use"]}

But return from your _httpRequest() in case of 400 error is simply false;

So we have to go and get the response, BUT the response is not being JSON decoded, because you have the $raw check only on successful request.

I would fix it like this:

...
//retrieve response code
$this->responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$this->response = $raw ? $this->response : Json::decode($body);
...
...
//check responseCode and return data/status
        if ($this->responseCode >= 200 && $this->responseCode < 300) { // all between 200 && 300 is successful
            return true;
        } elseif ($this->responseCode >= 400 && $this->responseCode <= 510) { // client and server errors return false.
            return false;
        } else { //any other status code or custom codes
            return true;
        }
...

I dont see much point returning the request result only in case its successful and its not HEAD. Just rather keep it consistent and have the function return boolean, and the developer to go for $curl->response directly

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.