PHP7基于curl實現的上傳圖片功能
2019-10-08 10:24BroceHui PHP教程
這篇文章主要介紹了PHP7基于curl實現的上傳圖片功能,結合實例形式對比分析了php5.5之前與php7版本的curl圖片上傳功能相關實現與使用技巧,需要的朋友可以參考下
本文實例講述了PHP7基于curl實現的上傳圖片功能。分享給大家供大家參考,具體如下:
根據php版本不同,curl模擬表單上傳的方法不同
php5.5之前
02 | if (defined( 'CURLOPT_SAFE_UPLOAD' )) { |
03 | curl_setopt( $curl , CURLOPT_SAFE_UPLOAD, false); |
05 | $data = array ( 'file' => '@' . realpath ( $path )); |
06 | curl_setopt( $curl , CURLOPT_URL, $url ); |
07 | curl_setopt( $curl , CURLOPT_POST, 1 ); |
08 | curl_setopt( $curl , CURLOPT_POSTFIELDS, $data ); |
09 | curl_setopt( $curl , CURLOPT_RETURNTRANSFER, 1); |
10 | curl_setopt( $curl , CURLOPT_USERAGENT, "TEST" ); |
11 | $result = curl_exec( $curl ); |
12 | $error = curl_error( $curl ); |
php5.5之后,到php7
02 | curl_setopt( $curl , CURLOPT_SAFE_UPLOAD, true); |
03 | $data = array ( 'file' => new \CURLFile( realpath ( $path ))); |
04 | url_setopt( $curl , CURLOPT_URL, $url ); |
05 | curl_setopt( $curl , CURLOPT_POST, 1 ); |
06 | curl_setopt( $curl , CURLOPT_POSTFIELDS, $data ); |
07 | curl_setopt( $curl , CURLOPT_RETURNTRANSFER, 1); |
08 | curl_setopt( $curl , CURLOPT_USERAGENT, "TEST" ); |
09 | $result = curl_exec( $curl ); |
10 | $error = curl_error( $curl ); |
下面提供一個兼容的方法:
02 | if ( class_exists ( '\CURLFile' )) { |
03 | curl_setopt( $curl , CURLOPT_SAFE_UPLOAD, true); |
04 | $data = array ( 'file' => new \CURLFile( realpath ( $path ))); |
06 | if (defined( 'CURLOPT_SAFE_UPLOAD' )) { |
07 | curl_setopt( $curl , CURLOPT_SAFE_UPLOAD, false); |
09 | $data = array ( 'file' => '@' . realpath ( $path )); |
11 | curl_setopt( $curl , CURLOPT_URL, $url ); |
12 | curl_setopt( $curl , CURLOPT_POST, 1 ); |
13 | curl_setopt( $curl , CURLOPT_POSTFIELDS, $data ); |
14 | curl_setopt( $curl , CURLOPT_RETURNTRANSFER, 1); |
15 | curl_setopt( $curl , CURLOPT_USERAGENT, "TEST" ); |
16 | $result = curl_exec( $curl ); |
17 | $error = curl_error( $curl ); |
其中:
$path:為待上傳的圖片地址
$url:目標服務器地址
例如
upload.php示例:
2 | file_put_contents (time(). ".json" , json_encode( $_FILES )); |
3 | $tmp_name = $_FILES [ 'file' ][ 'tmp_name' ]; |
4 | $name = $_FILES [ 'file' ][ 'name' ]; |
5 | move_uploaded_file( $tmp_name , 'audit/' . $name ); |
希望本文所述對大家PHP程序設計有所幫助。