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?

Dani AI

Generated

Good direction so far — is right to suggest a whitelist, and is right to check type. Combine both ideas and add content-level checks, safe naming, and basic server-side guards. Relying on $_FILES['type'] or on the original filename alone is unsafe (both can be spoofed); use pathinfo() for the extension, Fileinfo or getimagesize() to verify content, is_uploaded_file()/move_uploaded_file() to accept the upload, and never save the untrusted original name as an executable file on disk.

Example (concise, secure flow):

<?php
$allowed = ['jpg','jpeg'];
$maxBytes = 2*1024*1024; // 2 MB
$file = $_FILES['file_upload'] ?? null;

if ($file && $file['error'] === UPLOAD_ERR_OK && is_uploaded_file($file['tmp_name'])) {
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed, true) || $file['size'] > $maxBytes) { /* reject */ }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    if ($mime !== 'image/jpeg') { /* reject */ }

    $rand = function_exists('random_bytes')
        ? bin2hex(random_bytes(8))
        : bin2hex(openssl_random_pseudo_bytes(8));
    $dir = __DIR__ . '/uploads';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $target = $dir . '/' . $rand . '.' . $ext;

    if (move_uploaded_file($file['tmp_name'], $target)) chmod($target, 0644);
}
?>

Troubleshooting and security notes:

  • The HTML form must use method="post" and enctype="multipart/form-data".
  • Confirm php.ini settings (file_uploads on, upload_max_filesize, post_max_size).
  • Prefer storing uploads outside the webroot or disable script execution in the uploads folder (server config or .htaccess).
  • Keep the whitelist tight, log rejected attempts, and consider running uploaded images through getimagesize() or an image library for extra validation.

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.