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

Converting your OpenCart Extensions to OpenCart 3x the easy way

Hi there!

OpenCart 3x version already out and I am sure some guys like me are struggling to get their extensions updated to fit the Twig templating Engine introduced in OpenCart 3.

I will summarize what I have learnt and also give you some tricks I got from the OpenCart page.

Use regular expressions in PHP IDE to mass search and replace.

This will save you hours of going through your files one by one.

-Be careful with it,make sure you understand the regex before you do anything.

Examples given by OpenCart

The format used here is:

-Example

-Regex

-Replace

Eg

Example: <?php echo $var; ?>

Regex: <\?php echo [$](\w*\b)[;] \?\>

Replace: {{ $1 }}
<?php echo $error_name[$language['language_id']]; ?>

<\?php\s+echo\s+[$](\w+)\[[$](.*)\[\'(.*)\'\]\]\; \?\>

{{ $1[$2.$3] }}
<?php $attribute_row = 0; ?>

<\?php [$](\w*\b) = 0[;] \?\>

{% set $1 = 0 %}
<?php $filter_row++; ?>

<\?php [$](\w*\b)\+\+\; \?\>

{% set $1 = $1 + 1 %}

 

<?php echo $var['key']; ?>

<\?php echo [$](\w*\b)\[\'(\w*\b)\'\]; \?>

{{ $1.$2 }}

 

<?php if ($error_height) { ?>

<\?php if \([$](\w+\b)\) \{ \?\>

{% if $1 %}

 

<?php if (isset($error_name[$language['language_id']])) { ?> 
<\?php\s+if\s+\(isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\) \{ \?\> 
{% if $1[$2.$3] %}

 

<?php if (in_array($category['category_id'], $selected)) { ?> 
<\?php if \(in_array\([$](\w+\b)\[\'(.*\b)\'\], [$](\w+\b)\)\) \{ \?\>
{% if $3 in $1.$2 %}
<?php if (in_array($marketplace_code, $marketplaces_processing)) { ?> 
<\?php if \(in_array\([$](\w+\b), [$](\w+\b)\)\) \{ \?\>
 {% if $1 in $2 %}
<?php if ($attribute_group['attribute_group_id'] == $attribute_group_id) { ?> 
<\?php if \([$](\w+\b)\[\'(.*\b)\'\] == [$](.*\b)\) \{ \?\>
 {% if $1.$2 == $3 %}
<?php if ($custom_field['type'] == 'date') { ?> 
<\?php if \([$](\w+\b)\[\'(.*\b)\'\] == \'(.*\b)\'\) \{ \?\> 
{% if $1.$2 == '$3' %}
<?php if ($sort == 'pd.name') { ?>
 <\?php\s+if\s+\([$](\w+\b) == \'(.*\b)\'\)\s+\{\s+\?\> 
{% if $1 == '$2' %}
<?php if ($voucher['order']) { ?>
 <\?php if \([$](\w+\b)\[\'(\w+\b)\'\]\) \{ \?\> 
{% if $1.$2 %}
<?php if (!$shipping) { ?> 
<\?php if \(\![$](\w+\b)\) \{ \?\> 
{% if not $1 %}
<?php echo (isset($account_custom_field[$custom_field['custom_field_id']]) ? $account_custom_field[$custom_field['custom_field_id']] : $custom_field['value']); ?>

<\?php\s+echo\s+\(isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\s+\?\s+[$](.*\b)\[[$](.*\b)\[\'(.*\b)\'\]\] : [$](.*\b)\[\'(.*\b)\'\]\);\s+\?\>

{% if $1[$2.$3] %} {{ $4[$5.$6] }} {% else %} {{ $7.$8 }} {% endif %}
<?php echo (isset($account_custom_field[$custom_field['custom_field_id']]) ? $account_custom_field[$custom_field['custom_field_id']] : ''); ?>

<\?php\s+echo\s+\(isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\s+\?\s+[$](.*\b)\[[$](.*\b)\[\'(.*\b)\'\]\] : \'\'\);\s+\?\>

{% if $1[$2.$3] %} {{ $4[$5.$6] }} {% endif %}
<?php echo isset($information_description[$language['language_id']]) ? $information_description[$language['language_id']]['description'] : ''; ?>

<\?php\s+echo\s+isset\([$](\w+\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\)\s+\?\s+[$](.*\b)\[[$](.*\b)\[\'(.*\b)\'\]\]\[\'(.*\b)\'\] : \'\';\s+\?\>

{% if $1[$2.$3] %} {{ $4[$5.$6].$7 }} {% endif %}

 

<?php } elseif ($percentage) { ?>

<\?php \} elseif \([$](\w+\b)\) \{ \?\>

{% elseif $1 %}
<?php } elseif ($amazon_login_button_size == 'large') { ?>

<\?php \} elseif \([$](\w+\b) == \'(.*\b)\'\) \{ \?\>

{% elseif $1 == '$2' %}
<?php } elseif ($percentage < 0) { ?>

<\?php \} elseif \([$](\w+\b) \> 0\) \{ \?\>

{% elseif $1 in < 0 %}
<?php foreach ($var1 as $var2) ?>

<\?php foreach \([$](.*\b) as [$](.*\b)\) \{ \?\>

{% for $2 in $1 %}

<?php foreach ($custom_field['custom_field_value'] as $custom_field_value) { ?>

<\?php foreach \([$](.*\b)\[\'(.*\b)\'\] as [$](\w+)\) \{ \?\>

{% for $3 in $1.$2 %}
<?php foreach ($setting['returns']['paidby'] as $v) { ?>

<\?php foreach \([$](.*\b)\[\'(.*\b)\'\]\[\'(.*\b)\'\] as [$](\w+)\) \{ \?\>

{% for $4 in $1.$2.$3 %}
<?php foreach ($marketplaces as $id => $name) { ?>

<\?php foreach \([$](\w+)\s+as\s+[$](\w+)\s+=\>\s+[$](\w+)\)\s+\{ \?\>

{% for $2, $3 in $1 %}
<?php foreach ($capture['shipping_info'] as $key => $shipping_info) { ?>

<\?php foreach \([$](.*)\[\'(.*)\'\]\s+as\s+[$](.*)\s+=\>\s+[$](\w+)\)\s+\{ \?\>

{% for $3, $4 in $1.$2 %}

Close the ifs and for statements manually with the below syntax.

{% endif %}

{% endfor %}
<?php if ($rating == 2) { ?>//change 2 to any number 
<\?php\s+if\s+\([$](\w+\b) == \d\)\s+\{\s+\?\>
{% if $1 == $2 %}

 

Get module,controller and action ID in Yii 2

This tutorial will show you how to get the module ID,controller ID and action ID.

1.From the Views

Module ID $this->context->module->id
Controller ID $this->context->id
Action ID $this->context->action->id

2.From the controller

 Module ID   Yii::$app->controller->module->id;
 Controller ID   Yii::$app->controller->id
 Action ID  Yii::$app->controller->action->id; or
Module ID       $this->module->id;
Controller ID   $this->id;
Action ID       $this->action->id;

3.in the beforeAction method

Module ID      $action->controller->module->id;
Controller ID   $action->controller->id;
Action ID       $action->id;

Now you know it! Let us know your views so that we help where possible. 🙂

Get Yii RESTful guide manual

Using Yii aliases

Aliases are used to represent file paths or URLs so that you don’t have to hard-code absolute paths or URLs in your project. An alias must start with the @ character to be differentiated from normal file paths and URLs. Alias defined without leading @ will be prefixed with @ character.

Yii has many pre-defined aliases already available. For example, the alias @yii represents the installation path of the Yii framework; @web represents the base URL for the currently running Web application.[Adapted from Yii guide]

In this example you will learn how to use aliases to read files from a certain directory in your app.

First set an alias using Yii:setAlias method in common/config/bootstrap.php

Yii::setAlias('@shopfolders', dirname(dirname(__DIR__)). '/uploads/');

 

Now we can access the alias anywhere in the app using Yii:getAlias(@shopfolders)

Add a controller action that will handle the reading of folders

public function actionDetails()
{
    $dir = Yii::getAlias('@shopfolders').'/';
    $files = array();
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               // echo 
                //$files[]['filename'] = $file;
                //$files[]['filetype'] = filetype($dir . $file);
                if ($file != '.' && $file != '..') {
                    $files[] = array('filename' => $file,
                    'filetype' => filetype($dir . $file)
                 );
                }
                
            }
            closedir($dh);
        }
    }

    return $this->render('details',[
    'files'=>$files
        ]);
}

 

The view file

<?php
/* @var $this yii\web\View */
?>
<div>
<ul>
<?php
foreach ($files as $file) {
  echo "<li>".$file['filename']."    ". $file['filetype']."</li>";
}
//var_dump(json_encode($files));
?>
</ul>	
</div>

 

That is it! 🙂

Example of output

Get Yii 2 RESTful guide

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