I have a file manager written on PHP and I’m transfering all it’s logic to CakePHP 2.1, making it object oriented…

Yesterday I was working with the file upload section, that gets the file from the client and saves on the server, including saving some details of the file on the database. The difficult part was doing that using the CakePHP resources, because I didn’t knew them yet.

Example 1: I usually develop on Linux, that uses / for paths, but yesterday I was on Windows, that uses \. How to treat that??

Example 2: I was using PHP functions to create the directories (mkdir), remove directories (rmdir) and do the upload (move_uploaded_file). How to do that on CakePHP??

Two pages of the documentation were the kick start to solve my doubts:

http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html

To treat the directories path issue, I used the DS constant. Some people says that is useless to do that, but I prefered to use it. About the file upload directory, it’s located on app/webroot/files – To use that path, my code is as follows:

On the $localizacao var stays what comes from /files, because the WWW_ROOT constant takes me to the webroot.

http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html

Then came the part that generated more doubts. The link above has all the details to work with files and folders, but for me it was not exactly clear how to do the upload…

Searching references on Google, I found that one of the possible flows to file upload on CakePHP is:

1 – Read the file

2 – Store data on temporary var

3 – Close the file

4 – Start a file with desired destiny

5 – Write on it the temporary var data

6 – Close the new file

Look how my code is written:

This way, upload worked fine… Cool isn’t???

11 thoughts on “File Upload on CakePHP

  1. Olá, bom dia! Por favor, gostaria de saber como posso fazer o upload de um arquivo usando o form no CakePHP e salvar em um determinado diretório. A parte de salvar acho que poderia usar a que você explica aqui.

  2. Muito bacana esse tutorial Heitor. Parabéns cara! Salvou.
    Agora que começei a estudar cake mesmo. Agora vou tentar adotá-lo para meu desenvolvimento em php.
    Um abrçao. Valeu!

Leave a Reply to Nicolas Cancel reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.