Php curl сбросить кэш
true to disable the progress meter for cURL transfers.
Note:
PHP automatically sets this option to true , this should only be changed for debugging purposes.
The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.
CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM .
CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM .
Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also CURLOPT_REDIR_PROTOCOLS .
The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.
CURLAUTH_BASIC allows username/password authentication.
CURLAUTH_GSSAPI allows GSS-API authentication.
CURLAUTH_NONE allows no authentication.
Defaults to CURLAUTH_BASIC|CURLAUTH_GSSAPI . Set the actual username and password with the CURLOPT_PROXYUSERPWD option.
Note:
Your best bet is to not set this and let it use the default. Setting it to 2 or 3 is very dangerous given the known vulnerabilities in SSLv2 and SSLv3.
Note:
Your best bet is to not set this and let it use the default CURL_SSLVERSION_DEFAULT which will attempt to figure out the remote SSL protocol version.
A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET" , "POST" , "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.
Note:
Don't do this without making sure the server supports the custom request method first.
The default protocol to use if the URL is missing a scheme name.
Set the name of the network interface that the DNS resolver should bind to. This must be an interface name (not an address).
Set the local IPv4 address that the resolver should bind to. The argument should contain a single numerical IPv4 address as a string.
Set the local IPv6 address that the resolver should bind to. The argument should contain a single numerical IPv6 address as a string.
Note:
Secure Remote Password (SRP) authentication for TLS provides mutual authentication if both sides have a shared secret. To use TLS-SRP, you must also set the CURLOPT_PROXY_TLSAUTH_USERNAME and CURLOPT_PROXY_TLSAUTH_PASSWORD options.
The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY .
Note:
Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.
value should be an array for the following values of the option parameter:
Option | Set value to | Notes |
---|---|---|
CURLOPT_CONNECT_TO | Connect to a specific host and port instead of the URL's host and port. Accepts an array of strings with the format HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT . | Added in cURL 7.49.0. Available since PHP 7.0.7. |
CURLOPT_HTTP200ALIASES | An array of HTTP 200 responses that will be treated as valid responses and not as errors. | Added in cURL 7.10.3. |
CURLOPT_HTTPHEADER | An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100') | |
CURLOPT_POSTQUOTE | An array of FTP commands to execute on the server after the FTP request has been performed. | |
CURLOPT_PROXYHEADER | An array of custom HTTP headers to pass to proxies. | Added in cURL 7.37.0. Available since PHP 7.0.7. |
CURLOPT_QUOTE | An array of FTP commands to execute on the server prior to the FTP request. | |
CURLOPT_RESOLVE | Provide a custom address for a specific host and port pair. An array of hostname, port, and IP address strings, each element separated by a colon. In the format: array("example.com:80:127.0.0.1") | Added in cURL 7.21.3. |
value should be a stream resource (using fopen() , for example) for the following values of the option parameter:
Option | Set value to |
---|---|
CURLOPT_FILE | The file that the transfer should be written to. The default is STDOUT (the browser window). |
CURLOPT_INFILE | The file that the transfer should be read from when uploading. |
CURLOPT_STDERR | An alternative location to output errors to instead of STDERR . |
CURLOPT_WRITEHEADER | The file that the header part of the transfer is written to. |
A callback accepting five parameters. The first is the cURL resource, the second is the total number of bytes expected to be downloaded in this transfer, the third is the number of bytes downloaded so far, the fourth is the total number of bytes expected to be uploaded in this transfer, and the fifth is the number of bytes uploaded so far.
Note:
The callback is only called when the CURLOPT_NOPROGRESS option is set to false .
Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error.
Other values:
Option | Set value to |
---|---|
CURLOPT_SHARE | A result of curl_share_init() . Makes the cURL handle to use the data from the shared handle. |
Решение
Извините, но вы пришли к неверному выводу, и, таким образом, вы тут же лаете не на то дерево.
Если вы перестанете получать трафик до того, как он должен был закончиться, это потому, что больше нет данных, доставляемых или, скорее, получаемых libcurl. Это может быть сервер, который прекратил отправку, или это может быть что-то в вашей сети, что мешает. libcurl отправил запрос, и он будет ждать поступления данных, пока все не будет доставлено.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Список параметров
Дескриптор cURL, полученный из curl_init() .
Changelog
Notes
Note:
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
в кода я в настоящее время использую для получения информации выглядит следующим образом:
это возможно? Спасибо.
вам нужно написать или загрузить библиотеку кэширования php (например,расширяемая библиотека кэширования php или такой) и настроить ваш текущий код, чтобы сначала взглянуть на кэш.
предположим, что ваша библиотека кэша имеет 2 функции, называемые:
С save_cache() вы сохраните $result в кэше и с get_cache() вы получите данные.
$cache_key будет md5($fullURL) , уникальный идентификатор кэширование библиотеки, чтобы узнать, что вы хотите получить.
$timestamp - это количество минут / часов, которое вы хотите, чтобы Кэш был действительным, в зависимости от того, что принимает ваша библиотека кэширования.
теперь на вашем коде вы можете иметь логику, как:
вы можете кэшировать его с помощью memcache (сеанс) вы можете кэшировать его с помощью файлов на вашем сервере, и вы можете кэшировать его с помощью базы данных, как mySQL.
вам нужно будет установить разрешения папки, в которую вы хотите записать файлы, иначе вы можете получить некоторые ошибки.
затем, если вы хотите прочитать из кэша:
использовать Кэш Nette. Все, что вам нужно решение, простое в использовании и, конечно же, потокобезопасное.
Если у вас нет ничего против доступа к файловой системе, вы можете просто сохранить его в файл. Тогда может использовать скрипт на сервере, который проверяет метку времени файла на текущее время, и удаляет его, если он слишком старый.
Если у вас нет доступа ко всем аспектам сервера, вы можете просто использовать вышеуказанную идею и сохранить временную метку с информацией. Каждый раз, когда страница запрашивается, проверьте отметку времени.
и если у вас возникли проблемы с ФС узкое место, вы можете использовать базу данных MySQL, хранящуюся полностью в ОЗУ.
лучший способ избежать кэширования-это применить время или любой другой случайный элемент к url-адресу, например:
$url .= '?ts=' . time();
This function re-initializes all options set on the given cURL handle to the default values.
Примеры
// Создаём обработчик curl
$ch = curl_init ();
// Устанавливаем опцию CURLOPT_USERAGENT
curl_setopt ( $ch , CURLOPT_USERAGENT , "My test user-agent" );
// Сбрасываем все установленные опции
curl_reset ( $ch );
// Закрываем обработчик
curl_close ( $ch );
?>
Return Values
Returns true on success or false on failure.
See Also
Parameters
A cURL handle returned by curl_init() .
Смотрите также
User Contributed Notes 2 notes
If you're reusing a cUrl handle and want to ensure there's no residue from previous options -- but are frustrated with resetting the basics (e.g. FTP details) needed for each cURL call -- then here's an easy pattern to fix that:
/* Create the cURL handle */
function __construct () $this -> curl = curl_init ();
$this -> curl_init_opts ();
curl_exec ( $this -> curl );
>
/* Reload your base options */
function curl_init_opts () $opts [ CURLOPT_PROTOCOLS ] = CURLPROTO_FTP ;
$opts [ CURLOPT_RETURNTRANSFER ] = true ;
$opts [ CURLOPT_USERPWD ] = 'user:pass' ;
//.
curl_setopt_array ( $this -> curl , $opts );
>
/* Use when making a new cURL call */
function curl_exec ( $opts ) curl_reset ( $this -> curl ); // clears all old options
$this -> curl_init_opts (); // sets base options again
curl_setopt_array ( $this -> curl , $opts ); // sets your new options
return curl_exec ( $this -> curl );
>
/* Your whatever cURL method */
function curl_get_whatever () $opts [ CURLOPT_URL ] = 'ftp://. /whatever' ;
//.
$result = $this -> curl_exec ( $opts );
// .
>
>
?>
Then: each call to $this->curl_exec() from your whatever-method resets the previous options, reloads the base options, adds in your new options, and returns the result. Otherwise, can also put your base options into a class property, instead of in-method, if there's nothing dynamic being defined. Enjoy. =^_^=
Если я вставлю этот URL в адресную строку своего веб-браузера, я смогу увидеть живое видео, но через несколько минут оно перестает воспроизводиться. Если я убью браузер и повторю процесс, я смогу получить потоковое видео еще несколько минут, прежде чем он снова остановится.
Я подумал, что это должно быть связано с тем, что веб-браузер кэширует фреймы MJPEG и не хватает памяти, поэтому в качестве эксперимента я смоделировал простую HTML-страницу примерно так:
В результате видео постоянно течет и никогда не останавливается. Поэтому я думаю, что тег имеет отношение к утилизации кадров MJPEG и не вызывает сбой, как раньше.
URL вставлен в адресную строку веб-браузера:
URL, встроенный в веб-страницу:
Единственные различия, кажется, Принять: параметры.
Теперь перейдем к моей настоящей проблеме. Я использую тот же URL-адрес в моей программе C ++ curl, и я вижу точно такое же поведение, когда я получаю видеоданные в течение нескольких минут, а затем внезапно обратные вызовы curl прекращаются.
Я использовал следующие заголовки в моей программе curl:
Что я могу сделать, чтобы остановить это поведение в CURL? Я предполагаю, что кэширование должно быть таким же образом, как это делал браузер.
Return Values
Returns true on success or false on failure.
Changelog
Version | Description |
---|---|
8.0.0 | handle expects a CurlHandle instance now; previously, a resource was expected. |
Примечания
Замечание:
curl_reset() также сбрасывает URL, заданный в качестве параметра curl_init() .
Return Values
No value is returned.
Notes
Note:
curl_reset() also resets the URL given as the curl_init() parameter.
Список изменений
Версия | Описание |
---|---|
8.0.0 | handle теперь ожидает экземпляр CurlHandle ; раньше, ожидался ресурс ( resource ). |
User Contributed Notes 2 notes
If you're reusing a cUrl handle and want to ensure there's no residue from previous options -- but are frustrated with resetting the basics (e.g. FTP details) needed for each cURL call -- then here's an easy pattern to fix that:
/* Create the cURL handle */
function __construct () $this -> curl = curl_init ();
$this -> curl_init_opts ();
curl_exec ( $this -> curl );
>
/* Reload your base options */
function curl_init_opts () $opts [ CURLOPT_PROTOCOLS ] = CURLPROTO_FTP ;
$opts [ CURLOPT_RETURNTRANSFER ] = true ;
$opts [ CURLOPT_USERPWD ] = 'user:pass' ;
//.
curl_setopt_array ( $this -> curl , $opts );
>
/* Use when making a new cURL call */
function curl_exec ( $opts ) curl_reset ( $this -> curl ); // clears all old options
$this -> curl_init_opts (); // sets base options again
curl_setopt_array ( $this -> curl , $opts ); // sets your new options
return curl_exec ( $this -> curl );
>
/* Your whatever cURL method */
function curl_get_whatever () $opts [ CURLOPT_URL ] = 'ftp://. /whatever' ;
//.
$result = $this -> curl_exec ( $opts );
// .
>
>
?>
Then: each call to $this->curl_exec() from your whatever-method resets the previous options, reloads the base options, adds in your new options, and returns the result. Otherwise, can also put your base options into a class property, instead of in-method, if there's nothing dynamic being defined. Enjoy. =^_^=
Эта функция переинициализирует все настройки заданного обработчика сессии cURL значениями по умолчанию.
Examples
// 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 , false );
// grab URL and pass it to the browser
curl_exec ( $ch );
// close cURL resource, and free up system resources
curl_close ( $ch );
?>
Examples
// Create a curl handle
$ch = curl_init ();
// Set CURLOPT_USERAGENT option
curl_setopt ( $ch , CURLOPT_USERAGENT , "My test user-agent" );
// Reset all previously set options
curl_reset ( $ch );
// Close the handle
curl_close ( $ch );
?>
Читайте также: