Giter VIP home page Giter VIP logo

Comments (34)

samayo avatar samayo commented on June 2, 2024

you can save the original dimention with getHeight() and getWidth() methods and then resize it

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

Thanks @samayo but I wrote my question wrongly, what I was after is after uploading pic copy and move it to a different folder then resize it..

But I coded a bit to accomplish the copy and move it then used bulletproof resizing method...

Works nicely , but I encounter some problems, it seems that Bulletproof fails report that there was an error with the size or the weight of the processing picture..
example;
`
//mypic is the name of picture

$image = new Bulletproof\Image($_FILES);
$image->setSize( 1000, 716800);
$image->setDimension(1080, 1080);

$image->setLocation(UPLOADDIR . 'somefolder', 0777);
// We expect $image['mypic']
if( $image['mypic'] ){
// do the upload
}else{
// I am expecting $image['error'] to be populated
// but I got nothing and script don't log why it failed
}
`

from bulletproof.

samayo avatar samayo commented on June 2, 2024

please make sure to rename "profilepic" to whatever you have named your html input file name. because you have also mentioned "mypic" is the name of your picture. I guess I have to see the html code and full php code to make sure the error isn't trival

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

@samayo,
My bad, mypic is being used as example and my code the correct name is applied,
The script upload fine it is when either the weight or dimentions goes over the defined properties that fails silenly..

I am using php7 ... thanks..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

can you paste the whole code? I will try later today to see what the problem is.

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024
        function uploadPhoto( $files, $userfolder, $saveinSubfolder ){
   		global $picSize, $imgtype;

   		$res 	 = ['success' => false , 'msg' => null];//default response
   		$picname = $userfolder . round(microtime(true) );

   		$image = new Bulletproof\Image($files);

   		$image->setName($picname);

   		$image->setSize( 200, 716800 );
   		// set the max width/height limit of images to upload (limit in pixels)
		$image->setDimension(1080, 1080);
   		// define allowed mime types to upload
		$image->setMime($imgtype);

		// pass name (and optional chmod) to create folder for storage
		$image->setLocation( UPLOADDIR . $userfolder, 0777 );

   		
   		if( $image['profilepic'] ){

		    $upload = $image->upload(); 
			
		    if( $upload ){
		    	$newfilename = $picname .  '.' . $image->getMime();
		    	$avatar_path = UPLOADDIR . $userfolder . '/' . $saveinSubfolder;
		    	$vatar_name  = $avatar_path . '/' . $newfilename;
		        //echo $image->getMime();
		        // create folder if doesn't exit
		        if( !is_dir($avatar_path) ){
		        	mkdir( $avatar_path, 0777, true);
		        }
		        // move it if there isn't problem
		        if( copy( $image->getFullPath(), $vatar_name ) ){

		        	try {

			        	$resize = Bulletproof\resize(
							$vatar_name, 
							$image->getMime(),
							$image->getWidth(),
							$image->getHeight(),
							50,
							50,
							true
						);

		        	} catch( Exception $e ) {

		        		$res['msg']	=	'There was an internal error, please report to Admin.';
						return $res;

		        	}

		        	// we don't have exception then success
		        	$uploaded = [ 'success' => true, 'name' => $newfilename ];
					return $uploaded;

		        }else{
		        	// if errors remove the folder. this part still developed
		        	if( !rmdir($image->getLocation()) ){
		        		error_log('Directory could\'not be removed ' . $image->getLocation() );
		        		$res['msg']	=	'There was an internal error, please report to Admin.';
						return $res;
		        	}
		        }
		        
		    }else{
		        $res['msg']	=	$image["error"];// won't report anything..
				return $res;
		    }
		}

Thanks..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

Ok, I was just about to try this, until I noticed you are also resizing the image inside upload. I think there is nothing wrong with Bulletproof. I am sure the problem is somewhere in the size. You are not maybe resizing the image or you are unable to locate it after it's resized. Also, I think you might have misnamed $avatar_name because you are passing the the Bulletproof\resize method the name $vatar_name which seem are forgetting the letter a.

Either way, if the above doesn't fix the problem. Please try to go over it again. This time create just the upload function and add the resize function with care

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

This part here is the folder where we want a copy of our picture to go then get it resized

$newfilename = $picname .  '.' . $image->getMime();
 $avatar_path = UPLOADDIR . $userfolder . '/' . $saveinSubfolder;
 $vatar_name  = $avatar_path . '/' . $newfilename;

$image->getFullPath() is passed to copy:method so it can copy and be saved to $avatar_name so we don't touch our original picture at $image->getFullPath() once we have our copy saved then we pass it the copied picture and we resize it Bulletproof\resize:method ..

Everything there is working as intended what is not working is if( $image['profilepic'] ) not giving you any error at else conditional why is not set at that point and why goes silently.

Sorry I was not clear with code..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

The way I understand it. You want to upload an image, and if uploaded is success you want to keep a resized copy of image as avatar in a separated dir. If that is the case, then I looked at your code and most of what you have put was redundant like $picname = $userfolder . round(microtime(true)); when you could have used "copy_" . $image->getName() for the avatar., and if($image['profilepic']) { }else{ ... } the else{} doesn't make sense. It won't show anything if there is no name='profilepic' in the HTML form, why would it? otherwise it will show an error for every form submit in your page.

Now, I just wrote a code that does upload and then copy + resize. It will let you upload the original image into a folder called image_path and if success it will create a folder called avatar_path and make a resized copy of the image. I have tested it and it works.

image

html form

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
    <input type="file" name="profilepic"/>
    <input type="submit" value="upload"/>
</form>

php code

<?php 

require __DIR__. '/src/bulletproof.php';
require __DIR__. '/src/utils/func.image-resize.php';

// init
$image = new Bulletproof\Image($_FILES);

// where to keep uploaded image
$image_path = __DIR__ . '/image_path/'; 
// where to keep a resized copy
$avatar_path 	= __DIR__ . '/avatar_path'; 

$image->setLocation($image_path);
// set size
$image->setSize(200, 716800 );
// set the max width/height limit of images to upload (limit in pixels)
$image->setDimension(1080, 1080);
// define allowed mime types to upload
$image->setMime(['gif', 'jpeg', 'jpg', 'png']);

if($image['profilepic']){
	$upload = $image->upload(); 
	if($upload){

		// if image is uploaded get the image full path to make a copy
		$full_path = $upload->getFullPath(); 

		if(!is_dir($avatar_path)){
			mkdir( $avatar_path, 0777, true);
		}

		// get[prepare] full path for the avatar
		$avatar_image = $avatar_path . "/avatar_" .$image->getName() .".". $image->getMime(); 

		// if copy is success, then resize it
		if(copy( $full_path, $avatar_image)){
				$resize = Bulletproof\resize(
					$avatar_image, 
					$image->getMime(),
					$image->getWidth(),
					$image->getHeight(),
					50,
					50,
					true
				);
		}
	}else{
		echo "Image uploaded failed!! Reason: " . $image['error']; 
	}
}

from bulletproof.

samayo avatar samayo commented on June 2, 2024

let me know how it goes

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

If that is the case, then I looked at your code and most of what you have put was redundant like $picname = $userfolder . round(microtime(true));

That because I want a new name, with the folder I set for them...

<input type="file" name="profilepic"/> It is already in my HTML so I expect to be defined..

I have tested your code, cleaner and better than mine,
set $image->setSize(200, 716800000); and $image->setDimension(5000, 5000);
$image['profilepic'] with a 1920x1080 967kb is coming false , but when I try to get the error is an empty string..

So still failing, thanks for kind help

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

I have debugged a bit more..
This is a pic that passes the test
array(1) { ["profilepic"]=> array(5) { ["name"]=> string(29) "ampm_exterior_3_eng_short.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpZfLjDa" ["error"]=> int(0) ["size"]=> int(23440) } }

and this one is one that doesn't pass the test which is the same I being using and similar to other pictures I have..

array(1) { ["profilepic"]=> array(5) { ["name"]=> string(13) "thisatest.jpg" ["type"]=> string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(2) ["size"]=> int(0) } }

So it seems that my server is not allowing the file somehow, will hunting down php.ini now to see why is that..(disregard).
So is in the form..
And further reading http://www.php.net/manual/en/features.file-upload.errors.php the second file is coming with UPLOAD_ERR_FORM_SIZE ["error"]=> int(2)

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

So that's my issue, is it Bulletproof testing before everything else in the code... ?

So there is the main issue.

from bulletproof.

samayo avatar samayo commented on June 2, 2024

This could mean you are trying to upload an image with size greater than defined in your HTML

  <input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>

Here we have defined 1 Million bytes (~ 1mb) of maximum upload size. However, if you try to upload more than the amount specified in this HTML form you will get error number 2, which delineates to this specific issue.

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

Yeah, i know now.. but ur class dont check for that so you should test for that posibility..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

It does! That is why you are getting the clear error message message:

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

It can't get more specific. Note MAX_FILE_SIZE and HTML form

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

Before processing the file you should text for errors in $_FILES superglobal before doing anything on the file..

Don't you agree?

from bulletproof.

samayo avatar samayo commented on June 2, 2024

It will display the error before processing. If your file size is greater than the one defined in the HTML, the image will never be uploaded. This is processing before anything

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

I am not getting the error feom u class I got it using var_dump ( $_FILES ) before starting bulletproof..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

Sure it does. Try it on something like this..

<?php 
$image = Bulletproof\Image($_FILES);
if($image['foo']){
	$upload = $image->upload(); 
	if(!$upload){
		echo $image['error']; // this will work
	}
}

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

if ( $image ['whatevername] ) is false then at else shoud $image['error'] have specified error.. and it doesn't..

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

Yes, after u pass upload method but before that foo is false and wont tell why, that's the whole issue here.

from bulletproof.

samayo avatar samayo commented on June 2, 2024

No. You don't understand. if ( $image ['whatevername] ){} will check only if an HTML input with name='whatevername' is clicked or posted. At this point bulletproof will not and should not check the file size, type, dimension.... it doesn't make sense. This will only check POST and the html name. The only part that should check size, type, dimension is the $upload = $image->upload();

<?php 
$image = Bulletproof\Image($_FILES);
if($image['foo']){

	$upload = $image->upload(); 
	
        if($upload){
	
        } else{} // WE need else b/c here we are trying to upload

} // NO need for else otherwise error will show up when no post is made

the if($image['foo']){} part (which needs No else clause is like this code:

if($_POST){}

if you have a page for registering a user, and you put if($_POST){} else{ ... } the else part will be show when people are just browsing the register page, because no post is made. You should only display errors if post is made and something doesn't work. otherwise if they are just loading the page with no clicks, posts, and upload buttons pressed it makes no sense to display errors.

from bulletproof.

samayo avatar samayo commented on June 2, 2024

To simply paraphrase: if($image['foo']){} is same as if($_FILES['something']){} or if($_POST['login']){} none of them need an else statement to show an error. They are all checking if someone pressed an HTML button. If that someone hasn't pressed a button the no need to show error. They could simply be reading or looking at the page.

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

Alright,
in your example profilepic is the name of the being uploaded, when your class is init then $_FILES come with array ['profilepic'] then the array come with information and error if any,

Then as your saying if I just use method bulletproof\upload and the $_FILES comes with error int 2 then I get this error

Image uploaded failed!! Reason: Invalid File! Only (gif, jpeg, jpg, png) image types are allowed
2017/06/20 10:25:18 [error] 1161#0: *181 FastCGI sent in stderr: "PHP message: PHP Notice: Undefined index: tmp_name in /bulletproof.php on line 326 PHP message: PHP Warning: getimagesize(): Filename cannot be empty in /bulletproof.php on line 326 PHP message: PHP Notice: Undefined index: tmp_name in /bulletproof.php on line 311 PHP message: PHP Warning: getimagesize(): Filename cannot be empty in /bulletproof.php on line 311 PHP message: PHP Notice: Undefined index: error in /bulletproof.php on line 415 PHP message: PHP Notice: Undefined index: in /bulletproof.php on line 384 PHP message: PHP Notice: Undefined index: tmp_name in /bulletproof.php on line 420 PHP message: PHP Warning: exif_imagetype(): Filename cannot be empty in /bulletproof.php on line 127" while reading response header from upstream, client: 192.168.1.254, server: , request: "POST /app/do/registration/0 HTTP/1.1", upstream: "fastcgi://unix:/var/run/php7-fpm.sock:", host: "www.", referrer: "register"
`
So is this the correct behavior..

array(1) { ["profilepic"]=> array(5) { ["name"]=> string(13) "thisatest.jpg" ["type"]=> string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(2) ["size"]=> int(0) } }
that's the file before init bulletproof..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

Since the image is not uploaded it is normal to get an error with tmp_name

you can see the error in the first line

Image uploaded failed!! Reason: Invalid File! Only (gif, jpeg, jpg, png) image types are allowed

which you can get with $image['error']

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

But you are killing the syslog with that behavior, ur class is not testing before bulletproof\upload method is called...

In short before upload method is called ur class should have tested the $_FILES var..

from bulletproof.

samayo avatar samayo commented on June 2, 2024

That has some drawbacks. i think the best thing to do is halt the script if an error occurs first since the following logs could result from the first error. anyway i'm glad we figured out the issue

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

So I will have to test $_FILES before passing it to bulletproof...

Thanks for ur help.

from bulletproof.

samayo avatar samayo commented on June 2, 2024

No. no need, just exist when you encounter the first error.

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

What u mean? Elaborate..

from bulletproof.

samayo avatar samayo commented on June 2, 2024
$image = Bulletproof\Image($_FILES); 

if($image['foobar']){
	
	$upload = $image->upload(); 

	if(!$upload){
		echo $imag['error']; 
		// exit here early to avoid adding more error to your logs
	}
}

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

@samayo
With all due respect , that's unacceptable answer because bulletproof\upload would have tried to upload an $_FILES with an error in it.. therefor will flood the syslog..
regards.

from bulletproof.

Neumann-Valle avatar Neumann-Valle commented on June 2, 2024

So I changed the bulletproof\upload method so it can test $_FILES correctly the only changes would be the init of bulletproof class like so:

// the name of your picture in superglobal $_FILES

$image = new Bulletproof\Image($_FILES['profilepic']);// notice is not only $_FILES anymore

then call bulletproof\upload method

$upload = $image->upload();

then if there any error in $upload and become false, you will have $image['error'] populated.

/**
     * This methods validates and uploads the image
     * @return bool|Image|null
     * @throws ImageUploaderException
     */
    public function upload()
    {
        /* modify variable names for convenience */
        $image = $this;
        $files = $this->_files;

        /* check if php_exif is enabled */
        if(!function_exists('exif_imagetype')){
            $image->error = "Function 'exif_imagetype' Not found. Please enable \"php_exif\" in your PHP.ini";
            return null;
        }

        /* check for common upload errors before doing anything with $_FILES*/
        if($image->error = $image->uploadErrors($files["error"])){
            return null;
        }

        /* initialize image properties */
        $image->name     = $image->getName();
        $image->width    = $image->getWidth();
        $image->height   = $image->getHeight(); 
        $image->location = $image->getLocation();

        /* get image sizes */
        list($minSize, $maxSize) = $image->size;

        /* check image for valid mime types and return mime */
        $image->mime = $image->getImageMime($files["tmp_name"]);

        /* validate image mime type */
        if (!in_array($image->mime, $image->mimeTypes)) {
            $ext = implode(", ", $image->mimeTypes);
            $image->error = sprintf($this->error_messages['mime_type'], $ext);
            return null;
        }

        /* check image size based on the settings */
        if ($files["size"] < $minSize || $files["size"] > $maxSize) {
            $min = intval($minSize / 1000) ?: 1; $max = intval($maxSize / 1000);

            $image->error = sprintf($this->error_messages['file_size'], $min, $max);
            return null;
        }

        /* check image dimension */
        list($allowedWidth, $allowedHeight) = $image->dimensions;

        if ($image->height > $allowedHeight || $image->width > $allowedWidth) {
            $image->error = sprintf($this->error_messages['dimensions'], $allowedHeight, $allowedWidth);
            return null;
        }

        if($image->height < 2 || $image->width < 2){
            $image->error = $this->error_messages['too_small'];
            return null;
        }
 
        /* set and get folder name */
        $image->fullPath = $image->location. "/" . $image->name . "." . $image->mime;

        /* gather image info for json storage */ 
        $image->serialize = array(
            "name"     => $image->name,
            "mime"     => $image->mime,
            "height"   => $image->height,
            "width"    => $image->width,
            "size"     => $files["size"],
            "location" => $image->location,
            "fullpath" => $image->fullPath
        );

        if ($image->error === "") {
            $moveUpload = $image->moveUploadedFile($files["tmp_name"], $image->fullPath);
            if (false !== $moveUpload) {
                return $image;
            }
        }

        $image->error =  $this->error_messages['unknown'];
        return false;
    }

from bulletproof.

samayo avatar samayo commented on June 2, 2024

Ok. I'm on the verge of giving up because you haven't understood my point, and I'm quoting this line:

that's unacceptable answer because bulletproof\upload would have tried to upload an $_FILES with an error in it

PHP can't get the image image property like size, name without $_FILES uploading it to the tmp directory. Basically every file will be uploaded to the server before its checked. It's only after this point the image is moved to some other dir.

But you can download bulletproof and add modifications and use it in a way that makes sense to you.

from bulletproof.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.