PHP.mk документација

curl_exec

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.curl-exec.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.curl-exec.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
curl_exec

Референца за `function.curl-exec.php` со подобрена типографија и навигација.

function.curl-exec.php

curl_exec

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_execИзврши cURL сесија

= NULL

curl_exec(CurlHandle $handle): string|bool

Изврши ја дадената cURL сесија.

Оваа функција треба да се повика откако ќе се иницијализира cURL сесија и сите опции за сесијата се поставени.

Параметри

handle

cURL ракувач вратен од curl_init().

Вратени вредности

При успех, оваа функција го испушта резултатот директно во stdout и враќа true, или false при неуспех. Меѓутоа, ако CURLOPT_RETURNTRANSFER опцијата е set, ќе го врати резултатот при успех, false при неуспех.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Функцијата враќа прочитани податоци или falseОваа функција може да врати Буловска вредност false, но исто така може да врати и вредност што не е Буловска, а која се проценува како Булови . Ве молиме прочитајте го делот за за повеќе информации. Користете го операторот ===

Забелешка:

Забележете дека статусните кодови на одговорот што укажуваат на грешки (како 404 Not found) не се сметаат за неуспех. curl_getinfo() може да се користи за проверка на овие.

Дневник на промени

Верзија = NULL
8.0.0 handle беше вратено при неуспех. CurlHandle инстанца сега; претходно, а resource се очекуваше.

Примери

Пример #1 Преземање веб страница

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);
?>

Види Исто така

  • curl_multi_exec() - Стартувај ги под-врските на тековниот cURL дескриптор

Белешки од корисници 8 белешки

David од Code2Design.com
пред 15 години
Just in case anyone is looking for a a couple of simple functions [to help automate cURL processes for POST and GET queries] I thought I'd post these.

<?php

/**
 * Send a POST requst using cURL
 * @param string $url to request
 * @param array $post values to send
 * @param array $options for cURL
 * @return string
 */
function curl_post($url, array $post = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post)
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

/**
 * Send a GET requst using cURL
 * @param string $url to request
 * @param array $get values to send
 * @param array $options for cURL
 * @return string
 */
function curl_get($url, array $get = NULL, array $options = array())
{    
    $defaults = array(
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );
    
    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
?>
Анонимен
19 години пред
Be careful when using curl_exec() and the CURLOPT_RETURNTRANSFER option. According to the manual and assorted documentation:
Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

When retrieving a document with no content (ie. 0 byte file), curl_exec() will return bool(true), not an empty string. I've not seen any mention of this in the manual.

Example code to reproduce this:
<?php

    // fictional URL to an existing file with no data in it (ie. 0 byte file)
    $url = 'http://www.example.com/empty_file.txt';

    $curl = curl_init();
    
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);

    // execute and return string (this should be an empty string '')
    $str = curl_exec($curl);

    curl_close($curl);

    // the value of $str is actually bool(true), not empty string ''
    var_dump($str);

?>
turiyag
пред 8 години
Don't disable SSL verification! You don't need to, and it's super easy to stay secure! If you found that turning off "CURLOPT_SSL_VERIFYHOST" and "CURLOPT_SSL_VERIFYPEER" solved your problem, odds are you're just on a Windows box. Takes 2 min to solve the problem. Walkthrough here:

https://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
jpatta на digitalgamesystems dot com
пред 4 години
If you are looking the debug curl_exec, you may wish to log its details, and analyze the various time points during its execution.

before curl_exec:

<?php
    // this will produce a curl log
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    curl_setopt($curl, CURLOPT_STDERR, fopen('/your/writable/app/logdir/curl.log', 'a+')); // a+ to append...
?>

after curl_exec, but before curl_close:

<?php
    // this will extract the timing information
    extract(curl_getinfo($curl)); // create metrics variables from getinfo
    $appconnect_time = curl_getinfo($curl, CURLINFO_APPCONNECT_TIME); // request this time explicitly
    $downloadduration = number_format($total_time - $starttransfer_time, 9); // format, to get rid of scientific notation
    $namelookup_time = number_format($namelookup_time, 9);
    $metrics = "CURL...: $url Time...: $total_time DNS: $namelookup_time Connect: $connect_time SSL/SSH: $appconnect_time PreTransfer: $pretransfer_time StartTransfer: $starttransfer_time Download: $downloadduration";
    error_log($metrics);  // write to php-fpm default www-error.log, or append it to same log as above with file_put_contents(<filename>, $metrics, FILE_APPEND)
?>

Happy debugging
hablutzel1 на gmail точка com
пред 11 години
Be always aware that CURLOPT_SSL_VERIFYPEER set to FALSE or 0 should never be used for production as it makes the link inmediately vulnerable to man-in-the-middle attack, still you can use it during development, but I would suggest that only if you KNOW what are you doing, otherwise spend some more time making requests to HTTPS sites work without resorting to set that option to FALSE or 0.
roman dot ivasyuk на gmail dot com
пред 18 години
<?php
class CurlRequest
{
    private $ch;
    /**
     * Init curl session
     * 
     * $params = array('url' => '',
     *                    'host' => '',
     *                   'header' => '',
     *                   'method' => '',
     *                   'referer' => '',
     *                   'cookie' => '',
     *                   'post_fields' => '',
     *                    ['login' => '',]
     *                    ['password' => '',]      
     *                   'timeout' => 0
     *                   );
     */                
    public function init($params)
    {
        $this->ch = curl_init();
        $user_agent = 'Mozilla/5.0 (Windows; U; 
Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
        $header = array(
        "Accept: text/xml,application/xml,application/xhtml+xml,
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
        "Accept-Language: ru-ru,ru;q=0.7,en-us;q=0.5,en;q=0.3",
        "Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7",
        "Keep-Alive: 300");
        if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
        if (isset($params['header']) && $params['header']) $header[]=$params['header'];
        
        @curl_setopt ( $this -> ch , CURLOPT_RETURNTRANSFER , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_VERBOSE , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_HEADER , 1 );
        
        if ($params['method'] == "HEAD") @curl_setopt($this -> ch,CURLOPT_NOBODY,1);
        @curl_setopt ( $this -> ch, CURLOPT_FOLLOWLOCATION, 1);
        @curl_setopt ( $this -> ch , CURLOPT_HTTPHEADER, $header );
        if ($params['referer'])    @curl_setopt ($this -> ch , CURLOPT_REFERER, $params['referer'] );
        @curl_setopt ( $this -> ch , CURLOPT_USERAGENT, $user_agent);
        if ($params['cookie'])    @curl_setopt ($this -> ch , CURLOPT_COOKIE, $params['cookie']);

        if ( $params['method'] == "POST" )
        {
            curl_setopt( $this -> ch, CURLOPT_POST, true );
            curl_setopt( $this -> ch, CURLOPT_POSTFIELDS, $params['post_fields'] );
        }
        @curl_setopt( $this -> ch, CURLOPT_URL, $params['url']);
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYPEER, 0 );
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYHOST, 0 );
        if (isset($params['login']) & isset($params['password']))
            @curl_setopt($this -> ch , CURLOPT_USERPWD,$params['login'].':'.$params['password']);
        @curl_setopt ( $this -> ch , CURLOPT_TIMEOUT, $params['timeout']);
    }
    
    /**
     * Make curl request
     *
     * @return array  'header','body','curl_error','http_code','last_url'
     */
    public function exec()
    {
        $response = curl_exec($this->ch);
        $error = curl_error($this->ch);
        $result = array( 'header' => '', 
                         'body' => '', 
                         'curl_error' => '', 
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            return $result;
        }
        
        $header_size = curl_getinfo($this->ch,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($response, 0, $header_size);
        $result['body'] = substr( $response, $header_size );
        $result['http_code'] = curl_getinfo($this -> ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($this -> ch,CURLINFO_EFFECTIVE_URL);
        return $result;
    }
}
?>

Example of use:
<?php
..........
try
        {            
            $params = array('url' => 'http://www.google.com',
            'host' => '',
            'header' => '',
            'method' => 'GET', // 'POST','HEAD'
            'referer' => '',
            'cookie' => '',
            'post_fields' => '', // 'var1=value&var2=value
            'timeout' => 20
            );
            
            $this->curl->init($params);
            $result = $this->curl->exec();
            if ($result['curl_error'])    throw new Exception($result['curl_error']);
            if ($result['http_code']!='200')    throw new Exception("HTTP Code = ".$result['http_code']);
            if (!$result['body'])        throw new Exception("Body of file is empty");
            ...............
        }
        catch (Exception $e)
        {
                    echo $e->getMessage();
        }
?>
lukasl на ackleymedia dot com
19 години пред
Thank you for sharing this.  I was wondering why my result was 1.

To get around this in a safe way, this is how I check if the result is valid.

$ch = curl_init(); /// initialize a cURL session 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec ($ch);
curl_close ($ch);

if (!is_string($xmlResponse) || !strlen($xmlResponse)) {
    return $this->_set_error( "Failure Contacting Server" );
} else {
    return $xmlResponse;
}
nagyp на hunaxon dot hu
пред 22 години
fyi:
It returns false if there's an error while executing the curl session, no matter how CURLOPT_RETURNTRANSFER is set.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.