whiteletters in blankpapers whiteletters in blankpapers - 6 months ago 25
PHP Question

PHP file upload is creating filenames starting with "PHP" and with .tmp extension

I am using PHP (Symfony2) in my project which has image upload feature. Inside controller:

if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$index=(int)$request->request->get('index');

$image_file = $request->files->get('shop_bundle_managementbundle_posttype')['images'][$index]['file'];

$image= new Image();

$image->setFile($image_file);
$image->setSubDir('hg');
$image->upload();
$em->persist($image);
$em->flush();
}


I use a class
UploadFileMover
that handle the file upload. I didn't write the following code but as I understand, an MD5 hash will be created from the original file name and used as filename. But the instance of
UploadedFile
contains a file name like "PHP"+number.tmp, not the original as stored in computer filesystem.

class UploadFileMover {

public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath)
{
$originalName = $file->getFilename();

$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;

$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;

$ext = $file->getExtension();

$i=1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);

} else {
$targetFilePath = $targetFilePath . $i++;
}
}

$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;

if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));

return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}

}


This class is instanciated when an image is uploaded. In other words, I have an Entity
Image
that has a method
upload
. Inside entity class:

public function upload()
{
if (null === $this->getFile()) {
return;
}

$uploadFileMover = new UploadFileMover();
$this->path = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDir(),$this->subDir);

$this->file = null;
}


I var_dumped the filename all across the different steps but I cannot figure out where it is transformed to PHP16653.tmp.

Can it be related to an APACHE related configuration? Your help is appreciated. I really did a lot of research for similar issue in the web to no avail.

Answer

The problem was created by the line:

$originalName = $file->getFilename();

Use:

$originalName = $file->getClientOriginalName();

instead.