This article mainly introduces php curl upload file code example. This article gives two implementation methods, and gives the implementation code respectively. , friends in need can refer to it
Assume that the server-side upload file processing script upload.php:
The code is as follows:
print_r($_POST);
print_r($_FILES);
1. Use CURL’s default method
Copy the code. The code is as follows:
//If the php file is utf8 encoded and the system is GBK encoded, then you need to change the encoding, otherwise Php cannot find the file in the system
$file = realpath(mb_convert_encoding('Test picture.JPG','GBK','utf8'));
$file = realpath('temp.jpg'); //File to be uploaded
$fields['f'] = '@'.$file; // Add @ symbol in front to indicate uploading pictures
$ch =curl_init();
curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$content = curl_exec($ch);
echo $content;
2. An alternative approach. Sometimes we need to upload dynamically generated content to a remote server as a file, but we don’t want to build a temporary file in the local server. This way we have this alternative way of writing
The code is as follows:
$contents =<<< 'TEXT'
This is the file content, or it can be a binary image. The image needs to be modified to upload the file type
TEXT;
$varname = 'my'; //Upload to key
in $_FILES array$name = '3.txt';//File name
$type = 'text/plain';//File type
$key = "$varname"; filename="$namernContent-Type: $typern";
$fields[$key] = $contents;
$ch =curl_init();
curl_setopt($ch,CURLOPT_URL,'http://localhost/upload.php');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$content = curl_exec($ch);
echo $content;