here is the code that i use to upload files and unzip them in a directory.
But the problem is that it seems to be very slow on files greater than 5MB.
I think it doesnt have to do with the network because it is in localhost computer.
Do I need to edit any parameter in php.ini file or apache or any other workarround?
$target_path = "../somepath/";
$target_path .= JRequest::getVar('uploadedDirectory')."/";
$target_Main_path= JRequest::getVar('uploadedDirectory')."/";
$folderName = $_FILES['uploadedfile']['name'];
$target_path = $target_path . basename($folderName);
//upload file
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path."/")) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
$zip = new ZipArchive;
$res = $zip->open($target_path);
$target_path = str_replace(".zip", "", $target_path);
echo $target_path;
if ($res === TRUE) {
$zip->extractTo($target_path."/");
$zip->close();
echo "ok";
} else {
echo "failed";
}
When handling file uploads ther are a lot of factors to consider. These include PHP settings:
max_input_time
max_execution_time
upload_max_filesize
post_max_size
Execution time can affect the upload if for example, you have a slow upload speed resulting in a timeout.
File size can cause problems if the upload is larger than the upload_max_filesize like wise if your file size + the rest of the post data exceeds post_max_size.
Zip uses a lot of memory in the archive/extraction processes and could easily exceed the memory allocated to PHP -so that would be worth checking as well.
I would start with this page and note some of the comments.
Related
I'm a PHP newbie and have written a script to process form uploads. It works for small files(less than 1Mb). However when I try to upload an ~4Mb pdf file it returns an error message. What am I doing wrong?
PS: I ran php_info, got the value of "upload_tmp_dir" and set it to a directory owned by the apache process(www-data)
My client-side code is
<form action="upper.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile"><br>
<input type="submit" value="Upload">
</form>
Upper.php contains
define("UPLOAD_DIR", "/var/www/html/upload/");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "Error is " . $myFile["error"];
//echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
Most probably you have wrong config in you php.ini file.
You need to set
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
its already described here: PHP change the maximum upload file size
You ned to set values in php.in file.
Open the file,
Find upload_max_filesize and post_max_size lines.
Change this two value. (M= MB)
; Maximum allowed size for uploaded files.
upload_max_filesize = 20M
; Must be greater than or equal to upload_max_filesize
post_max_size = 20M
Restart the sever for effect.
Note:
You can set any number. But not use any decimal value.
Open the php.ini file in NOTEPAD. Don't user wordpad or any word processor.
I am trying to upload PDF file using PHP Script, The below is my code. It works perfectly for any file which is less than 1 MB, but when I upload more than 1 MB, It goes to the else statement and gives this message - "Max File Size Upload Limit Reached, Please Select Any Other File".
I have already seen php.ini configuration, this is set at 16M. Please help
ini_set('upload_max_filesize', '16M');
ini_set('post_max_size', '16M');
//$ImageName=addslashes($_REQUEST['txtimagename']);
//$ImageTitle=addslashes($_REQUEST['txtimagetitle']);
$filepath="files/";
//$filedt=date("dmYhisu")."_.".pathinfo($_FILES['imagefile']['name'], PATHINFO_EXTENSION);
$filedt=$_POST['vehregistration'].".".pathinfo($_FILES['imagefile']['name'], PATHINFO_EXTENSION);
//basename($_FILES['photoimg']['name']);
$destination_img=$_POST['vehregistration'].".".pathinfo($_FILES['imagefile']['name'], PATHINFO_EXTENSION);
$filename=$filepath.$destination_img;
//$filename=$filepath.basename($_FILES['Photo']['name']);
//echo "$filepath".$_FILES[" imagefile "][" name "];
if(move_uploaded_file($_FILES["imagefile"]["tmp_name"], $filename))
{
//echo $filedt;exit;
//rename($_FILES['Photo']['tmp_name'],$filedt);
return $filedt;
}
else
{
echo "Max File Size Upload Limit Reached, Please Select Any Other File";
}
}
Add this in else condition $_FILES['imagefile']['error'] and see what is exact error . For more details http://php.net/manual/en/features.file-upload.errors.php
Instead of using ini_setuse $_FILES["imagefile"]["size"]
$fileSize = $_FILES["imagefile"]["size"]; // File size in bytes
$maxFileSz = 16777216; // set your max file size (in bytes) in this case 16MB
if($fileSize <= $maxFileSz) {
// everything is okay... keep processing
} else {
echo 'Max File Size Upload Limit Exceeded, Please Select Any Other File';
}
$image = $_FILES['picture']['name'];
$id=$_SESSION['id'];
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['picture']['name']) ;
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "mainimage/";
//This combines the directory, the random file name, and the extension
$target = $target . $id.".".$ext;
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
{
echo ("This is your new profile picture!");
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
for some reason the "else" keeps showing up (there was a problem uploading the file). I put comments in everything that I am trying to do. please help! thanks!
To close the question as per OP's request.
The issue is that you need to increase the maximum size for uploads. PHP's default is usually 2M and you are most probably trying to upload a file larger than what the maximum setting is set to.
This can be achieved in two ways.
By editing your php.ini file with the following settings:
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
or via an .htaccess file placed in the root of your server:
php_value upload_max_filesize 20M
php_value post_max_size 30M
I am working with Files and Folders within CakePHP. Now everything works fine and in the way I want it to. However, when Zipping files, I get the following error message :
Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 240047685 bytes)
Now zipping smaller files, its fine! I have even done files in size of around 10MB without any issues, however zipping that are larger in size seem to have an issue.
Now I have added the following to my .htaccess file and made a php.ini file as I thought that might be the issue.
php_value upload_max_filesize 640000000M
php_value post_max_size 640000000M
php_value max_execution_time 30000000
php_value max_input_time 30000000
Until I found some posts pointing at the fact that PHP as a 4GB file limit. Well even if that is the case, why does my zip file not do this file (which is only about 245mb).
public function ZippingMyData() {
$UserStartPath = '/data-files/tmp/';
$MyFileData = $this->data['ZipData']; //this is the files selected from a form!
foreach($MyFileData as $DataKey => $DataValue) {
$files = array($UserStartPath.$DataValue);
$zipname = 'file.zip';
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
$path = $file;
if(file_exists($path)) {
$zip->addFromString(basename($path), file_get_contents($path));
} else {
echo"file does not exist";
}
} //End of foreach loop for $files
} //End of foreach for $myfiledata
$this->set('ZipName', $zip_name);
$this->set('ZipFiles', $MyFileData);
$zip->close();
copy($zip_name,$UserStartPath.$zip_name);
unlink($zip_name); //After copy, remove temp file.
$this->render('/Pages/download');
} //End of function
Any ideas of where I am going wrong? I will state that this is NOT my code, I found bits of it on others posts and changed it to fit my needs for my project!
All help most welcome...
Thanks
Glenn.
I think that ZipArchive loads your file in memory, so you have to increase the memory_limit parameter in php.ini.
To avoid consuming all the memory of your server and drop performance, if your file is big, a better (but far from be the best) solution should be:
public function ZippingMyData() {
$UserStartPath = '/data-files/tmp/';
$MyFileData = $this->data['ZipData']; //this is the files selected from a form!
foreach($MyFileData as $DataKey => $DataValue) {
$files = array($UserStartPath.$DataValue);
$zip_name = time().".zip"; // Zip name
// Instead of a foreach you can put all the files in a single command:
// /usr/bin/zip $UserStartPath$zip_name $files[0] $files[1] and so on
foreach ($files as $file) {
$path = $file;
if(file_exists($path)) {
exec("/usr/bin/zip $UserStartPath$zip_name basename($path)");
} else {
echo"file does not exist";
}
} //End of foreach loop for $files
} //End of foreach for $myfiledata
$this->render('/Pages/download');
} //End of function
or similar (depends on your server). This solution has only two limits: disk space and zip limitations.
I apologize for the poor quality of my code and for any error.
Whenever I try to upload a ZIP File via PHP, the Filesize is 0.
Everything else works: 7z, rar, png, xml
for example (I output filesize and location for testing):
File Location: /tmp/phpKNortG/feba81fed1ff5d2c04aa0c42975eb94f.7z
Filesize: 1284
File Location: /tmp/phpEWrmLT/feba81fed1ff5d2c04aa0c42975eb94f.zip
Filesize: 0
My form has enctype="multipart/form-data" and the file is definitely not too big to be uploaded. (I've also set the memory limit to 128 MB to make sure it's not that)
ini_set('memory_limit', '128M');
set_time_limit(0);
$session_id = "3423840093480344";
mkdir('uploaded_files/' . $session_id);
for($i = 0; $i < count($_FILES['backup_file']['name']); $i++) {
$file_name = $_FILES['backup_file']['name'][$i];
$file_type = $_FILES['backup_file']['type'][$i];
$file_error = $_FILES['backup_file']['error'][$i];
$file_size = $_FILES['backup_file']['size'][$i];
$file_tmp = $_FILES['backup_file']['tmp_name'][$i];
print($file_name . "<br />");
print($file_type . "<br />");
print($file_error . "<br />");
print($file_size . "<br />");
print($file_tmp . "<br />");
if($file_error != 0) {
echo "Error-Code: ".$file_error;
continue;
}
move_uploaded_file($file_tmp, 'uploaded_files/' . $session_id);
}
The following code outputs this:
feba81fed1ff5d2c04aa0c42975eb94f.zip
application/zip
0
0
/tmp/phpEWrmLT
It even recognizes the MIME-Type, but the file is always zero bytes in size. (even before moving it with move_uploaded_file)
Is there any server setting that could prevent .zip files to be uploaded?
The memory_limit setting has no bearing on file uploads.
What are the values for your post_max_size and upload_max_filesize and how does the .zip filesize compare with those values?