PHP7基於curl實現的上傳圖片功能php技巧

來源:互聯網
上載者:User
這篇文章主要介紹了PHP7基於curl實現的上傳圖片功能,結合執行個體形式對比分析了php5.5之前與php7版本的curl圖片上傳功能相關實現與提示,需要的朋友可以參考下

本文執行個體講述了PHP7基於curl實現的上傳圖片功能。分享給大家供大家參考,具體如下:

根據php版本不同,curl類比表單上傳的方法不同

php5.5之前

$curl = curl_init();if (defined('CURLOPT_SAFE_UPLOAD')) {  curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);}$data = array('file' => '@' . realpath($path));//‘@' 符號告訴伺服器為上傳資源curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_POST, 1 );curl_setopt($curl, CURLOPT_POSTFIELDS, $data);curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);curl_setopt($curl, CURLOPT_USERAGENT,"TEST");$result = curl_exec($curl);$error = curl_error($curl);

php5.5之後,到php7

$curl = curl_init();curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);$data = array('file' => new \CURLFile(realpath($path)));url_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_POST, 1 );curl_setopt($curl, CURLOPT_POSTFIELDS, $data);curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);curl_setopt($curl, CURLOPT_USERAGENT,"TEST");$result = curl_exec($curl);$error = curl_error($curl);

下面提供一個相容的方法:

$curl = curl_init();if (class_exists('\CURLFile')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);$data = array('file' => new \CURLFile(realpath($path)));//>=5.5} else { if (defined('CURLOPT_SAFE_UPLOAD')) {  curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } $data = array('file' => '@' . realpath($path));//<=5.5}curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_POST, 1 );curl_setopt($curl, CURLOPT_POSTFIELDS, $data);curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);curl_setopt($curl, CURLOPT_USERAGENT,"TEST");$result = curl_exec($curl);$error = curl_error($curl);

其中:

$path:為待上傳的圖片地址

$url:目標伺服器地址

例如

$url="http://localhost/upload.php";$path = "/bg_right.jpg"

upload.php樣本:

<?php  file_put_contents(time().".json", json_encode($_FILES));  $tmp_name = $_FILES['file']['tmp_name'];  $name = $_FILES['file']['name'];  move_uploaded_file($tmp_name,'audit/'.$name);?>

您可能感興趣的文章:

PHP5.0~5.6 各版本相容性cURL檔案上傳功能執行個體分析php技巧

PHP區塊查詢實現方法分析php技巧

可相容php5與php7的cURL檔案上傳功能執行個體分析php技巧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.