Assume that the server-side upload file processing script upload.php:
Copy code The code is as follows:
print_r($_POST);
print_r($_FILES);
1. Use CURL’s default method
Copy 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 this 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 the @ symbol in front to indicate uploading images
$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 as files to the remote server, but do not want to build temporary files in the local server. This way we have this alternative way of writing
Copy code The code is as follows:
$contents =<<< 'TEXT'
Here is the file content, it can also be a binary image. The image needs to be modified to upload the file type
TEXT;
$varname = 'my';//key uploaded to the $_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;