Hi, I'm pretty new this whole PHP thing, so I need your help. I got this code from somewhere to upload files using two PHP files (a form and an upload file), but I need it to be able to restrict to only jpg, png, gif, and jpeg files. Everything else works great. Can anyone point me in the right direction? Code posted below:

<?php
//upload.php


// Upload directory

$dir = 'uploadpics/';

$num = $_POST['num'];

$messages = array();



for ($x = 1; $x <= $num; $x++) {

$file = $_FILES['file'.$x];

if (! is_uploaded_file($file['tmp_name'])) {

    $messages[$x-1] = 'File '.$x.': No file selected.';

    continue;

}

if (! move_uploaded_file($file['tmp_name'],$dir.$file['name'])) {

    $messages[$x-1] = 'File '.$x.': Unable to move file.';

    continue;

} else {

    $messages[$x-1] = 'File '.$x.': Uploaded...';

}

}



foreach ($messages as $msg) {

echo $msg.'<br />';

}



?>

and, just in case, the code for the form

<?php



// If the number of files have not been set, show the first form

if ((!isset($_GET['num'])) || (empty($_GET['num']))) {



?>
<html><head><title>Upload Files</title></head><body bgcolor="#0099CC"><table width="640" border="0" align="center"><tr><td><div align="center">
<font size="6" color="#FFFFFF">Upload Pictures</font><br><br><form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">

<font color="#FFFFCC">Number of files to upload:</font>

<select name="num">

<?php

for ($x = 1; $x <= 20; $x++) {

    echo '<option value='.$x.'>'.$x.'</option>';

}

?>

</select>

<input type="submit" value="Submit" />

</form></div>
</td></tr></table></body></html>
<?php



} else {

// else, show the upload form

// get the integer value of $_GET['num']

$num = intval($_GET['num']);



?>
<html>
<head><title>Upload Pictures</title></head><body bgcolor=#0099CC><table width="640" border="0" align="center"><tr><td>
<div align="center"><font size="6" color="#FFFFFF">Upload Pictures</font>
<form action="upload.php" method="post" enctype="multipart/form-data">

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

<input type="hidden" name="num" value="<?php echo $num; ?>" />

<?php



// show the file input field $num times

// name the fields file1,file2,file3...

for ($x = 1; $x <= $num; $x++) {

echo 'File '.$x.': <input type="file" name="file'.$x.'" /><br />';

}



?>

<input type="submit" value="Upload Files" />

</form>
<em>Please be patient while your files upload. This may take several minutes. Do not click refresh.</em>
</div>
</td>
</tr>
</table>
</body>
</html>
<?php



}



?>

Thanks in advance for any help 🙂

    $ext = substr( trim($file['name']) , -3 ); //get the extension

    if ( $ext == 'jpg' || $ext == 'JPG'|| $ext == 'png' || $ext == 'PNG' || $ext == 'gif' || $ext == 'GIF' || $ext == 'jpeg' || $ext == 'JPEG' )
    {
    // dot the stuff of uploading
    }
    else
    {
    //display error msg
    }

      Thanks for your reply. However, I get an error message for any file that I try to upload -- even jpg, gif, png, etc. Is there something wrong with the way I applied the code?

      for ($x = 1; $x <= $num; $x++) {
      
      	if ( $ext == 'jpg' || $ext == 'JPG'|| $ext == 'png' || $ext == 'PNG' || $ext == 'gif' || $ext == 'GIF' || $ext == 'jpeg' || $ext == 'JPEG' ){
      
      	$file = $_FILES['file'.$x];
      
      	if (! is_uploaded_file($file['tmp_name'])) {
      
      		$messages[$x-1] = 'File '.$x.': No file selected.';
      
      		continue;
      
      	}
      
      	if (! move_uploaded_file($file['tmp_name'],$dir.$file['name'])) {
      
      		$messages[$x-1] = 'File '.$x.': Unable to move file.';
      
      		continue;
      
      	} else {
      
      		$messages[$x-1] = 'File '.$x.': Uploaded...';
      
      	}
      
      }
      else
      {
        // no match, don't upload this file, append an error, and continue
        $messages[$x-1] = 'File '.$x.': Bad file type. Please use only gif, png, jpg, or jpeg files.';
      }
      }
      

      Thanks

        from the script above, i think u missed out the line:

        $ext = substr( trim($file['name']) , -3 ); //get the extension

        sorry if i got it wrong.

          yes, I got that, but I forgot to copy it to my previous post. It should be like this:

          <?php
          $dir = 'uploadpics/';
          
          $num = $_POST['num'];
          
          $messages = array();
          
          
          $ext = substr( trim($file['name']) , -3 ); //get the extension
          
          
          // dot the stuff of uploading
          
          
          for ($x = 1; $x <= $num; $x++) {
          
          	if ( $ext == 'jpg' || $ext == 'JPG'|| $ext == 'png' || $ext == 'PNG' || $ext == 'gif' || $ext == 'GIF' || $ext == 'jpeg' || $ext == 'JPEG' ){
          
          	$file = $_FILES['file'.$x];
          
          	if (! is_uploaded_file($file['tmp_name'])) {
          
          		$messages[$x-1] = 'File '.$x.': No file selected.';
          
          		continue;
          
          	}
          
          	if (! move_uploaded_file($file['tmp_name'],$dir.$file['name'])) {
          
          		$messages[$x-1] = 'File '.$x.': Unable to move file.';
          
          		continue;
          
          	} else {
          
          		$messages[$x-1] = 'File '.$x.': Uploaded...';
          
          	}
          
          }
          else
          {
            // no match, don't upload this file, append an error, and continue
            $messages[$x-1] = 'File '.$x.': Bad file type. Please use only gif, png, jpg, or jpeg files.';
          }
          }
          
          
          
          
          foreach ($messages as $msg) {
          
          echo $msg.'<br />';
          
          }
          
          
          
          ?>
          

            You're taking the extension of "$file" before file is defined (probably hinted at by the error messages), and you're defining "$file" after checking its extension. Also, you're using three characters for "$ext", but "jpeg" and "JPEG" are four characters long. And all those inexplicable blanks lines...

            This should work:

            $dir = 'tmp/'; 
            $num = $_POST['num']; 
            $messages = array(); 
            
            for ($x = 1; $x <= $num; $x++) { 
                $file = $_FILES['file' . $x]; 
                $ext = substr(trim($file['name']), -4 ); //get the extension
                if ($ext == '.jpg' || $ext == '.JPG' || $ext == '.png' || 
                    $ext == '.PNG' || $ext == '.gif' || $ext == '.GIF' || 
                    $ext == 'jpeg' || $ext == 'JPEG' ) { 
                    if (!is_uploaded_file($file['tmp_name'])) { 
                        $messages[$x] = 'File ' . $x . ': No file selected.'; 
                        continue; 
                    } 
                    if (!move_uploaded_file($file['tmp_name'], $dir . $file['name'])) { 
                        $messages[$x] = 'File ' . $x . ': Unable to move file.'; 
                        continue; 
                    } else { 
                        $messages[$x] = 'File ' . $x . ': Uploaded...'; 
                    } 
                } else { 
                    $messages[$x] = 'File ' . $x . ': Bad file type. ' .
                                    'Please use only gif, png, jpg, or jpeg files.'; 
                } 
            } 
            
            foreach ($messages as $msg) { 
                echo $msg . '<br />'; 
            }

            Edit: Here's how I'd check the extensions:

            // ...
            $ext_arr = array('.jpg', '.png', '.gif', 'jpeg');
            
            for ($x = 1; $x <= $num; $x++) { 
                $file = $_FILES['file' . $x]; 
                $ext = substr(trim($file['name']), -4 ); //get the extension
                if (in_array(strtolower($ext), $ext_arr)) { 
            // etc.

              Thank you for your reply. I will try this as soon as I get home.

              -t

                Instead of getting the last four characters of the filename, why not split the file at each period (explode) into an array and check the last element of the array?

                $pieces = explode(".",$file_name);
                $ext = $pieces[(count($pieces) - 1)];

                This uses [MAN]explode[/MAN] to split the file name into an array and uses the size of the array to get the last element - do this just in case someone uploads a file with one or more period in the file name (ex: php.net.logo.gif).

                Also, please remember that if you really want to be secure and control the type of file being uploaded, you really need to check the MIME type, not the file extension. You can rename an executeable file from .exe to .jpg, but it's still an executeable. This type of file will make it's way onto your server. If you're expecting an image, a good way of checking for a valid MIME type is to use [MAN]getimagesize[/MAN]. The third element in the array returned by this function is a numeric value referring to the MIME type of the image. if it's not an image, it'll return 0.

                  I finally got it to work... using Installer's method for now. I did make a small change, however. Here's what I used:

                   $dir = 'uploadpics/';
                  $num = $_POST['num'];
                  $messages = array();
                  
                  for ($x = 1; $x <= $num; $x++) {
                      $file = $_FILES['file' . $x];
                      $ext = substr(trim($file['name']), -4 ); //get the extension
                  
                      if (!is_uploaded_file($file['tmp_name'])) {
                          $messages[$x] = 'File ' . $x . ': No file selected.';
                          continue;
                      }
                      elseif ($ext != '.jpg' && $ext != '.JPG' && $ext != '.png' &&
                              $ext != '.PNG' && $ext != '.gif' && $ext != '.GIF' &&
                              $ext != 'jpeg' && $ext != 'JPEG' ) {
                                $messages[$x] = 'File ' . $x . ': Bad file type. ' .
                                                        'Please use only gif, png, jpg, or jpeg files.';
                                continue;
                      }
                      elseif (!move_uploaded_file($file['tmp_name'], $dir . $file['name'])) {
                          $messages[$x] = 'File ' . $x . ': Unable to move file.';
                          continue;
                      } else {
                          $messages[$x] = 'File ' . $x . ': Uploaded...';
                      }
                  } 
                  
                  
                  foreach ($messages as $msg) {
                      echo $msg . '<br />';
                  }
                  

                  Again, thanks for all of your help 🙂

                    Write a Reply...