PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 9, 2022

[FIXED] Uploading image to with custom name in Yii framework

 January 09, 2022     image-uploading, php, yii, yii-cactiverecord, yii-cformmodel     No comments   

Issue

I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:

//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
    $upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part

The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?


Solution

The problem has been solved through following code:

$uploadFile = CUploadedFile::getInstance($personModel, 'picture');
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
$fileName = $userModel->username . '.' . $extension;

if (isset($uploadFile)) {
    $personModel->picture = $fileName;
    $uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
}


Answered By - Muminur Rahman
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing