php - Get file extension after file is uploaded and moved in Symfony2 -


i'm uploading file through symfony2 , trying rename original in order avoid override same file. doing:

$uploadedfile = $request->files; $uploadpath = $this->container->getparameter('kernel.root_dir') . '/../web/uploads/';  try {     $uploadedfile->get('avatar')->move($uploadpath, $uploadedfile->get('avatar')->getclientoriginalname()); } catch (\ exception $e) {     // set error 'can not upload avatar file' }  // right filename $avatarname = $uploadedfile->get('avatar')->getclientoriginalname(); // wrong extension meaning empty, why?  $avatarext = $uploadedfile->get('avatar')->getextension();  $resource = fopen($uploadpath . $uploadedfile->get('avatar')->getclientoriginalname(), 'r'); unlink($uploadpath . $uploadedfile->get('avatar')->getclientoriginalname()); 

i renaming file follow:

$avatarname = sptrinf("%s.%s", uniqid(), $uploadedfile->get('avatar')->getextension()); 

but $uploadedfile->get('avatar')->getextension() not giving me extension of uploaded file give wrong filename jdsfhnhjsdf. without extension, why? right way rename file after or before move end path? advice?

well, solution simple if know it.

since moved uploadedfile, current object instance cannot used anymore. file no longer exists, , getextension return in null. new file instance returned move.

change code (refactored clarity):

    $uploadpath = $this->container->getparameter('kernel.root_dir') . '/../web/uploads/';      try {         $uploadedavatarfile = $request->files->get('avatar');          /* @var $avatarfile \symfony\component\httpfoundation\file\file */         $avatarfile = $uploadedavatarfile->move($uploadpath, $uploadedavatarfile->getclientoriginalname());          unset($uploadedavatarfile);     } catch (\exception $e) {         /* if don't set $avatarfile default file here          * cannot execute next instruction.          */     }      $avatarname = $avatarfile->getbasename();     $avatarext = $avatarfile->getextension();      $openfile = $avatarfile->openfile('r');     while (! $openfile->eof()) {         $line = $openfile->fgets();         // here...     }     // close file     unset($openfile);     unlink($avatarfile->getrealpath()); 

(code not tested, wrote it) hope helps!


Comments

Popular posts from this blog

angularjs - Redirect to a new template in angular js -

Oracle SQL. How to select specific IDs where value of columns specify criteria? -

Desktop Launcher for Python Script Starts Program in Wrong Path (Linux) -