`

【转】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 网上下载

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics