2

I am checking uploaded file extension by pathinfo() function of php but in coding standard check it's shows

The use of function pathinfo() is discouraged

My code:

$fileExt = pathinfo($file, PATHINFO_EXTENSION);
1
  • Let me know if you have any issue Commented Sep 12, 2017 at 18:40

3 Answers 3

6

You can use Magento\Framework\Filesystem\Io\File instead.

Example:

<?php

namespace Vendor\ModuleName\Model;

use Magento\Framework\Filesystem\Io\File;

class MyClass
{
   /**
    * @var File
    */
   private $file;

   /**
    * @param File $file
    */
   public function __construct(File $file)
   {
       $this->file = $file;
   }

   public function myMethod()
   {
       $path = 'this\is\some\dummy\path\potato.jpg';
       $pathInfo = $this->file->getPathInfo($path);
   }
}
2
  • This doesn't allow for the PATHINFO_EXTENSION option as a second parameter however. Commented Dec 3, 2019 at 18:42
  • this will return an array, you can access the extension using key extension
    – Mujahidh
    Commented May 3, 2023 at 11:43
0

Use \Magento\MediaStorage\Model\File\UploaderFactory for file operation You can get file extension by this code:

$uploader = $this->fileUploaderFactory->create(['fileId' => $scope]);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);

if ($uploader->save($this->getBaseDir())) {
    echo $fileName = $uploader->getUploadedFileName();
    echo $fileExt = $uploader->getFileExtension();
}
0
0

I think I've found the best way to achieve that, you'll get file extension from this code:

        $pathArray = explode('.', $path);
        $extension = end($pathArray);
        return $extension;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.