Link to home
Start Free TrialLog in
Avatar of QUESTOMNI
QUESTOMNIFlag for United States of America

asked on

upload_image.php script -Didn't upload and didn't give error message. What could have happened?

upload_image.php script -Didn't upload and didn't give error message. What could have happened?
upload-image.php
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

You've set your maxfilesize at 0.5MB (512k) in the HTML. Is the file you're trying to upload larger than that? What is your PHP max upload size?
Avatar of QUESTOMNI

ASKER

No.
ALI.jpg
Avatar of gr8gonzo
Try echoing out the value of __LINE__ throughout the PHP portion of the script
For example:
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

echo __LINE__."<br>\n";

	// Check for an uploaded file.
	if (isset($_FILES['upload'])) {

echo __LINE__."<br>\n";
		
		// Validate the type. Should be jpeg, jpg, or gif.
		$allowed = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg');
		if (in_array($_FILES['upload']['type'], $allowed)) {

echo __LINE__."<br>\n";

Open in new window


Also, check your log file for any PHP errors. You have MAX_FILE_SIZE but there's also a setting in php.ini for upload file size called upload_max_filesize. If that's set to 0 or something, it will also prevent the upload.
Don't understand. Please explain.
Don't worry about the php.ini stuff for now - try the code changes first. The only thing you have to do is copy that one line:

echo __LINE__."<br>\n";

...and then paste it at various points inside your PHP code, and then try to upload the image again. The __LINE__ is a special variable that will display the current line number, so when you echo __LINE__ on line 5, then it will display "5" and so on.

This way, you can see what parts of your PHP script are actually running. It's a good debugging technique.

So for example, here is the old code:
<?php # Script 11.1 - upload_image.php

// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

	// Check for an uploaded file.
	if (isset($_FILES['upload'])) {
		
		// Validate the type. Should be jpeg, jpg, or gif.
		$allowed = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg');
		if (in_array($_FILES['upload']['type'], $allowed)) {
		
			// Move the file over.
			if (move_uploaded_file($_FILES['upload']['tmp_name'], "uploads/{$_FILES['upload']['name']}")) {
			
				echo '<p>The file has been uploaded!</p>';
			
			} else { // Couldn't move the file over.
			
				echo '<p><font color="red">The file could not be uploaded because: </b>';
		
				// Print a message based upon the error.
				switch ($_FILES['upload']['error']) {
					case 1:
						print 'The file exceeds the upload_max_filesize setting in php.ini.';
						break;
					case 2:
						print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
						break;
					case 3:
						print 'The file was only partially uploaded.';
						break;
					case 4:
						print 'No file was uploaded.';
						break;
					case 6:
						print 'No temporary folder was available.';
						break;
					default:
						print 'A system error occurred.';
						break;
				} // End of switch.
				
				print '</b></font></p>';

			} // End of move... IF.
			
		} else { // Invalid type.
			echo '<p><font color="red">Please upload a JPEG or GIF image.</font></p>';
			unlink ($_FILES['upload']['tmp_name']); // Delete the file.
		}

	} else { // No file uploaded.
		echo '<p><font color="red">Please upload a JPEG or GIF image smaller than 512KB.</font></p>';
	}
			
} // End of the submitted conditional.
?>

Open in new window


Replace it with this new code with the debugging lines:
<?php # Script 11.1 - upload_image.php

echo __LINE__."<br>\n";

// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

echo __LINE__."<br>\n";

	// Check for an uploaded file.
	if (isset($_FILES['upload'])) {

echo __LINE__."<br>\n";
		
		// Validate the type. Should be jpeg, jpg, or gif.
		$allowed = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg');
		if (in_array($_FILES['upload']['type'], $allowed)) {

echo __LINE__."<br>\n";
		
			// Move the file over.
			if (move_uploaded_file($_FILES['upload']['tmp_name'], "uploads/{$_FILES['upload']['name']}")) {

echo __LINE__."<br>\n";
			
				echo '<p>The file has been uploaded!</p>';
			
			} else { // Couldn't move the file over.

echo __LINE__."<br>\n";
			
				echo '<p><font color="red">The file could not be uploaded because: </b>';
		
				// Print a message based upon the error.
				switch ($_FILES['upload']['error']) {
					case 1:
						print 'The file exceeds the upload_max_filesize setting in php.ini.';
						break;
					case 2:
						print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
						break;
					case 3:
						print 'The file was only partially uploaded.';
						break;
					case 4:
						print 'No file was uploaded.';
						break;
					case 6:
						print 'No temporary folder was available.';
						break;
					default:
						print 'A system error occurred.';
						break;
				} // End of switch.
				
				print '</b></font></p>';

			} // End of move... IF.
			
		} else { // Invalid type.

echo __LINE__."<br>\n";

			echo '<p><font color="red">Please upload a JPEG or GIF image.</font></p>';
			unlink ($_FILES['upload']['tmp_name']); // Delete the file.
		}

	} else { // No file uploaded.

echo __LINE__."<br>\n";

		echo '<p><font color="red">Please upload a JPEG or GIF image smaller than 512KB.</font></p>';
	}
			
} // End of the submitted conditional.

echo __LINE__."<br>\n";
?>

Open in new window


Then try to upload and see what the output is.
Sorry. I accidently gave you the wrong script from the other book. Try this one.
upload-image.php
HTTP 500 Internal Server Error
when I did this.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Upload an Image</title>
      <style type="text/css" title="text/css" media="all">
      .error {
            font-weight: bold;
            color: #C00;
      }
      </style>
</head>
<body>
<?php # Script 11.2 - upload_image.php

// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

      // Check for an uploaded file:
      if (isset($_FILES['upload'])) {
            
            // Validate the type. Should be JPEG or PNG.
            $allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png');
            if (in_array($_FILES['upload']['type'], $allowed)) {
            
                  // Move the file over.
                  if (move_uploaded_file ($_FILES['upload']['tmp_name'], "../uploads/{$_FILES['upload']['name']}")) {
                        echo '<p><em>The file has been uploaded!</em></p>';
                  } // End of move... IF.
                  
            } else { // Invalid type.
                  echo '<p class="error">Please upload a JPEG or PNG image.</p>';
            }

      } // End of isset($_FILES['upload']) IF.
      
      // Check for an error:
      if ($_FILES['upload']['error'] > 0) {
            echo '<p class="error">The file could not be uploaded because: <strong>';
      
            // Print a message based upon the error.
            switch ($_FILES['upload']['error']) {

echo __LINE__."<br>\n";

                  case 1:
                        print 'The file exceeds the upload_max_filesize setting in php.ini.';
                        break;

echo __LINE__."<br>\n";

                  case 2:
                        print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                        break;

echo __LINE__."<br>\n";

                  case 3:
                        print 'The file was only partially uploaded.';
                        break;

echo __LINE__."<br>\n";

                  case 4:
                        print 'No file was uploaded.';
                        break;

echo __LINE__."<br>\n";

                  case 6:
                        print 'No temporary folder was available.';
                        break;

echo __LINE__."<br>\n";

                  case 7:
                        print 'Unable to write to the disk.';
                        break;

echo __LINE__."<br>\n";

                  case 8:
                        print 'File upload stopped.';
                        break;

echo __LINE__."<br>\n";

                  default:
                        print 'A system error occurred.';
                        break;
            } // End of switch.
            
            print '</strong></p>';
      
      } // End of error IF.
      
      // Delete the file if it still exists:
      if (file_exists ($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name']) ) {
            unlink ($_FILES['upload']['tmp_name']);
      }
                  
} // End of the submitted conditional.
?>
      
<form enctype="multipart/form-data" action="upload_image.php" method="post">

      <input type="hidden" name="MAX_FILE_SIZE" value="524288" />
      
      <fieldset><legend>Select a JPEG or PNG image of 512KB or smaller to be uploaded:</legend>
      
      <p><b>File:</b> <input type="file" name="upload" /></p>
      
      </fieldset>
      <div align="center"><input type="submit" name="submit" value="Submit" /></div>

</form>
</body>
</html>
That's fine - do the same thing. Just add that same line inside every if / else block:

From:
if(something)
{
   original code
}
else
{
   original code
}

Open in new window


To:
if(something)
{
   echo __LINE__."<br>\n";
   original code
}
else
{
   echo __LINE__."<br>\n";
   original code
}

Open in new window


It's a good technique to learn and master. Imagine if you gave someone directions to your house and they called you to tell you they were lost.

Well, "lost" isn't much information, but if they told you, "I turned left onto Street A, then turned right onto Street B, etc...", then you would have a much better idea of where things went wrong.

We're doing that same thing - forcing PHP to tell us what direction it went whenever it needed to make a decision. This helps you to narrow down the problem to a specific area of code. For example, if the script says:

10
14
23

Then you can go back to your code and look at lines 10, 14, and 23. Maybe you expected it to go to line 40 instead of 23 - now you know that there's a problem somewhere in that area and you can begin looking at more specific code.
Good - it looks like you started down the right path while I was writing the previous comment. The problem you're facing now is just that you put the:

echo __LINE__."<br>\n";

...in-between a "break" and a "case" keyword, which is not where PHP code can go. When you're working with a switch statement, PHP expects a certain structure to follow:

case X:
  ...any PHP code can go here...
  break;

case Y:
  ...any PHP code can go here...
  break;

So you could instead do:

case #:
  echo __LINE__."<br>\n";
  ...PHP code...
  break;

case #:
  echo __LINE__."<br>\n";
  ...PHP code...
  break;
Hey, I'm exhausted. Don't know if I'm up to it. Don't believe they allow it on my hosting service. The script came out of the book. It may be a security problem they don't allow. If you can get it to work on a hosted service let me know. I have to get some sleep. Sorry to have cost you so much time.
You don't need to fix everything in one go. This is a good learning exercise, and has nothing to do with your hosting provider unless they've taken some extreme measures (probably not if it's a major provider). You're almost there, so get some sleep and try again when you've got some rest.
Here is a teaching example of an upload script that contains some error checking and visualization.  Please read it over and post back if there is anything that you do not understand.  (And I'm with @gr8gonzo -- get plenty of sleep).

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


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// 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/reserved.variables.files.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 'uploads' DIRECTORY (MUST ALREADY EXIST)
$uploads = 'RAY_junk';

// 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

Best regards, ~Ray
Didn't solve the problem.
Um, why did you close the question if the problem wasn't solved? If you had responded to the last comment(s), we could have continued to try to help...
sorry, spent considerable time on it and couldn't solve. Got new problem to work on.
I will ask a moderator to reopen the question so you can explain why you left this question hanging without comment for almost two months, then gave the worst possible grade that anyone can give at Experts Exchange.  It's a bit of a surprise since I gave you a tested-and-working code example that works flawlessly.

Looking forward to your response. ~Ray
Sorry. It's probably a case of the server not allowing access or something is wrong with software. Got tired after being up all night trying to figure it out. Lost patience. Sorry. Please close and I'll work on it at some later date. I moved on and didn't get back. It happens. Shouldn't take it personal. Please close.
You might want to ask a moderator for advice on how to handle questions when you've been "up all night" and have "lost patience."  Giving a bad grade, especially when you got a tested and working code sample, is almost certainly not the recommended approach.
I don't know that it has answered the question. Let an administrator decide. I am removed from the study and not going back at this time. I expected the guy to work with the script I gave him and he did not give me a solution. I'm tired of this crap. Have it closed as I already did! Don't ever again reopen once I have closed. It prevents me from asking another question. Didn't always be this way! it's bad policy! CLOSE THIS QUESTION AS I REQUESTED.
Imagine someone walked up to you and asked you for help in finding your lost dog, and you stopped what you were doing and then went off to join his search. Hours later, you suddenly realize that the other guy is nowhere to be found. You have no idea what happened - he either found his dog and left without saying anything or he just gave up and left without saying. Either way, you've spent an hour or two trying to help out someone only to be the only one left without any type of answer. Then, you finally find him months later and he gets angry because you've asked what happened when he disappeared. How would you feel?

"I expected the guy to work with the script I gave him..."

Problem here is that it may not have been a script problem. I was trying to walk you through debugging the problem to see if it was and you quit in the middle without any further response. Then Ray gave you a complete working solution and you didn't respond to him, either. Remember that we are REAL human beings with REAL hours of time involved into helping you here (for free, I might add - we don't get paid for helping - we do it to help others).

So while you might feel like you are being inconvenienced by the way the system works, it's designed to also protect experts and ensure that the asking parties are providing proper closure to their questions and not just leaving us without any idea of what happened or what the results of our last comments were. When we provide comments, we're getting invested, too.
ASKER CERTIFIED SOLUTION
Avatar of QUESTOMNI
QUESTOMNI
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Tired of dealing with it. Need to move on so I'm not blocked when I have another question.