Home > Backend Development > PHP Tutorial > php curl upload file code example_PHP tutorial

php curl upload file code example_PHP tutorial

WBOY
Release: 2016-07-13 09:55:59
Original
945 people have browsed it

php curl upload file code example

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;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/990996.htmlTechArticlephp curl upload file code example This article mainly introduces php curl upload file code example. This article gives two There are three implementation methods, and the implementation codes are given respectively. Friends in need can refer to...
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template