Tutorial :Extracting File Extension in PHP (image upload script)


Can anyone tell me what is wrong with this? The file is renamed using a time stamp but the extension doesn't get extracted and placed in the new name.

    $filenameext = pathinfo($filename, PATHINFO_EXTENSION);        $today = getdate();      $uniqueStr = $today[year];      $uniqueStr .= $today[mon];      $uniqueStr .= $today[wday];      $uniqueStr .= $today[mday];      $uniqueStr .= $today[hours];      $uniqueStr .= $today[minutes];      $uniqueStr .= $today[seconds];        $filename = $uniqueStr.".".$filenameext;  

The full code:

<?php  $folder = 'images/';  $orig_w = 500;    if( isset($_POST['submit']) )  {      $imageFile = $_FILES['image']['tmp_name'];      $filenameext = pathinfo($filename, PATHINFO_EXTENSION);        $today = getdate();      $uniqueStr = $today[year];      $uniqueStr .= $today[mon];      $uniqueStr .= $today[wday];      $uniqueStr .= $today[mday];      $uniqueStr .= $today[hours];      $uniqueStr .= $today[minutes];      $uniqueStr .= $today[seconds];      $filename = $uniqueStr.".".$filenameext;        list($width, $height) = getimagesize($imageFile);        $src = imagecreatefromjpeg($imageFile);      $orig_h = ($height/$width)* $orig_w;        $tmp = imagecreatetruecolor($orig_w, $orig_h);      imagecopyresampled($tmp, $src, 0,0,0,0,$orig_w,$orig_h,$width,$height);      imagejpeg($tmp, $folder.$filename,100);        imagedestroy($tmp);      imagedestroy($src);        $filename = urlencode($filename);      header("Location: crop.php?filename=$filename&height=$orig_h");  }  



This should work fine - can you print your $filename right before pathinfo()?

Edit after you posted your code: so let me get this straight

$imageFile = $_FILES['image']['tmp_name'];  $filenameext = pathinfo($filename, PATHINFO_EXTENSION);  

You read in $imageFile but parse an uninitialized variable $filename?


Do not trust the filename extension to describe the file format accurately. Don't trust the mime type either.

$sourceFile = $_FILES['photoupload']['tmp_name'];    list($width, $height, $type, $attr) = getimagesize($sourceFile);    $filetype = image_type_to_extension($type, true);  // $filetype includes the dot.  if ('.jpeg' == $filetype) {      $filetype = '.jpg';  // use jpg, not the 'jpeg' the function would return  }  


While pathinfo() is supposed to return a string for single requests, it's usually defined to return an array.

Try this: $filenameext = pathinfo($path)['extension'];

However, have you logged the output of "path"? It might be the temporary path generated by your web server on upload, rather than the user's supplied file name, depending on where you get it from.


explode(".", $_FILES["file"]["name"]);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »