Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 506
  • Last Modified:

php saving image script

I have a script that I upload an image and crop it.
My script saves the original file as tmp in my folder.
After I crop it, I am having a problem that the final file only saves if  the original file is smaller than around 900kb.
I don't understand , because it wouldn't be a  folder setting because the temp file saves no matter how big it is.
just the final file.
I am pasted the code I have. Where does it specify the max file size here:
  public function process($saveToFilePath = null, $retainFileExt = false)
    {
	
//$saveToFilePath = 'http://'.$_SERVER['SERVER_NAME'].'/admin/crop/picture/';
        // list($width, $height) = getimagesize($_POST["imageSource"]);
        // $viewPortW = $_POST["viewPortW"];
        //$viewPortH = $_POST["viewPortH"];
        $pWidth = $_POST["imageW"];
        $pHeight = $_POST["imageH"];
        $ext = end(explode(".", $_POST["imageSource"]));	
				 		

        $function = $this->returnCorrectFunction($ext);
	
        $image = $function($_POST["imageSource"]);
        $width = imagesx($image);
        $height = imagesy($image);
    
	    // Resample
        $image_p = imagecreatetruecolor($pWidth, $pHeight);
        $this->setTransparency($image, $image_p, $ext);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $pWidth, $pHeight, $width, $height);
        imagedestroy($image);
        $widthR = imagesx($image_p);
        $hegihtR = imagesy($image_p);
			

        $selectorX = $_POST["selectorX"];
        $selectorY = $_POST["selectorY"];
        if ($_POST["imageRotate"]) {
            $angle = 360 - $_POST["imageRotate"];
            $image_p = imagerotate($image_p, $angle, 0);

            $pWidth = imagesx($image_p);
            $pHeight = imagesy($image_p);

            //print $pWidth."---".$pHeight;

            $diffW = abs($pWidth - $widthR) / 2;
            $diffH = abs($pHeight - $hegihtR) / 2;

            $_POST["imageX"] = ($pWidth > $widthR ? $_POST["imageX"] - $diffW : $_POST["imageX"] + $diffW);
            $_POST["imageY"] = ($pHeight > $hegihtR ? $_POST["imageY"] - $diffH : $_POST["imageY"] + $diffH);


        }

        $dst_x = $src_x = $dst_y = $src_y = 0;

        if ($_POST["imageX"] > 0) {
            $dst_x = abs($_POST["imageX"]);
        } else {
            $src_x = abs($_POST["imageX"]);
        }
        if ($_POST["imageY"] > 0) {
            $dst_y = abs($_POST["imageY"]);
        } else {
            $src_y = abs($_POST["imageY"]);
        }

        $viewport = imagecreatetruecolor($_POST["viewPortW"], $_POST["viewPortH"]);
        $this->setTransparency($image_p, $viewport, $ext);

        imagecopy($viewport, $image_p, $dst_x, $dst_y, $src_x, $src_y, $pWidth, $pHeight);
        imagedestroy($image_p);
        $selector = imagecreatetruecolor($_POST["selectorW"], $_POST["selectorH"]);
        $this->setTransparency($viewport, $selector, $ext);
        $a = imagecopy($selector, $viewport, 0, 0, $selectorX, $selectorY, $_POST["viewPortW"], $_POST["viewPortH"]);
        $saveToFilePath = ($retainFileExt == true) ? $saveToFilePath . '.' . $ext : $saveToFilePath;

        $this->parseImage($ext, $selector, $saveToFilePath);
        imagedestroy($viewport);
        //Return value
        return $this;
        /* Functions */

    }

Open in new window

0
rivkamak
Asked:
rivkamak
  • 7
  • 7
1 Solution
 
Ray PaseurCommented:
There are a number of settings that can affect large file uploads.  The HTML form has some important information.  Here is my teaching example of how to upload files.  Check the man pages referenced in the comments, and the HTML form near line 60.

<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/reserved.variables.files.php
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/function.getimagesize.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 
rivkamakAuthor Commented:
But there is no max file size for the temp file.
are you saying the reference to the max file might be in the form not in the saving script?
0
 
Ray PaseurCommented:
Yes, exactly!  Check the comments in the PHP script for man page references you need to understand, and check the comments in the HTML lines 66-72.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
rivkamakAuthor Commented:
so why is it able to save the file the first time as a tmp file?
0
 
Ray PaseurCommented:
Sorry, maybe I misunderstood.  In PHP file uploads, tmp is a term of art, referring to the temporary storage that is used when a file is uploaded and that is discarded when the script ends.  Can you show us the rest of the class?  Did you write this script or did you find it somewhere else?  This is really curious; what does it do?  Are you familiar with $_FILES?

$image = $function($_POST["imageSource"]);
0
 
Neil_BradleyWeb UX/UI DeveloperCommented:
Would raising the memory limit help?
ini_set('memory_limit', '64M');
N
0
 
rivkamakAuthor Commented:
when I have a large filesize I don't get past line 14.

$image = $function($_POST["imageSource"]);
does this run a function? or just puts the variable $image with the new image location.
How can I figure out what it's calling.
0
 
Ray PaseurCommented:
does this run a function?
Good grief, how would I know?  Where did you get this code?  It doesn't really make sense to me (looks like it is a fragment that was ripped out of a larger class) but I figured if you were using it, you understood it and trusted it.

If you're not sure what this code is doing, it might be wise to step away from it and get a bit of a foundation in how PHP works.  Handling file uploads is considered an intermediate-to-advanced topic with security implications.  You can get a good head start on learning PHP with the resources in this article.  Another approach, if you want to save time, would be to hire a professional developer to either write the code, or help you write the code.
0
 
rivkamakAuthor Commented:
I am trying to use a crop function.
Someone uploads the photo, then they can crop, rotate and compress and hit save.
Someone wrote the script for me using the YII framework.

Now I'm looking back at it and realizing it only works for files under 1 mb and I can't figure out how to fix it.
0
 
Ray PaseurCommented:
Yeah, I see this kind of thing all the time.  Not only do you have to learn PHP, you have to learn the framework, too.  Wherever the fix might be, it probably isn't in this code.  Do you have a link to this online anywhere so I could see the native behavior when I use a small file and a large one that triggers the failure?
0
 
rivkamakAuthor Commented:
You can view it here:
http://kkrtaxliens.com/admin/crop/
0
 
rivkamakAuthor Commented:
I am reposting the code along with kind of tracing, i set up a cookie that gets set as you go along so you can see what is happening.
  public function process($saveToFilePath = null, $retainFileExt = false)
    {
	setcookie("cropzoomehandler", "1");
//$saveToFilePath = 'http://'.$_SERVER['SERVER_NAME'].'/admin/crop/picture/';
        // list($width, $height) = getimagesize($_POST["imageSource"]);
        // $viewPortW = $_POST["viewPortW"];
        //$viewPortH = $_POST["viewPortH"];
        $pWidth = $_POST["imageW"];
        $pHeight = $_POST["imageH"];
        $ext = end(explode(".", $_POST["imageSource"]));	
				 		
	setcookie("cropzoomehandler", "2");
        $function = $this->returnCorrectFunction($ext);
		setcookie("cropzoomehandler", "3");
        $image = $function($_POST["imageSource"]);
		setcookie("test", 'test' );

        $width = imagesx($image);
        $height = imagesy($image);
    	setcookie("cropzoomehandler", "4");
	    // Resample
        $image_p = imagecreatetruecolor($pWidth, $pHeight);
        $this->setTransparency($image, $image_p, $ext);
			setcookie("cropzoomehandler", "5");
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $pWidth, $pHeight, $width, $height);
			setcookie("cropzoomehandler", "6");
        imagedestroy($image);
        $widthR = imagesx($image_p);
        $hegihtR = imagesy($image_p);
			
	setcookie("cropzoomehandler", "7");
        $selectorX = $_POST["selectorX"];
        $selectorY = $_POST["selectorY"];
        if ($_POST["imageRotate"]) {
            $angle = 360 - $_POST["imageRotate"];
            $image_p = imagerotate($image_p, $angle, 0);

            $pWidth = imagesx($image_p);
            $pHeight = imagesy($image_p);

            //print $pWidth."---".$pHeight;

            $diffW = abs($pWidth - $widthR) / 2;
            $diffH = abs($pHeight - $hegihtR) / 2;

            $_POST["imageX"] = ($pWidth > $widthR ? $_POST["imageX"] - $diffW : $_POST["imageX"] + $diffW);
            $_POST["imageY"] = ($pHeight > $hegihtR ? $_POST["imageY"] - $diffH : $_POST["imageY"] + $diffH);


        }

        $dst_x = $src_x = $dst_y = $src_y = 0;
	setcookie("cropzoomehandler", "8");
        if ($_POST["imageX"] > 0) {
            $dst_x = abs($_POST["imageX"]);
        } else {
            $src_x = abs($_POST["imageX"]);
        }
        if ($_POST["imageY"] > 0) {
            $dst_y = abs($_POST["imageY"]);
        } else {
            $src_y = abs($_POST["imageY"]);
        }
	setcookie("cropzoomehandler", "9");
        $viewport = imagecreatetruecolor($_POST["viewPortW"], $_POST["viewPortH"]);
        $this->setTransparency($image_p, $viewport, $ext);

        imagecopy($viewport, $image_p, $dst_x, $dst_y, $src_x, $src_y, $pWidth, $pHeight);
        imagedestroy($image_p);
        $selector = imagecreatetruecolor($_POST["selectorW"], $_POST["selectorH"]);
        $this->setTransparency($viewport, $selector, $ext);
        $a = imagecopy($selector, $viewport, 0, 0, $selectorX, $selectorY, $_POST["viewPortW"], $_POST["viewPortH"]);
        $saveToFilePath = ($retainFileExt == true) ? $saveToFilePath . '.' . $ext : $saveToFilePath;
			setcookie("cropzoomehandler", "10");

        $this->parseImage($ext, $selector, $saveToFilePath);
        imagedestroy($viewport);
        //Return value
        return $this;
        /* Functions */

    }

Open in new window

0
 
Ray PaseurCommented:
It's demanding a login that I don't have.  Sorry, this isn't a question with an answer any more -- it's a research project and for that you might want to hire a professional developer, maybe the one who wrote the script originally would know how to correct it.  Best of luck with the project, ~Ray
0
 
rivkamakAuthor Commented:
Thank you for your help anyway?
I will have to hire someone to figure it out.
0
 
Ray PaseurCommented:
Sorry I couldn't figure it out, but thanks for the points and good luck with it.  I'm guessing that the answer will be found in a configuration setting or in the form that does the upload. At least that is where I would look first.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now