Php curl Upload File Code instance
This article mainly introduces the php curl file upload code example. This article provides two implementation methods and provides the implementation code respectively. For more information, see
Assume that the server uploads the file processing script upload. php:
The Code is as follows:
Print_r ($ _ POST );
Print_r ($ _ FILES );
1. Use the default CURL Method
Copy the Code as follows:
// If the Php file is utf8 encoded and the system is GBK encoded, it needs to be converted to the next encoding. Otherwise, Php cannot find this file in the system.
$ File = realpath (mb_convert_encoding ('test image. JPG ', 'gbk', 'utf8 '));
$ File = realpath('temp.jpg '); // the object to be uploaded
$ Fields ['F'] = '@'. $ file; // Add a @ symbol to upload an image.
$ 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. Alternative Approach: Sometimes we need to upload dynamically generated content to a remote server as a file, but we do not want to build temporary files on the local server. In this way, this alternative writing method is available.
The Code is as follows:
$ Contents = <'text'
This is the file content, or the Image Binary. You need to modify the upload file type for the image.
TEXT;
$ Varname = 'my'; // key uploaded to the $ _ FILES Array
$ Name = '3.txt '; // file name
$ Type = 'text/plain '; // file type
$ Key = "$ varname \"; filename = \ "$ name \ r \ nContent-Type: $ type \ r \ n ";
$ 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;