Uploading and reading files with Yii

Hi everyone.

Yii is the first framework I am using.

I need to upload and read a file, how and where should I do this?

I mean, I don't need the entier code, but just an idea of what goes where, as I am not familiar with Yii or other frameworks.

Thank you.

Did you read this? http://www.yiiframew…doc/cookbook/2/

Thank you, I didn't see that, sorry.

Now, I don't need to store the uploaded file on the server, so is it possible to just read the file after it is uploaded?

Where would something like this go?:

$handle = @fopen("/tmp/inputfile.txt", "r");

if ($handle) {

    while (!feof($handle)) {

        $buffer = fgets($handle, 4096);

        // do a bunch of stuff and save to a database <-- really important!




Two main questions are:

1- where do I get the filename for fopen to read? maybe $image->file?

2- maybe the do a bunch of stuff and save to a database goes into a model? (I'm sorry, this MVC is new to me)

Other tips/ideas?

Thank you

Example just to get the general idea:

You have a controller (e.g.) SiteController and an action inside called uploadAction(). You also have a model e.g. uploads (you can create a model for your db table using the yii shell command)

In the action you check if the request is POST or not (check Yii::app()->request->isPostRequest).

If it is you then:

  • validate using your model's validate rules (read about validation scenarios too)

  • Now if the data validation goes well you can the save it to the database

  • if not, you re-render the form and you can display validation errors

If the request is not a POST request you just render the form that prompts the user to upload a file for example.

When the data are validated you can do for example:

$newRecord = new uploads; /* creates a new upload object  */

$newRecord->filename = $_POST['uploadedFile']; /* assigns the upload filename to the object */

$newRecord->save(); /* saves the record to your database */

Now in case you want for example to delete the uploaded file after this you can put some code in your model's afterSave() method.

All the above is only to give you a starting point, not best practise or anything, after all i'm not an expert of yii or anything.

P.S: read the documentation, it's all there and of course far better explained.