We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Looking for the correct upload file's script example

Hi guys, I got trouble when create an uploading file function based on the official doc (https://docs.phalcon.io/en/latest/reference/request.html#uploading-files) It seems the script below doesn't work properly,

$file->moveTo('files/' . $file->getName());

So, could you help me to fix that by providing the correct code or example ?

Thanks



58.4k

Hi

Are you sure chmod files dictory?

Here example my code move file into public/img/sinhvien

        public function uploadImg($name=null){
          // Check if the user has uploaded files
          if ($this->request->hasFiles() == true) {

              // Print the real file names and sizes
              foreach ($this->request->getUploadedFiles() as $file) {
                  //Print file details
                  // echo "<pre>";
                  // print_r($file->getType());
                  // print_r($_FILES);
                  // echo $file->getName(), " ", $file->getSize(), "\n";
                  if (preg_match('/^image\/(x-)?png$/i',$file->getType())){
                      $ext = '.png';
                      //Move the file into the application
                      $file->moveTo('img/sinhvien/'.$name.$ext);
                      return true;

                  }
                  else{
                      return false;
                  }

              }
          }
          return true;
    }

Please Have a check at your error log. Most of time it's a permission issue

Thanks for your replies guys, So, if it only the permission issue, what proper 'chmod' for my upload folder?



21.8k
Accepted
answer

@zahroul it depens on the user that runs the webserver and on your security policy.

Then if you run local or dev (you dont mind about security) application just do chmod -R 777 path/to/upload/dir and it will solve problem . If you are on production, and you need max security just do chmod -R 700 path/to/upload/dir then chown -R www-data:www-data path/to/dir. But just remember that your user needs write access on the directory

By the way I use to chown it to the user that runs the webprocess. For instance default for debian/apache would be chown -R www-data:www-data path/to/dir

The important is to be sure of what you do with permission.

edited Apr '14

Your suggestion works Soufiane, thanks