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

file upload

in controller i have this now

if ($request->hasFiles() == true)
        {
          $path = 'uploads' . DIRECTORY_SEPARATOR . 'advertisements' . DIRECTORY_SEPARATOR . 'image_id_' . $advert->id;
          $errors = array();
          foreach ($_FILES['CreateAdvert']['tmp_name'] as $key => $tmp_name)
          {
            $file_name = $_FILES['CreateAdvert']['name'][$key];
            $file_size = $_FILES['CreateAdvert']['size'][$key];
            $file_tmp = $_FILES['CreateAdvert']['tmp_name'][$key];
            $file_type = $_FILES['CreateAdvert']['type'][$key];
            //echo var_dump($file_name);
            //echo var_dump($file_size);
            if ($file_size > 2097152)
            {
              $errors[] = 'Размер файла не больше 2 мегабайт';
            }
            $extensions = array(
              "jpeg",
              "jpg",
              "png",
              "jpeg");
            $file_ext = explode('.', $file_name);
            $file_ext = strtolower(end($file_ext));
            if (in_array($file_ext, $extensions) === false)
            {
              $errors[] = "Недопустимый формат файла, допускаются изображения форматов: jpg, gif, png, jpeg";
            }
            if (empty($errors) == true)
            {
              if (is_dir($path) == false)
              {
                mkdir("$path", 0777); // Create directory if it does not exist
              }
              if (is_dir("$path/" . $file_name) == false)
              {
                move_uploaded_file($file_tmp, $path . DIRECTORY_SEPARATOR . $file_name);
              }
              else
              { //rename the file if another one exist
                $new_dir = $path . $file_name . time();
                rename($file_tmp, $new_dir);
              }
            }
            else
            {
              foreach ($errors as $error)
              {
                $this->flash->notice((string )$error);
              }
              return $this->forward('posts/new');
            }
          }
        }

how can i inplement this in model i need this in beforSave() for multiple files



32.5k
edited Oct '14
$request = new Phalcon\Http\Request();

in any place you want. Request is a singleton in phalcon, you always will get actually current request with all related data.

To access DI services from any phalcon class you can use $this->getDI():

$this->getDI()->getFlash();
$this->getDI()->get('flash');

Direct "$this->flash" in Controller is a 'magic' field, just for convenience. It's not a basic usage for getting access to DI service.

Also forward() would be unnecessary in Model.

All other code you can just copy-past as is.