【转】PHP 文件上传

 

How to upload image file to remote server with PHP cURL

In this example we learn how to upload static files to remote server using PHP cURL library.

We must know following functionality before we continue this example

  • PHP file upload functionality.
  • cURL function reference.
  • how to submit data to remote server with PHP cURL

Files and Folders

For this example we use three files

  • uploader.php -that recieves the files on to the remote server.
  • handler.php -is used to web based client to upload the file.
  • curl_handler.php -PHP cURL uploading client to upload file.

Since we use same host to both local and remote server ,we create seperate directories

  • local_files/ - these files will be uploaded to the remote server ,means to uploaded_files directory.
  • uploaded_files/ - these files are from the uploding client from both web based and PHP cURL based .

uploader.php

$upload_directory=dirname(__FILE__).'/uploaded_files/';
//check if form submitted
if (isset($_POST['upload'])) {  
    if (!empty($_FILES['my_file'])) { 
			//check for image submitted
    		if ($_FILES['my_file']['error'] > 0) { 
			// check for error re file
            echo "Error: " . $_FILES["my_file"]["error"] ;
        } else {
			//move temp file to our server            
			move_uploaded_file($_FILES['my_file']['tmp_name'], 
			$upload_directory . $_FILES['my_file']['name']);	
			echo 'Uploaded File.';
        }
    } else {
	        die('File not uploaded.'); 
			// exit script
    }
}

handler.php

 
<form method="post" enctype="multipart/form-data" action="uploader.php" id="form1">
  <input type="file" name="my_file" id="my_file"><input type="submit" value="Upload" name="upload" id="upload">
</form>
 
curl_handler.php
$local_directory=dirname(__FILE__).'/local_files/';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_URL, 'http://localhost/curl_image/uploader.php' );
	//most importent curl assues @filed as file field
    $post_array = array(
        "my_file"=>"@".$local_directory.'shreya.jpg',
        "upload"=>"Upload"
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); 
    $response = curl_exec($ch);
	echo $response;
 

 

 

 From 网上下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值