Yii 2 RESTful api upload single image

Upload image in Yii 2 REST API

Hey guys, here comes another year and another code snippeton how to upload images via Yii2 REST API.

I have made this extremely easy by commenting the code,in case you get stuck drop a comment ūüôā

public function actionSinglefile()
{
 
  \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  //response array
  $response = array();
  //create date string to be used a year
  $ymd = date("Ymd");
  //get the 'image' being send via api
  //Returns an uploaded file according to the given file input name.
  //The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').

  $uploadedFile = UploadedFile::getInstanceByName('image');
  if ($uploadedFile) {
    //get the uploaded file name
    $filename = $uploadedFile->name;
    //pathinfo() returns more info about the $uploadFile
    $pathinfo = pathinfo($uploadedFile);
    //create a new filename to avoid file collission
    $filename = $pathinfo['filename'].date('YmdHis').rand(10000,99999);
    //get extension
    $extension  = $uploadedFile->getExtension();
    //directory to save the image
    $save_path = \Yii::getAlias('@backend') . '/web/uploads/' . $ymd . '/';
    //check if dir already exists 
      if (!file_exists($save_path)) {
        //make dir ,give permissions
          mkdir($save_path, 0777, true);
        }
        //save file
      $uploadedFile->saveAs($save_path . $filename. '.' . $extension);
    return $response = array(
                              'fileinfo' => pathinfo($uploadedFile),
                              'filename' => $filename
                            );
  } else {
    return array(
                  'file' => $uploadedFile->error,
                );
  }

  
}

 

Yii REST API Guide

How to delete blank empty lines from your code

I will keep this short because again we devs like straight,brief and clear  instructions.

Assume you have such kind of code and you want to remove all these empty lines .How will you go about it?

<?php

// Heading

$_['heading_title']    = 'My Downloads';

$_['heading_title1']    = 'Add Download';



// Text

$_['text_success']     = 'Success: You have modified downloads!';

$_['text_upload']      = 'Your file was successfully uploaded!';

$_['text_loading']      = 'Loading..';



$_['text_edit']      = 'Edit';



$_['text_no_results']      = 'No Results Found';



// Column

$_['column_name']      = 'Download Name';

$_['column_remaining'] = 'Total Downloads Allowed';

$_['column_action']    = 'Action';



$_['column_date_added'] = 'Date Added';


 

Easy! us regular expressions.

Use^\n to be precise.

In your IDE use Find using Regular expressions and Replace.

Example

Find: ^\n

Replace with: (nothing,blank)
So the results of my code will be.

<?php
// Heading
$_['heading_title']    = 'My Downloads';
$_['heading_title1']    = 'Add Download';
// Text
$_['text_success']     = 'Success: You have modified downloads!';
$_['text_upload']      = 'Your file was successfully uploaded!';
$_['text_loading']      = 'Loading..';
$_['text_edit']      = 'Edit';
$_['text_no_results']      = 'No Results Found';
// Column
$_['column_name']      = 'Download Name';
$_['column_remaining'] = 'Total Downloads Allowed';
$_['column_action']    = 'Action';
$_['column_date_added'] = 'Date Added';

Looks good ūüôā

In case you have spaces in the line then you can use ^[\s]*?[\n\r]+

May you are wondering what all these regex thing is,have a look look at PHP Regex cheat sheet.

Cheat Sheet

[abc] A single character of: a, b or c
[^abc] Any single character except: a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a

Options

i case insensitive‚ÄÉ m treat as multi-line string‚ÄÉ s dot matches newline‚ÄÉ x ignore whitespace in regex‚ÄÉ A matches only at the start of string‚ÄÉ D matches only at the end of string‚ÄÉ U non-greedy matching by default

You have other great ways of doing this? let us know!

Donwload OpenCart 3x MultiVendor Extension

Log the URLs users visited in Yii 2

In this example we will use Yii 2 behavior to log the URLs user have visited on our Yii 2 powered application.
Lets get started.

1.Create a behavior folder in the commons directory,then create LogactionBehavior class.

<?php
namespace common\behaviors;

use Yii;
use yii\web\Controller;
use yii\base\Behavior;
use yii\web\Request;

class LogactionBehavior extends Behavior
{
    /**
     * 
     * @var yii\web\Request
     */
    private $request;

    /**
     * Use dependency injection to inject yii\web\Request
     * @param array $config
     * @param yii\web\Request  $request
     */
    public function __construct($config =[],Request $request)
    {
        parent::__construct($config);
        $this->request = $request;
    }

    /**
     * Activation of events
     * Register beforeAction to  Controller::EVENT_BEFORE_ACTION 
     * Register afterAction to Controller::EVENT_AFTER_ACTION 
     * @return array
     */
    public function events()
    {
        return [
            Controller::EVENT_BEFORE_ACTION => 'beforeAction',
            Controller::EVENT_AFTER_ACTION => 'afterAction'
        ];
    }

    /**
     * log
     */
    public function beforeAction()
    {
        $date =date("Y/m/d h:i:sa");
        $url = $this->request->url;
        $ip = $this->request->userIP;
        $params = $this->request->getRawBody();
        $log = $date."   ".$url."  ".$params."   ".$ip;
        Yii::info($log);
        Yii::beginProfile('myBenchmark');//log user activty toÔľĆmyBenchmark---change modify the name
    }

    public function afterAction()
    {
        Yii::endProfile('myBenchmark');//end analysis
    }
}

 

2 Controller behavior

public function behaviors()
{
    return [
        LogactionBehavior::className(),
    ];

 

3 Add to application configuration

'log'=>[
    'targets' => [
        [
            'class'=> 'yii\log\FileTarget',
            'levels' => ['info','profile'],
            'logVars' => [],
        ]

    ]
]

 

Get Yii RESTful guide

Create a Yii 2 Module

In this tutorial, you will learn how to generate and configure a Yii 2 module.

So letes get started!

First make sure you have installed Yii framework template,either basic or advanced template will do.

We will use Yii 2’s Gii tool to help you generate templates for the module.

To can access Yii 2 Gii tool navigate to yourdomain/index.php?r=gii .

                                                                                            Yii 2 Gii tool interface

Step 1: Select the Module Generator option

Step 2: Enter your module ID and Class

In this case my module ID is post and the Module class is backend\modules\post\PostModule.

 

C

Step 3: Click Preview button to preview then Generate button to generate the files shown in the preview.

Step 4: Add the Post module to your application configuration:

Add the Module class to your modules  configuration

'post' => [
            'class' => 'backend\modules\post\PostModule',
        ],

Add Module alias to to alias array

'aliases' => 
       ......
       'post' => '@backend/modules/post',
       ......
   ],
Module file structure

You now have your module! access it in the backend  by navigating to yourdomain/backend/post/default/index

Thanks for reading this far, if helpful let alot of folks know it.:)

Adding a new app in Yii2 Advanced app

Yii2 advanced app already contains three main folders (frontend,backend,common) that can help you to start your project.

As their names suggests,frontend can be used to create your apps front interface,the backend can be the administration end to manage the whole app.

The commons folder contains files or assets that are required by both the frontend and the backend.

Sometimes the three folders are not enough and you want to add an additional app (when building the next billion dollar business).How do you go about this?

First things first! Make sure you have installed Yii advanced template on your serve(I use XAMPP on my local computer).

For illustration purposes I have installed Yii 2 advanced template on the localhost.

Step 1: Make a new folder in the root directory name it anything you want (named shop in my case).

After this step you must be having an extra folder i.e frontend,common,backend and shop.

Step 2 :Copy the contents of frontend into the newly created shop folder.

Step 3 : Edit the config files

Navigate to shop/config folder and edit the config files.

You will have to change the app ID,controllerNamespace,app components like request and session in the main.php.

See example :

'id' => 'shop',
'controllerNamespace' => 'shop\controllers',

'components' => [
'request' => [
'csrfParam' => '_csrf-shopping-cart',

'cookieValidationKey' => 'fjdsjjkdkkassdsdd'
],
'session' => [
// this is the name of the session cookie used for login on the shopping-cart
'name' => 'frontend-shopping-cart',
]

]

 

Modify the controller and model namespace in the shop/controllers  and shop/models files (where applicable) .

 

Step 4: Add app alias to common/config/bootstrap.php

Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
Yii::setAlias('@shop', dirname(dirname(__DIR__)) . '/shop')

 

 

Step 5: Add your app to the .htaccess file .

This step will be optional depending on how you configured the .htaccess file.

# deal with shop
RewriteCond %{REQUEST_URI} ^/projects/YiiRestful/(shop)
RewriteRule ^shop/assets/(.*)$ shop/web/assets/$1 [L]
RewriteRule ^shop/css/(.*)$ shop/web/css/$1 [L]
RewriteRule ^shop/js/(.*)$ shop/web/js/$1 [L]
RewriteRule ^shop/images/(.*)$ shop/web/images/$1 [L]

 

Now you should be able to access your new app on http://localhost/projects/YiiRestful/shop/

Thats it guys, let me know your ideas¬† guys so that I can improve where possible ūüôā

 

Relate posts

Yii RESTful guide