Home Uncategorized How To *Really* Upload Files With PHP

I’ve noticed that whenever I search for a “php upload script” or “how to upload files”, the first page of Gogle results is full of pages that tell you how to handle file uploads = letting users to upload something to your server. But what if you actually want to create a PHP script that will upload a file to another website?

So today I will show you a simple PHP upload script that simulates a web browser uploading a file through a file submission form. I’ll be using the excellent CURL library for this purpose.

So, without further ado, here’s the upload script :
 
 
/* This should be a fully qualified filename of the file you
want to upload. Relative filenames may not work. */
$filename = "/folder/file.txt";
 
/* The page that processes the upload. You can usually
find this in the "ACTION" field of the HTML form. */
 
/* The form fields and their values. */
$post_data = array(
    "field1" => "value1",
    "field2" => "value2",
    "file_field" => "@$filename"
);
/* The general format for file upload fields is '@file_name_here'.
If the form you're has multiple file fields you can upload
several files if you use the correct field names. */
 
$ch = curl_init($submit_url);
/* Follow redirects (optional) */
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
/* Use the "POST" method (possibly redundant) */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
 
/* Upload the file now */
$results = curl_exec($ch);
curl_close ($ch);
/* Now the $results variable contains any response the
$submit_url might have returned, or false if upload failed*/
 

Naturally you will need to modify the $submit_url and other variables to fit your situation.

Also note that in most practical cases you must "log in" to the target website before you can upload anything, so you might want to read my how to log in with PHP and CURL post.

You may also like

Leave a Comment