EverKB

Knowledge Base Ever

在PHP中使用cURL上傳文件的方法

2019-11-18 23:43:46

標籤: PHP, PHP5.5, cURL, CURLOPT_POSTFIELDS, File Upload, CURLFille, PHP上傳文件

PHP使用Daniel Stenberg創建的libcurl庫連接各種服務器,它支持的協議有http、https、ftp、gopher、telnet、dict、file、ldap。 libcurl還支持HTTPS證書、POST、PUT、FTP等,還支持基於表單的上傳、代理、cookies、用戶名+密碼的認證。

PHP使用cURL庫發起這些HTTP請求。 cURL依賴libcurl7.10.5或以上版本。

在PHP5.4或之前的版本中,cURL上傳文件的封裝方式是過程式的:

$ch = curl_init();
$data = array('name' => 'File1', 'file' => '@/path/to/file.png');
curl_setopt($ch, CURLOPT_URL, 'https://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);

在PHP5.5或之後的版本中,cURL上傳文件的封裝更新成CURLFille類的方式:

$ch = curl_init();
$data = array('name' => 'File1', 'file' => new CURLFille('/path/to/file.png'));
curl_setopt($ch, CURLOPT_URL, 'https://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);

標籤

CentOS7 CentOS PHP Linux Python3 Python MySQL MariaDB YUM JavaScript MySQL8 caching_sha2_password HTML mysql_native_password PHP7 CSS Redis frequency conflict set_error_handler TestCase Compiling PHP Elasticsearch7.3 PHPUnit ss5.conf apr HTTP particles.js Slim Vincent Garreau daemon Failed to build these modules: _uuid MongoDB Sudo DATE_ADD ip command pg_bha.conf SQL Server width Frameworks MySQL-python scrollbar Tcp BBR Compiling Apache Elasticsearch libpython3.7m.so.1.0 PHPStorm ss5-3.8.9 Apache2.4 NodeJs show VIM CURLOPT_POSTFIELDS Failed to build these modules: _ctypes Minimal ISO substr Bluetooth date sub INTERVAL PECL SQL Date Funcitons Wi-Fi font-size root Tag Cloud CodeIgniter dual network interfaces Laravel ss5 apache httpd horiz-align node.js ShadowsocksR vertical-align CURLFille exec mb_substr PyCharm SUBDATE BarManager date add IntelliJIDEA PEAR SOCKS5 Proxy Server WebStorm find remi Tag Chrome du jQuery PHP5.5 src Apache hide nginx Shadowsocks-Python V2Ray cURL eth0 MariaDB10.4 PostgreSQL sub folder availability date Install MongoDB pdo_sqlsrv SOCKS5 Web Server File Upload mssql-tools register_shutdown_function Symfony DevExpress JetBrain php-fpm sqlsrv Zend Framework ADDDATE height network interface Shadowsocks-Libev unixODBC-devel error_get_last Port 80 string Aura data INDENTIFIED BY password policy requirements SOCKS Web Development Fedora Media Writer msodbcsql Redis5 SVN Deepin jemalloc SQLAlchemy absolute FuelPHP mysqlclient Shadowsocks toggle convert Error Control Operator margin PHPUnit Framework ss5.passwd at-symbol IIS password SOCKET vps daemon process Fatal Errors MongoDB4 sudoers center DATE_SUB Phalcon SQL Server 2017 WiFi .htaccess