Saturday 21 September 2013

Friday 20 September 2013

Yii: Single sign on for all subdomains

For example :
Now you have a main domain "mydomain.com" and there are some subdomains such as : id.mydomain.com , news.mydomain.com, blog.mydomain.com ...v.v. So how to with just one log in on "id.mydomain.com" a member can be logged in to the whole system.

It called "Single Sign-on". And we have some way to do it. This document will give you a basic solution with Yii framework.

The requirement:
+ All subdomain running on same server and can be share session.
+ Using same yii session class : CHttpSession or CDbHttpSession

The solution:
We have to configure these website using a same session and a same cookie.

Step 1 : open all main config file which you want to impact.
set a same id for them
array(
            'id' => 'siteID', // change it to same on all subdomain
            'name' => 'site name',
            'defaultController' => 'homepage',
            'theme' => 'web',
            ......
      );

Step 2 : Continue looking on main config files to session array.

* CHttpSession:
if you are using CHttpSession set Cookies params and savePath like this :
'session' => array(
                    'class'=>'CHttpSession',
                   // 'savePath' => dirname(__FILE__).'/../../session',  /*change session path to same folder if not using php default session*/
                    'cookieMode' => 'allow',
                    'cookieParams' => array(
                        'domain' => '.mydomain.com',
                    ),
                ),
CHttpSession save session in file so we just only need to config for all subdomain save session in a same folder. Session folder can be put anywhere but make sure that it is exists and can be access (chmod777).

* CDbHttpSession:
CDbHttpSession is not using savePath param so session array will like that :
'session' => array(
                    'class'=>'CDbHttpSession',
                    'cookieMode' => 'allow',
                    'cookieParams' => array(
                        'domain' => '.mydomain.com',
                    ),
                ),
Session is saved by CDbHttpSession in runtime fordel. we have to config to all application to a same runtime folder. Do it in main config array.
array(
            'id' => 'siteID', // change it to same on all subdomain
            'name' => 'site name',
            'defaultController' => 'homepage',
            'theme' => 'web',
            'runtimePath'=>dirname(__FILE__).'/../../runtime', // change runtime path
            ......
      );

Note : make sure savePath and runtimePath is exists and chmod 777 

Step 3 : Ok, now check your websites.

This is only a basic solution. With a bigger system we have to use more complex technologies such as OAuth 2.0


Apache: Set default virtual host for all new subdomains

It's so easy to auto config all new subdomain point to your vitual host.

NameVirtualHost *:80 

<VirtualHost *:80>
   ServerAdmin webmaster@defaultdomain.com
   DocumentRoot "/home/defaultdomain/www" 
   ServerName defaultdomain.com
   ServerAlias *.defaultdomain.com #apply for all subdomain#
   ErrorLog "/var/log/defaultdomain-error_log" 
   CustomLog "/var/log/defaultdomain-access_log" common
</VirtualHost>

So if you want to have a default website for all domain point to your server. How to do it ?

Apache use virtual host to run more than one website on a single Server. Each request will be match with respective website. If  the domain name is not configured in virtual host configuration file, Apache will run default website. That is the first virtual host configured so that to set a website is default for your server you have to put it on top of virtual host configuration file.


For example:

NameVirtualHost *:80 

#default website
<VirtualHost *:80>
   ServerAdmin webmaster@defaultdomain.com
   DocumentRoot "/home/defaultdomain/www" 
   ServerName defaultdomain.com
   ServerAlias www.defaultdomain.com
   ErrorLog "/var/log/defaultdomain-error_log" 
   CustomLog "/var/log/defaultdomain-access_log" common
</VirtualHost>

#other website
<VirtualHost *:80>
   ServerAdmin webmaster@otherdomain.com
   DocumentRoot "/home/otherdomain/www" 
   ServerName otherdomain.com
   ServerAlias www.otherdomain.com
   ErrorLog "/var/log/otherdomain-error_log" 
   CustomLog "/var/log/otherdomain-access_log" common
</VirtualHost>

Thursday 19 September 2013

Linux: show apache version

In most Linux system (Redhat, Centos, Ubuntu ....) you can try follow command to find out apache version.

# httpd -V
This will not list dynamically loaded modules included using the LoadModule directive. To dump a list of loaded Static and Shared Modules:
# httpd -M

Wednesday 18 September 2013

PHP: how to get current page url (Windows/IIS + Linux)

In many times we need to get current page url using PHP. But there are some different system parameters between Linux and Windows so that some function can be good in linux server but cannot run on Windows example Xampp on windows. The following solutions can solve the problem.

function getURL()
    {
        $pageURL = 'http';
        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { // SSL connection
            $pageURL .= 's';
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

You also can custom it to get other system parameters base on $_SEVER variable.
learn more : PHP $_SERVER manual.

Thursday 12 September 2013

PHP: Convert string to float or get float number from string

(float) function that is the fastest way and the fastest performance to convert a string to a float number.
For example :

echo (float) '154.256';                     // output 154.256
echo (float) '154.256dsgaddgvgf';    // output 154.256
echo (float) '154.256fsadfdsfa15';   // output 154.256
echo (float) 'fsdfdsafd154.256';       // output 0

* if you want to get a float from all numeric characters in string you can try following functions :

function getFloatFromString($string) {
     return (float) preg_replace('/[^0-9.]/', '', $string);
}

example :

echo getFloatFromString('abcdef152.685');       // output 152.685
echo getFloatFromString('abcdef152.6cs85');    // output 152.685
echo getFloatFromString('abcdef152.685fd');    // output 152.685

Wednesday 11 September 2013

Yii: Recoverable error - Object of class *** could not be converted to string

We get this error when call a function such as : findAllByAttributes, Find, FindAll, Chtml, .,.,
because one of your parameter type is not correct.

example :

Recoverable error


Object of class OAuthSession could not be converted to string

to solve it let check type of all parameters in that function. Make sure that all of them are string.

Sunday 8 September 2013

PHP: how to clear echo buffer

Sometimes we need to clear all previously output such as : echoed text, printed, buffer ....
"ob_get_clean()" is solution.

<?php
//ob_start(); // This function must be put at top of file. It will turn output buffering on, but not important because default is on
?>
Demo output !
<?php
echo "Hello World";
ob_get_clean();
?>

Wednesday 4 September 2013

PHP AES encrypt / decrypt

$sDecrypted and $sEncrypted were undefined in your code. See fixed solution:
$Pass = "Passwort";
$Clear = "Klartext";        

$crypted = fnEncrypt($Clear, $Pass);
echo "Encrypred: ".$crypted."</br>";

$newClear = fnDecrypt($crypted, $Pass);
echo "Decrypred: ".$newClear."</br>";        

function fnEncrypt($sValue, $sSecretKey)
{
    return rtrim(
        base64_encode(
            mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256,
                $sSecretKey, $sValue, 
                MCRYPT_MODE_ECB, 
                mcrypt_create_iv(
                    mcrypt_get_iv_size(
                        MCRYPT_RIJNDAEL_256, 
                        MCRYPT_MODE_ECB
                    ), 
                    MCRYPT_RAND)
                )
            ), "\0"
        );
}

function fnDecrypt($sValue, $sSecretKey)
{
    return rtrim(
        mcrypt_decrypt(
            MCRYPT_RIJNDAEL_256, 
            $sSecretKey, 
            base64_decode($sValue), 
            MCRYPT_MODE_ECB,
            mcrypt_create_iv(
                mcrypt_get_iv_size(
                    MCRYPT_RIJNDAEL_256,
                    MCRYPT_MODE_ECB
                ), 
                MCRYPT_RAND
            )
        ), "\0"
    );
}