PHP-php Tutorial

Source: Internet
Author: User
This article mainly introduces the phpcurl file upload code example. This article provides two implementation methods and the implementation code respectively, for more information, see upload. php:

The code is as follows:


<? Php

Print_r ($ _ POST );
Print_r ($ _ FILES );


1. use the default CURL method

The code is 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 practicesSometimes we need to upload the dynamically generated content to the 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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.