i'm trying to upload file using php. i want to restrict the file extensions to .jpg and jpeg. this is the code i have

$upload_errors = array(
        UPLOAD_ERR_OK => "No errors.",
        UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
        UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
        UPLOAD_ERR_PARTIAL => "Partial upload.",
        UPLOAD_ERR_NO_FILE => "No file.",
        UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
        UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
        UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
    );
    
    if ( isset( $_POST['submit'] ) ) {
        // process the form data
        $tmp_file = $_FILES['file_upload']['tmp_name'];
        $target_file = basename( $_FILES['file_upload']['name'] );
        $upload_dir = "uploads";
        
        // file_exists() can be used to determine if there isn't a file with the same name in the upload_dir
        
        // move_uploaded_file will return false if $tmp_file is not a valid upload file
        // or if it can not be moved for any other reason
        if ( move_uploaded_file( $tmp_file, $upload_dir . "/" . $target_file ) ) {
            $message = "File has been successfully uploaded.";
        } else {
            $error = $_FILES['file_upload']['error'];
            $message = $upload_errors[$error];       
        }
    }

how do i make use of an array that has the specifics extensions to be used?

Recommended Answers

All 2 Replies

i'm trying to upload file using php. i want to restrict the file extensions to .jpg and jpeg. this is the code i have

...

how do i make use of an array that has the specifics extensions to be used?

There are some options. You are mentioning an array which is of course one potential solution.

<?php
  $validExt = array('jpg', 'jpeg', 'png');

  $extension = array_pop(explode('.', $_FILES[0]['name']));  // replace this with your version of the FILES array
  $extension = strtolower($extension); // make it all lower case
  if (in_array($extension, $validExt)) {
     // here comes the code for a valid JPEG ... file
  } else {
     // here comes the code for an invalid file
  }
?>

Regards
Maba

Hi,

See if the code below works for you. Note that 'pjpeg' refers to progressive jpegs and when dealing with jpgs, I always include it to avoid possible issues in IE.

$filetype = $_FILES['file_upload']['type'];
if( $filetype === "image/jpeg" || $filetype === "image/pjpeg" ) {
	//do nothing
} else {
	//invalid file type
  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.