cannot upload and save large image files on PHP server - php

I have written the php upload image files to php server.
When small images within 100kB, it is success.
But when over 500KB, it is failed and said no data received on server.
I also do not know why. No file saved in php server of this uploading.
Do you know how to solve??
function uploadImages($input, $file)
{
if($input == null || $input == "")
{
return false;
}
$stringVal = $input;
$value = str_replace('data:image/png;base64,', '', $stringVal);
if ($this->check_base64_image($value) == false) {
return false;
}
$actualFile = base64_decode($value);
$img = imagecreatefromstring($actualFile);
$imgSize = getimagesize('data://application/octet-stream;base64,' . base64_encode($actualFile));
if ($img == false) {
return false;
}else
{
/*** maximum filesize allowed in bytes ***/
$max_file_length = 100000;
log_message('debug', 'PRE UPLOADING!!!!!!!!');
if (isset($img)){
log_message('debug', 'UPLOADING!!!!!!!!');
// check the file is less than the maximum file size
if($imgSize['0'] > $max_file_length || $imgSize['1'] > $max_file_length)
{
log_message('debug', 'size!!!!!!!!'.print_r($imgSize));
$messages = "File size exceeds $max_file_size limit";
return false;
}else if (file_exists($file)) {
return false;
}else
{
file_put_contents($file, $actualFile);
return true;
}
}
}
}

try this,
ini_set('post_max_size',52428800); // 50 MB
ini_set('upload_max_filesize',52428800) // 50 MB

Related

PHP AJAX image upload - I need to limit quota to a folder

I am using Ajax PHP to upload images to a folder, but I want to limit that space to 50 MB. I think I'm on the right track, but the code does not work for me. If you can help me.
I think the error should be in "if ($ size> 52428800) {"
Thank you
/*** Calling from ajax to add the gallery new an image****/
public function Addgallery() {
$size = 0;
$files= glob($directory.$folder_gallery.'/*');
foreach($files as $path){
is_file($path) && $size += filesize($path);
is_dir($path) && get_dir_size($path);
}
return $size;
if ($size > 52428800 ) {
echo alert("Your quota on disk does not allow the upload of images. Please erase images that you do not use.");
} else {
$this->_upload_file($this->_base_path .'/images/gallery/', array( '.png', '.jpg', '.jpeg', '.gif' ), 'addgallery');
}
}
You are returning $size on line 9. Everything below the return statement will be skipped.
If you move return $size below the else, your code should work.
/*** Calling from ajax to add the gallery new an image****/
public function Addgallery() {
$size = 0;
$files = glob($directory.$folder_gallery.'/*');
foreach($files as $path){
is_file($path) && $size += filesize($path);
is_dir($path) && get_dir_size($path);
}
if ($size > 52428800){
echo alert("Your quota on disk does not allow the upload of images. Please erase images that you do not use.");
} else {
$this->_upload_file($this->_base_path .'/images/gallery/', array( '.png', '.jpg', '.jpeg', '.gif' ), 'addgallery');
}
return $size;
}
Note: alert() is not a PHP function, just in case you didn't create that function

All images not uploading in multiple images upload

I'm trying to upload multiple files and it uploads them well. But I am also checking for errors (type and size) and catch errors in an array variable. When I select, lets say, 3 images and one of them has some error (more size than allowed and/or type not allowed) and its the first image then the other two images also don't get uploaded. If the file with error is second one then only first one gets uploaded, and when error image is last one the first two get uploaded. What I'm trying to do is even if there is error in one or more images then other valid images should get uploaded no matter the order in which they are selected.
Here is my script:
function filesupload($files) // here files is $_FILES array
{
$i = 0;
$errors = array();
$maxfilesize = 1*1024*1024; // 1 MB
$num = count($files['name']);
$allowed_types = array('image/jpeg', 'image/png');
foreach($files['tmp_name'] as $key=>$tmp_name)
{
$tmpname = $files['tmp_name'][$key]; // file temp name
$fsize = $files['size'][$key]; // file size
if(!empty($files['name'][$key]))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $files['tmp_name'][$key]); // file mime type
}
//validations for file type and size
// no file selected
if(empty($files['name'][$key]))
{
$errors[] = 'Select at least one file for uploading';
}
// file type not allowed
if(in_array($ftype, $allowed_types) === false)
{
$errors[] = 'One or more files have invalid file extension';
}
// file size validation
if($fsize > $maxfilesize)
{
$errors[] = 'Size of one or more files is more than allowed';
}
// if no errors uploaded file(s)
if(empty($errors))
{
$path = 'images/';
$newfilename = time().'_'.rand(100000, 999999).'_'.$files['name'][$key];
$move = move_uploaded_file($tmpname, $path.$newfilename);
if($move)
{
$i = $i + 1;
if($i == $num)
{
$msg = 'Files uploaded';
return $msg;
}
}
}
elseif(!empty($errors))
{
return $errors;
}
}
}
In the loop you have checked $error[]. So when the error is in first file so that array will not be blank and other images will not upload.
Try as below :
function filesupload($files) // here files is $_FILES array
{
$i = 0;
$errors = array();
$maxfilesize = 1*1024*1024; // 1 MB
$num = count($files['name']);
$allowed_types = array('image/jpeg', 'image/png');
foreach($files['tmp_name'] as $key=>$tmp_name)
{
$tmpname = $files['tmp_name'][$key]; // file temp name
$fsize = $files['size'][$key]; // file size
if(!empty($files['name'][$key]))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $files['tmp_name'][$key]); // file mime type
}
//validations for file type and size
// no file selected
if(empty($files['name'][$key]))
{
$errors[$key] = 'Select at least one file for uploading';
}
// file type not allowed
if(in_array($ftype, $allowed_types) === false)
{
$errors[$key] = 'One or more files have invalid file extension';
}
// file size validation
if($fsize > $maxfilesize)
{
$errors[$key] = 'Size of one or more files is more than allowed';
}
// if no errors uploaded file(s)
if(!isset($errors[$key]))
{
$path = 'images/';
$newfilename = time().'_'.rand(100000, 999999).'_'.$files['name'][$key];
$move = move_uploaded_file($tmpname, $path.$newfilename);
if($move)
{
$i = $i + 1;
if($i == $num)
{
$msg = 'Files uploaded';
return $msg;
}
}
}
}
if(!empty($errors))
{
return $errors;
}
}
I have changed error message array from $errors[] to $errors[$key] and checked the same. So if you have 4 file input and 1st and 3rd are having error then 2nd and 4th will upload and you will get error in 0th and 2nd index of array.

valums ajax-upload broken script after xhr.send(file) - sometimes works, and sometimes does not

I searched for solution to this the better part of the day and I'm still in the dark. For a client of mine I created a simple web gallery for uploading images and I'm using valums file uploader. Till now I didn't have any problems with it on any other site I created, except miss-configuration which I solved some time ago.
So, what is the problem?
When I upload a image with filesize below 260KB it works fine. But, when I'm uploading a bigger image, it doesn't throw me back any error. I just get an empty thumbnail, because image wasn't uploaded.
When I open Chrome Console, this is what I see:
POST http://designflowstudio.com/gallery2/include/upload.php?url=uploads%2Fe558c4dfc2a0f0d60f5ebff474c97ffc&fid=7&qqfile=316267269718409738080100.jpg 403 (Forbidden) fileuploader.js:1463
POST http://designflowstudio.com/gallery2/include/upload.php?url=uploads%2Fe558c4dfc2a0f0d60f5ebff474c97ffc&fid=7&qqfile=3.jpg 403 (Forbidden) fileuploader.js:1463
On some occasions I got 413 error "Request entity too large".
Let me say that this problem really annoys me because the script works well on my local web server (apache) and on my web server. Here I can upload as may and as big images as I can find, but on the client's web server...
If anyone have time and will to help me, here is the JavaScript that I use to call the valums uploader:
function createUploader(){
var uploader = new qq.FileUploaderBasic({
debug: true,
multiple: true,
allowedExtensions: [<?php $tmp=".";foreach($allowedExt as $ext){$tmp.="'$ext', ";}echo substr($tmp,1,strlen($tmp)-3);?>],
button: document.getElementById('uploadDiv'),
action: '<?php echo$home;?>include/upload.php',
sizeLimit: <?php echo$sizeLimit;?>,
forceMultipart: true,
params: {'url':'uploads/<?php echo$g['path'];?>','fid':'<?php echo$g['id'];?>'},
onSubmit: function(id, fName){$('#upload-list').append('<div id="upload-list-'+id+'" class="gallery" rel="'+fName+'"><div class="progress'+id+'"></div>');$('.progress'+id).progressbar({value:0})},
onProgress: function(id, fName, loaded, total){
var p = 0;
p = parseFloat(loaded/total*100);
if(isNaN(p)) p = '';
$('.progress'+id).progressbar("option","value",p);
},
onComplete: function(id,fName,json){
if(json.error){
$('#upload-list-'+id).html(fName+'<br />'+json.error);
}else{
$('#upload-list-'+id)
.attr("rel",json.fname)
.html('<img class="cmd" id="deleteImg" rel="'+json.id+'" src="<?php echo$home;?>images/delete.png" title="Delete picture" /><img class="img" src="<?php echo$home;?>uploads/<?php echo$g['path'];?>/th_'+json.fname+'" /><input class="ut" type="text" name="name" value="'+json.name+'" /><input class="ud" type="text" name="desc" /><div class="cl"></div>')
.attr("id",json.id);
}
},
onError: function(id,fName,error){
console.log(id+' '+fName+' '+error);
}
});
}
window.onload = createUploader;
And here is my PHP for server processing the file:
require("config.php");
require("SimpleImage.php");
ini_set("log_errors" , "1");
ini_set("error_log" , "php-errors-upload.log");
ini_set("display_errors" , "1");
/**
* Handle file uploads via XMLHttpRequest
*/
class qqUploadedFileXhr {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()){
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
return true;
}
function getName() {
return $_GET['qqfile'];
}
function getSize() {
if (isset($_SERVER["CONTENT_LENGTH"])){
return (int)$_SERVER["CONTENT_LENGTH"];
} else {
throw new Exception('Getting content length is not supported.');
}
}
}
/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
class qqUploadedFileForm {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
return false;
}
return true;
}
function getName() {
return $_FILES['qqfile']['name'];
}
function getSize() {
return $_FILES['qqfile']['size'];
}
}
class qqFileUploader {
private $allowedExtensions = array();
private $sizeLimit = 20485760;
private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 20485760){
$allowedExtensions = array_map("strtolower", $allowedExtensions);
$this->allowedExtensions = $allowedExtensions;
$this->sizeLimit = $sizeLimit;
$this->checkServerSettings();
if (isset($_GET['qqfile'])) {
$this->file = new qqUploadedFileXhr();
} elseif (isset($_FILES['qqfile'])) {
$this->file = new qqUploadedFileForm();
} else {
$this->file = false;
}
}
private function checkServerSettings(){
$postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
}
}
private function toBytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/**
* Returns array('success'=>true) or array('error'=>'error message')
*/
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
chdir("../");
if(!file_exists($uploadDirectory)){
foreach(explode("/",$uploadDirectory) as $val){
if(empty($val2)){$val2=$val."/";}else{$val2.=$val."/";}
if($val<>""){if(!file_exists($val2)){mkdir($val2);}}
}
}
if (!is_writable($uploadDirectory)){
return array('error' => "Server error. Upload directory isn't writable.");
}
if (!$this->file){
return array('error' => 'No files were uploaded.');
}
$size = $this->file->getSize();
if ($size == 0) {
return array('error' => 'File is empty');
}
if ($size > $this->sizeLimit) {
return array('error' => 'File is too large');
}
$pathinfo = pathinfo($this->file->getName());
$filename = md5($pathinfo['filename'].mt_rand());
//$filename = md5(uniqid());
$ext = strtolower($pathinfo['extension']);
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
}
if(!$replaceOldFile){
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}
if ($this->file->save($uploadDirectory .'/'. $filename . '.' . $ext)){
global $sql_images;
$md=md5($filename);
$tmp=mysql_query("SELECT `order` FROM `$sql_images` WHERE `gid`='{$_REQUEST['fid']}' ORDER BY `order` DESC");
if($tmp&&mysql_num_rows($tmp)>0){$i=mysql_result($tmp,0);$i++;}else{$i=0;}
mysql_query("INSERT INTO `$sql_images` (`order`,`gid`,`name`,`path`) VALUES ('$i','{$_REQUEST['fid']}','{$pathinfo['filename']}','$filename.$ext')");
$image = new SimpleImage();
$image->load($uploadDirectory.'/'.$filename.'.'.$ext);
$image->resizeToWidth(150);
$image->save($uploadDirectory.'/th_'.$filename.'.'.$ext);
return array('success'=>true,'fname'=>$filename.".".$ext,'name'=>$pathinfo['filename'],'id'=>mysql_insert_id());
} else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
}
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 20*1024*1024;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($_REQUEST['url']);
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
Let me say again, all the calls to MySQL, files with require() are valid. The scripts work on two other servers, but on this one, not.
Thank you for your time and will to help.
You have some configuration issues on your server if it is choking due to the content-type header. Instead of commenting out this line, to work around this messed up server, you should perhaps try to set the forceMultipart option to true, assuming your server can handle multipart-encoded requests correctly. This all assumes you are using the 2.1-SNAPSHOT version of the uploader, as the option I mentioned first appeared in this version.

PHP File Type Validation

I wrote the following php function to upload files but I'm having a hard time with the array of allowed file types. If I assign just one file type i.e. image/png, it works fine. If I assign more than one, its not working. I use the in_array() function to determine the allowed file types but I can't figure out how to use it properly.
Thank you!
function mcSingleFileUpload($mcUpFileName, $mcAllowedFileTypes, $mcFileSizeMax){
if(!empty($mcUpFileName)){
$mcIsValidUpload = true;
// upload directory
$mcUploadDir = UPLOAD_DIRECTORY;
// current file properties
$mcFileName = $_FILES[$mcUpFileName]['name'];
$mcFileType = $_FILES[$mcUpFileName]['type'];
$mcFileSize = $_FILES[$mcUpFileName]['size'];
$mcTempFileName = $_FILES[$mcUpFileName]['tmp_name'];
$mcFileError = $_FILES[$mcUpFileName]['error'];
// file size limit
$mcFileSizeLimit = $mcFileSizeMax;
// convert bytes to kilobytes
$mcBytesInKb = 1024;
$mcFileSizeKb = round($mcFileSize / $mcBytesInKb, 2);
// create array for allowed file types
$mcAllowedFTypes = array($mcAllowedFileTypes);
// create unique file name
$mcUniqueFileName = date('m-d-Y').'-'.time().'-'.$mcFileName;
// if file error
if($mcFileError > 0)
{
$mcIsValidUpload = false;
mcResponseMessage(true, 'File error!');
}
// if no file error
if($mcFileError == 0)
{
// check file type
if( !in_array($mcFileType, $mcAllowedFTypes) ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'Invalid file type!');
}
// check file size
if( $mcFileSize > $mcFileSizeLimit ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'File exceeds maximum limit of '.$mcFileSizeKb.'kB');
}
// move uploaded file to assigned directory
if($mcIsValidUpload == true){
if(move_uploaded_file($mcTempFileName, $mcUploadDir.$mcUniqueFileName)){
mcResponseMessage(false, 'File uploaded successfully!');
}
else{
mcResponseMessage(true, 'File could not be uploaded!');
}
}
}
}
}
//mcRequiredFile('mcFileUpSingle','please select a file to upload!');
mcSingleFileUpload('mcFileUpSingle', 'image/png,image/jpg', 2097152);
Change this line:
$mcAllowedFTypes = array($mcAllowedFileTypes);
To this:
$mcAllowedFTypes = explode(',',$mcAllowedFileTypes);
Don't rely on the clent file type from $_FILES which is unsafe, get it from the file content.
Then define your allowed file types, check if the upload file type in your white list.
if(in_array(mime_type($file_path),$allowed_mime_types)){
// save the file
}
$allowed_mime_types = array(
'image/jpeg',
'image/jpg',
'image/png',
'image/gif',
'video/mp4'
);
/*
For PHP>=5.3.0, you can use php's `finfo_file`([finfo_file](https://www.php.net/manual/en/function.finfo-file.php)) function to get the file infomation about the file.
For PHP<5.3.0, you can use your's system's `file` command to get the file information.
*/
function mime_type($file_path)
{
if (function_exists('finfo_open')) {
$finfo = new finfo(FILEINFO_MIME_TYPE, null);
$mime_type = $finfo->file($file_path);
}
if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {
ob_start();
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);
if ($return > 0) {
ob_end_clean();
$mime_type = null;
}
$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
$mime_type = null;
}
$mime_type = $match[1];
}
return $mime_type;
}

image upload problem

I wrote a function to resize and upload images...it works, but only for one image. So if I call the function three times, I end up with 3 copies of the last image.....
function uploadImage($name,$width,$height,$size,$path='content/user_avatars/')
{
//===================================================
//Handle image upload
$upload_error=0;
//Picture
$img = $_FILES[$name]['name'];
if($img)
{
$file = stripslashes($_FILES[$name]['name']);
$ext = strtolower(getExt($file));
if($ext!='jpg' && $ext!='jpeg' && $ext!='png' && $ext!='gif')
{
$error_msg = "Unknown extension";
$upload_error = 1;
return array($upload_error,$error_msg);
}
if(filesize($_FILES[$name]['tmp_name'])>$size*1024)
{
$error_msg = "Max file size of ".($size*1024)."kb exceeded";
$upload_error = 2;
return array($upload_error,$error_msg);
}
$newFile = time().'.'.$ext;
resizeImg($_FILES[$name]['tmp_name'],$ext,$width,$height);
$store = copy($_FILES[$name]['tmp_name'],$path.$newFile);
if(!$store)
{
$error_msg = "Uploading failed";
$upload_error = 3;
return array($upload_error,$error_msg);
}
else
{
return array($upload_error,$newFile);
}
}
}
//=========================================================================================
//Helper Functions
function getExt($str)
{
$i = strpos($str,".");
if(!$i)
{
return "";
}
$l = strlen($str)-$i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function resizeImg($file,$ext,$width,$height)
{
list($aw,$ah) = getimagesize($file);
$scaleX = $aw/$width;
$scaleY = $ah/$height;
if($scaleX>$scaleY)
{
$nw = round($aw*(1/$scaleX));
$nh = round($ah*(1/$scaleX));
}
else
{
$nw = round($aw*(1/$scaleY));
$nh = round($ah*(1/$scaleY));
}
$new_image = imagecreatetruecolor($nw,$nh);
imagefill($new_image,0,0,imagecolorallocatealpha($new_image,255,255,255,127));
if($ext=='jpg'||$ext=='jpeg')
{
$src_image = imagecreatefromjpeg($file);
}
else if($ext=='gif')
{
$src_image = imagecreatefromgif($file);
}
else if($ext=='png')
{
$src_image = imagecreatefrompng($file);
}
imagecopyresampled($new_image,$src_image,0,0,0,0,$nw,$nh,$aw,$ah);
if($ext=='jpg'||$ext=='jpeg')
{
imagejpeg($new_image,$file,100);
}
else if($ext=='gif')
{
imagegif($new_image,$file);
}
else if($ext=='png')
{
imagepng($new_image,$file,9);
}
imagedestroy($src_image);
imagedestroy($new_image);
}
I have a form with two upload fields, 'face_pic' and 'body_pic', and I want to upload these two to the server and resize them before storing. Any ideas?
You use the current time to determine the resulting name of the file. The function executes so fast, that time() yields the same result for both images.
Use some other means to disambiguate the resulting name of the file. Best choice would be to pass the resulting name as a parameter. That way, the environment can determine how the file is named. Candidates are primary key of the meta information (in case they are stored in the database), original file name, universally unique identifier.
In any case, check whether the resulting name is a legal filename on your platform and that you do not accidentally overwrite files.
Also consider using move_uploaded_file to move the file from the temporary location to the destination. That function does some security checking.
md5(microtime())
Try naming it like this.
Or try something like this...
function slikeAvatar($slika,$id = 0){
copy($slika, "avatari/{$id}l.jpg");
$gfx = new Thumbnail($slika, 200);
$gfx->save("avatari/{$id}.jpg");
unset($gfx);
$gfx = new Thumbnail($slika, 75);
$gfx->save("avatari/{$id}s.jpg");
unset($gfx);
slikeCrop("avatari/{$id}s.jpg","avatari/{$id}s.jpg");
}
slike = images

Categories