RSS

Category Archives: Yii

htaccess in yii2 basic app

By: http://www.codematrics.com/

.htaccess is a configuration file, by which apache can handle redirects which are not written in php code. So for e.g.  if you want to redirect your users to specific page when 404 error comes, you can do it with a line of code in .htaccess file.

In Yii2 basic app, if you have chose pretty url enabled(and of course you want to make pretty url), than you need to add two htaccess files. Which are mentioned below with path information.

1. BasicApp ( root ) > .htaccess

2. BasicApp ( root ) > web > .htaccess

That’s it.

If you are going to enable pretty url, than you need to add below code snippet in web.php

All the best with .htaccess

And add

$baseUrl = str_replace('/web', '', (new \yii\web\Request)->getBaseUrl());

to head of web.php

and add

'components' => [
    'request' => [
        // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
        'cookieValidationKey' => 'dMDKbOHxH3zzTpLq_6RAqVhn8R6zWY9F',
        'baseUrl' => $baseUrl,
    ],

Copy from: http://www.codematrics.com/htaccess-in-yii2-basic-app/

 
Leave a comment

Posted by on February 17, 2016 in PHP, Yii

 

Yii2 htaccess – How to hide frontend/web and backend/web COMPLETELY

By: mohit

 

Step 1

Create .htaccess file in root folder, i.e advanced/.htaccess and write below code.

Options +FollowSymlinks
RewriteEngine On

# deal with admin first
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^admin/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^admin/css/(.*)$ backend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/  <------
RewriteCond %{REQUEST_URI} ^/(admin)  <------
RewriteRule ^.*$ backend/web/index.php [L]


RewriteCond %{REQUEST_URI} ^/(assets|css)  <------
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/  <------
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php

Note : if you are trying in local server then replace ^/ with ^/project_name/ where you see arrow sign. Remove those arrow sign <------ after setup is done.

Step 2

Now create a components/Request.php file in common directory and write below code in this file.

namespace common\components;


class Request extends \yii\web\Request {
    public $web;
    public $adminUrl;

    public function getBaseUrl(){
        return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
    }


    /*
        If you don't have this function, the admin site will 404 if you leave off 
        the trailing slash.

        E.g.:

        Wouldn't work:
        site.com/admin

        Would work:
        site.com/admin/

        Using this function, both will work.
    */
    public function resolvePathInfo(){
        if($this->getUrl() === $this->adminUrl){
            return "";
        }else{
            return parent::resolvePathInfo();
        }
    }
}

Step 3

Installing component. Write below code in frontend/config/main.php and backend/config/main.phpfiles respectively.

//frontend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/frontend/web'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

// backend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/backend/web',
    'adminUrl' => '/admin'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

Thats it! You can try your project with
http://www.project.com/admin, http://www.project.com

in local server
localhost/project_name/admin, localhost/project_name

 

Copy from: http://stackoverflow.com/questions/28118691/yii2-htaccess-how-to-hide-frontend-web-and-backend-web-completely

 
3 Comments

Posted by on October 8, 2015 in PHP, Yii

 

Error 500 and 404 when using .htaccess for removing index.php

By: Sochinda

Enable mod_rewrite in apache

  1. Enable ReWrite mode in Apache2
    $ sudo a2enmod rewrite
    $ sudo service apache2 restart
  2. Edit site-enable configuration
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
    </Directory>
    
  3. Add .htaccess
    Options +FollowSymLinks
    IndexIgnore */*
    
    <IfModule mod_rewrite.c>
     RewriteEngine on
    
     #RewriteBase /
    
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
    
     RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]
    
    </IfModule>
  4. Restart Apache2 Service
 
Leave a comment

Posted by on May 19, 2015 in Apache2, Yii

 

Installing the PHP mcrypt extension on OSX 10.9

By:  Jens segers on Nov 05 2013

The following steps will explain you how to install the mcrypt extension for the default PHP version (5.4.24) that is shipped with OSX Mavericks. You need this extension for stuff like Laravel and phpMyAdmin. Otherwise you will get this error:

Mcrypt PHP extension required.

Step 1: Install autoconf and mcrypt

I used homebrew to install autoconf and mcrypt, which is as easy as:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

 

brew install autoconf mcrypt

If this does not work for you, or you don’t want to use homebrew, then check out this tutorial.

Step 2: Build the PHP extension

To build the PHP extension you will need the PHP 5.4.17 source code that is available for download here and extract it:

cd ~/Downloads
unzip PHP-5.4.17.zip

Then build the extension using the following commands:

cd php-src-PHP-5.4.17/ext/mcrypt/
/usr/bin/phpize
./configure
make
sudo make install

Step 3: Enable the extension

All that is left is to enable the extension by editing /etc/php.ini. If this file is not present, copy /etc/php.ini.default and rename it:

sudo cp /etc/php.ini.default /etc/php.ini

Edit the /etc/php.ini file and add the following:

extension=mcrypt.so

Step 4: Restart apache

Now just restart apache and you’re done!

sudo apachectl restart

 

Copy from: http://jenssegers.be/blog/49/installing-the-php-mcrypt-extension-on-osx-10-9 and

 
Leave a comment

Posted by on October 1, 2014 in Mac, PHP, Yii

 

Yii: use ajax function via htmlOptions attribute

By: lars

If you want to trigger an ajax call on a Yii form element onchange, you can pass an array of ajax attributes as one of the “htmlOptions” like so:

<?php echo $form->textField($model,'my_input_field',array(
	'ajax' => array(
		'type'=>'POST', //request type
		'url'=>$this->createUrl('site/ajaxAction'), // url to call controller action
		'success'=>' function(data) { $(\'#my_output_field\').val(data) }',// function to call onsuccess 
             // "data" is returned data and function can be regular js or jQuery
             // here we are are updating the value of another field that has id "my_output_field"
	),
	'size'=>60,
	'maxlength'=>128,
)); ?>

and the (site) controller action would look something like:

public function actionAjaxAction() {
  [check/filter inputs...]
  [data functions...]
  echo $my_val_string;
  Yii::app()->end()
}
 
Leave a comment

Posted by on July 11, 2012 in Yii

 

Creating a CSS Driven Drop Down Menu using CMenu

By: Yii

CMenu offers great functionality and the ability to customize just about every aspect of the output. There are many times when I need to create a drop down menu or simply modify the look to make the designers happy. Because this seems to be a common task for me, I figured I would share my code to create a very simple drop down menu that other people could use.

There are many ways to approach this but I wanted to start out very simply so we are going to accomplish this using nothing but CSS.

Here is our desired output:

<div id="menu-top"> 
  <ul id="yw1">
    <li id="itemCompany"><a id="menuCompany" href="/company/index">Company</a>
      <ul>
        <li class="active"><a href="/company/index">Our Mission</a></li>
        <li><a href="/company/aboutUs">About Us</a></li>
        <li><a href="/company/careers">Careers</a></li>
        <li><a href="/company/contactUs">Contact Us</a></li>
        <li><a href="/company/storeLocator">Store Locator</a></li>
      </ul>
    </li>
    <li><a id="menuBlog" href="/blog/post/index">Blog</a></li>
    <li id="itemChange"><a id="menuChange" href="/change/index">Change</a>
      <ul>
        <li><a href="/change/index">Community Involvement</a></li>
        <li><a href="/change/ecoPolicy">Eco Responsibility</a></li>
        <li><a href="/change/responsibility">Responsibility</a></li>
      </ul>
    </li>
    <li><a id="menuBuy" href="/shop">Shop</a></li>
  </ul>
</div>

And here is the code we are going to use to create this output:

<div id="menu-top">
<?php
$this->widget('zii.widgets.CMenu',array(
  'activeCssClass'=>'active',
  'activateParents'=>true,
  'items'=>array(
    array(
      'label'=>'Company',
      'url'=>array('/company/index'),
      'linkOptions'=>array('id'=>'menuCompany'),
      'itemOptions'=>array('id'=>'itemCompany'),
      'items'=>array(
        array('label'=>'Our Mission', 'url'=>array('/company/index')),
        array('label'=>'About Us', 'url'=>array('/company/aboutUs')),
        array('label'=>'Careers', 'url'=>array('/company/careers')),
        array('label'=>'Contact Us', 'url'=>array('/company/contactUs')),
        array('label'=>'Store Locator', 'url'=>array('/company/storeLocator')),
      ),
    ),
    array(
      'label'=>'Blog',
      'url'=>array('/blog/post/index'),
      'linkOptions'=>array('id'=>'menuBlog')
    ),
    array(
      'label'=>'Change',
      'url'=>array('/change/index'),
      'linkOptions'=>array('id'=>'menuChange'),
      'itemOptions'=>array('id'=>'itemChange'),
      'items'=>array(
        array('label'=>'Community Involvement', 'url'=>array('/change/index')),
        array('label'=>'Eco Responsibility', 'url'=>array('/change/ecoPolicy')),
        array('label'=>'Responsibility', 'url'=>array('/change/responsibility')),
      ),
    ),
    array(
      'label'=>'Shop',
      'url'=>array('/shop'),
      'linkOptions'=>array('id'=>'menuBuy')
    ),
  ),
)); ?>
</div>

Let’s dig into the code to see what is happening here.

CMenu::activeCssClass is simply the CSS class that will be assigned to the active menu item. The active menu item simply indicates the current page you are viewing by adding some style to that menu link.CMenu::activateParents means that when a child item is activated, the parent of that item will be given the ‘active’ css class assignment as well.

You will notice that the ‘Company’ item has another CMenu::items array set under it that will be the items that show up in the drop down when a user hovers over ‘Company’ in the menu.

Also, in the parent items ( Company, Blog, Affecting Change, Shop ) you will see that we take advantage of theCMenu::linkOptions property in order to add an ID to tag that Yii will output wrapping the label. I needed to do this because the menu I am creating uses sprites which means I need an ID for each menu item to specify the background-position property of each item independently.

Ok so now that we have our PHP setup, let’s dig into the CSS part. I am also not going to include the code for the sprites to keep things simple.

#menu-top ul { list-style: none; margin: 0; padding: 0; position: relative; height: 30px; }

#menu-top ul li { display: block; height: 28px; float: left; overflow: visible; }
#menu-top ul li:hover > ul { display: block; }

#menu-top ul li a { float: left; display: block; }

#menu-top ul li ul { display: none; position: absolute; top: 100%;
                    background: #000; color: #fff; height: auto;
}

#menu-top ul li ul li a { color: #ccc; padding: 4px 14px; display: block; }

#menu-top ul li ul li.active a,
#menu-top ul li ul li a:hover { color: #fff; }

An important part to pay attention to is setting the overflow to visible on the ‘#menu-top ul li’ elements. Otherwise, when you mouseover an parent item, the child items will not be visible.

The line that does all the magic is: #menu-top ul li:hover > ul { display: block; }

This simply means that when a user hovers over a parent item ( ul li ), take any child ul elements and switch them from ‘display: none;’ to ‘display: block;’ making them visible.

Once you put this all together, you should have a nice little drop down menu with active highlighting.

Referenced by: http://www.yiiframework.com/wiki/211/creating-a-css-driven-drop-down-menu-using-cmenu/

 
1 Comment

Posted by on July 8, 2012 in Yii

 

How to create a Custom Pagination Widget for Yii Framework

By:

Agile Web Application Development with Yii 1.1 and PHP5Yii Framework is great, I truly like this framework, makes complicated things an easy task and its learning curve quite easy. But… yeah man, is always a but… what happens to all those fellow programmers, like me, that do not like the way ‘automated things’ are? Where are the tutorials to change and improve the framework and make it work just the way we like? There are not many around…

Again, a programmer needs to investigate the guts of the framework, in order to find out how to properly do it. But don’t worry, if you have a question in the format: would I be able to do this with Yii? The answer will be always positive. It is a great framework.

So, I would like to share with you guys my personal experience and put some small tutorials to ‘open’ the minds of others begginning with this framework. This will be the first of a set of small tuts on this Framework.

Creating a Custom Pagination Widget

A pagination Widget is the responsible of displaying a set of numbered links that lead to different pages of target. When you first create a Web application through the yiic tool – this tool creates the skeleton of the application, the automated CMS works with CLinkPager widget and its style and Page Links were not suitable for my project. My project had to end up making AJAX calls and its STYLE like the following picture:

Please not that if you want to just change its style, you can create a skin as exposed here:http://www.yiiframework.com/doc/guide/topics.theming#customizing-widgets-globally. Once I look at the code, I realized that creating a custom widget was easier than I thought. The first thing we need to do is to extend our new Widget class from CLinkPager, my class is named SimplaPager as I have used a template admin theme called SIMPLA.

1
class SimplaPager extends CLinkPager

Now, there are three methods to override from our father and grandfather classes (CLinkPager and CBasePager). The parent methods we need to override are run and createPageButtons and from our grandfather class createPageUrl.

a)  run Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public function run()
{
     //
     // here we call our createPageButtons
     //
     $buttons=$this->createPageButtons();
     //
     // if there is nothing to display return
     if(empty($buttons))
          return;
     //
     // display the buttons
     //
     echo $this->header; // if any
     echo implode("&nbsp;",$buttons);
     echo $this->footer;  // if any
 }

b) createPageButton Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Creates a page button.
 * You may override this method to customize the page buttons.
 * @param string the text label for the button
 * @param integer the page number
 * @param string the CSS class for the page button. This could be 'page', 'first', 'last', 'next' or 'previous'.
 * @param boolean whether this page button is visible
 * @param boolean whether this page button is selected
 * @return string the generated button
 */
protected function createPageButton($label,$page,$class,$hidden,$selected)
{
       //
       // CSS_HIDDEN_PAGE and CSS_SELECTED_PAGE
       // are constants that we use to apply our styles
       //
    if($hidden || $selected)
        $class=' '.($hidden ? self::CSS_HIDDEN_PAGE : self::CSS_SELECTED_PAGE);
    $class .= ' number';
       //
       // here I write my custom link - site.call is a JS function that takes care of an AJAX call
       //
    return CHtml::link($label,'#',array(
                'class'=>$class,
                'onclick'=>"site.call(CONST_MAIN_LAYER,'{$this->createPageUrl($this->getController(),$page)}');"));
}

c) createPageUrl Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Creates the URL suitable for pagination.
* This method is mainly called by pagers when creating URLs used to
* perform pagination. The default implementation is to call
* the controller's createUrl method with the page information.
* @param CController the controller that will create the actual URL
* @param integer the page that the URL should point to. This is a zero-based index.
* @return string the created URL
*/
public function createPageUrl($controller,$page)
{
    // HERE I USE POST AS I DO AJAX CALLS VIA POST NOT GET AS IT IS BY
    // DEFAULT ON YII
    $params=$this->getPages()->params===null ? $_POST : $this->getPages()->params;
    if($page>0) // page 0 is the default
       $params[$this->getPages()->pageVar]=$page+1;
   else
      unset($params[$this->getPages()->pageVar]);
   return $controller->createUrl($this->getPages()->route,$params);
}

Styling is controlled by a couple of constants in CLinkPager class, so the only thing we need to do is to override those constants.

1
2
const CSS_HIDDEN_PAGE='hidden';
const CSS_SELECTED_PAGE='current';

How to use the Widget

In order to use this widget first we create a widget subfolder in our application’s protected folder (in my case I saved a file named SimplaPager.php) and call it in our views like this:

1
2
3
$this->widget('application.widgets.SimplaPager', array(
    'pages'=>$pagination,
));

I have created another widget to display records in a table because I had the same problems than with the pagination so I use the the pagination within the Table Widget I created like this:

1
2
3
4
5
/**
 * @var array the configuration for the pager. Defaults to <code>array('class'=>'CLinkPager')</code>.
* @see enablePagination
 */
public $pager=array('class'=>'application.widgets.SimplaPager');

I promise I will discuss how to create a Table Widget in the next post :) . Nevertheless, you can view how both widgets look at the end:

SimplaTable and SimplaPager working together

DOWNLOAD

Please remember than this class has some AJAX calls in its createPageButton function that is exclusive for my project. Change that part to suit your needs. This class was for you to better understand how to create custom Widgets by extending those from Yii framework.

 
1 Comment

Posted by on July 7, 2012 in Yii