Thursday, July 5, 2012

Uploding big file in php

Uploading larger/bigger files is difficult using http because it uses UDP protocol. However in shared hosting environment it is difficult to upload just 3-4 MB files. In order to uplaod larger document you can set upload_max_filesize and post_max_size in your htaccess file. But in order to update seamlessly you need to increase the execution time as well.

Set the following values according to your choice.

php_value upload_max_filesize 10M
php_value post_max_size 11M
php_value max_execution_time 600
php_value max_input_time 200

Note: Please make sure to use this .htaccess file in the same directory.
Note: Always mention greater upload_max_size than post_max_size because a post contain additional data also. However it is totally based on your wish to use.
Upload files using HTTP:

Here goes the script

move_uploaded_file($_FILES['userfile']['tmp_name'], 'path_to_directory/'.$_FILES['userfile']['name']);

If this does not solve your problem then probably you need to “upload your file using ftp”. Here I am providing a simple code to upload your file using ftp.
Upload files using FTP:

Here goes the script

$path = "path_to_directory/";
$ftp_server = "";
$ftp_user   = "USER";
$ftp_pass   = "PASSWORD";

// set up a connection to ftp server
$conn_id = ftp_connect($ftp_server);

//check for connection error
 echo “connection failed”;

// ftp login with username and password
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);

// check for login
if (!$login_result) {
       echo "Attempted to connect to $ftp_server for user $ftp_user.... failed";

// upload the file to the path specified
$upload = ftp_put($conn_id, $paths.'/'.$name, $file, FTP_BINARY);


If you are having a shared hosting environment than probably your outbound ftp is disabled. In that case you need to upload using cURL. Yes cURL is a great library with great power. Almost all big site using cURL in some way. Check the following script.
Upload files using cURL:

Here is the simplest script

$ch = curl_init();
$file = $_FILES['userfile']['tmp_name'];
$fp = fopen($file, 'r');
curl_setopt($ch, CURLOPT_URL, ''.$_FILES['userfile']['name']);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file));
curl_exec ($ch);

if you need to change the file permission after upload use chmod. As,

chmod("path_to_file" ,0755);

Upload checking could be done using php inbuilt funtion file_exists. As,


No comments: