Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, 7 November 2022

PHP Convert Hex String to String

How to decode Hex String to String?

Ex: Decode Hex String to get JWT token when integrating Apple ID login


Solved

Hex string is a data type commonly used for transmission over the internet in the lower network layers. In some cases PHP will need to manipulate this data type directly. To handle them, PHP provides us with the "pack" function to manipulate Hex and binary string data.

Ex:


$stringHexData = "65794a68624763694f694a49557a49314e694973496e523563434936496b705856434a392e65794a7063334d694f694a6f64485277637a6f764c3246776347786c61575175595842776247557559323974496977695958566b496a6f69593239744c6e4e68625842735a533568634841694c434a6c654841694f6a45324d5459354f4455794e6a4973496d6c68644349364d5459784e4449314d444d334d69776963335669496a6f694d4441774e7a677a4c6d4e6b5a6a45354d47526b4d544130595452685a6a42694e6d49774e6a63784d3249344d4455304d6a52694c6a45304d5451694c434a6a58326868633267694f694a7852557035546d7473556d4a5a626c46565679316b646d6774536b7452496977695a573168615777694f694a7a59573177624756415a3231686157777559323974496977695a57316861577866646d567961575a705a5751694f694a30636e566c4969776959585630614639306157316c496a6f784e6a45324f5441774d7a63794c434a756232356a5a56397a6458427762334a305a5751694f6e527964575573496e4a6c5957786664584e6c636c397a6447463064584d694f6a4a392e764b6c394873303057587463426851796f47326742766a744375394d5878787471674e46777854772d5034";

$stringData = pack("H*",$stringHexData);

echo $stringData;

Result (JWT String): 


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiY29tLnNhbXBsZS5hcHAiLCJleHAiOjE2MTY5ODUyNjIsImlhdCI6MTYxNDI1MDM3Miwic3ViIjoiMDAwNzgzLmNkZjE5MGRkMTA0YTRhZjBiNmIwNjcxM2I4MDU0MjRiLjE0MTQiLCJjX2hhc2giOiJxRUp5TmtsUmJZblFVVy1kdmgtSktRIiwiZW1haWwiOiJzYW1wbGVAZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOiJ0cnVlIiwiYXV0aF90aW1lIjoxNjE2OTAwMzcyLCJub25jZV9zdXBwb3J0ZWQiOnRydWUsInJlYWxfdXNlcl9zdGF0dXMiOjJ9.vKl9Hs00WXtcBhQyoG2gBvjtCu9MXxxtqgNFwxTw-P4

More 

In addition, the "pack" function also supports other data types. 


possible values of format are:
a – string which is NUL-padded
A – string which is SPACE-padded
h – low nibble first Hex string
H – high nibble first Hex string
c – signed character
C – unsigned character
s – signed short (16 bit, machine byte order)
S – unsigned short ( 16 bit, machine byte order)
n – unsigned short ( 16 bit, big endian byte order)
v – unsigned short ( 16 bit, little endian byte order)
i – signed integer (machine dependent byte order and size)
I – unsigned integer (machine dependent byte order and size)
l – signed long ( 32 bit, machine byte order)
L – unsigned long ( 32 bit, machine byte order)
N – unsigned long ( 32 bit, big endian byte order)
V – unsigned long ( 32 bit, little endian byte order)
f – float (machine dependent representation and size)
d – double (machine dependent representation and size)
x – NUL byte
X – Back up one byte
Z – string which is NUL-padded
@ – NUL-fill to absolute position

Tuesday, 26 July 2022

[Laravel] How to find out which Class and File are behind a Facade

Facades in Laravel allow us to call libraries very conveniently. However, developers who are new to a project will find it difficult to investigate errors because Laravel Error Handling does not specify which class caused the error. In particular, the problem is very common with Facades that have many services  available. Ex: DB, Image, Auth, Cache, Mail...

Laravel Facade Flow

* Quick debug:

To find out the PHP class behind a Facade that you don't know where it is, you can debug it with the following code:
$behindClass = get_class(\<<Facade>>::getFacadeRoot());
$classReflector = new \ReflectionClass($behindClass);
dd($behindClass, $classReflector->getFileName(), $classReflector);
ex: 
$behindClass = get_class(\Mail::getFacadeRoot());
$classReflector = new \ReflectionClass($behindClass);
dd($behindClass, $classReflector->getFileName(), $classReflector);
result:

* Understand how the Facade is loaded by Laravel:

To find the underlying class behind a Laravel Facade without debugging you need to understand how a Facade is installed and loaded into Laravel.
Facade looks magical, but it's actually based on PHP's built-in class_alias feature. You can see in the project's config file (/config/app.php) there is a block to declare the Facade class alias.
Ex:
'aliases' => [
  ....
  'Lang' => Illuminate\Support\Facades\Lang::class,
  'Log' => Illuminate\Support\Facades\Log::class,
  'Mail' => Illuminate\Support\Facades\Mail::class,
If you open the class Illuminate\Support\Facades\Mail you will see that the class is almost completely empty. It has very little source code and doesn't really handle any features. In this file, the most special thing we see is the getFacadeAccessor() function and this function does not process anything but just returns a simple string like "mailer". This function is present in all Facades.
protected static function getFacadeAccessor()
{
         return 'mailer';
}
It looks magical, but it's not really here. Illuminate\Support\Facades\Mail inherits another class, Illuminate\Support\Facades\Facade::class . In this superclass Laravel will call getFacadeAccessor() to get the name of the actual service that has been configured by laravel for this facade. The example here is 'mailer'. Laravel will then call the 'mailer' service to return the Facade call - app('mailer').
You may be wondering that until now we still do not know where the 'mailer' service is located and how it is declared in Laravel.
Normally, every Laravel service needs to be declared through a Provider and then be available anywhere. Facades are treated the same way. Usually when you install a service pack from outside you will see in the source code of that service pack in addition to the Class Facade there will be a Class Provider to declare the service with Laravel. This means that once we have found information about Facade's extension in config/main.php, we can next look for Class Provider in that extension's source code to see the exact services that have been provided. How is it declared and what files it leads to.
Ex:
class MailServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register()
    {
        $this->registerSwiftMailer();
        $this->registerIlluminateMailer();
        $this->registerMarkdownRenderer();
    }
    protected function registerIlluminateMailer()
    {
        $this->app->singleton('mailer', function ($app) {
            $config = $app->make('config')->get('mail');
Usually the Providers will be installed automatically when we add the extension package to the project. In addition, Providers can also be manually declared in "config/app.php". There are some services that are core of Laravel, so by default they are declared when laravel starts. For example, with the 'mailer' service we just learned about. For core services, the Facade location and the service source code may be different. As with most package that you install from a third party, the Facade source code, Facade Provider, and Facade-related files are all in the same place in Vendors.

* Note:

we can read the source code in the "vendor" to understand and find a way to fix the error faster, but it is absolutely not recommended to edit the source code directly in the "vendor".

Sunday, 26 July 2020

Laravel Fix Error : Function name must be a string by Illuminate\Pipeline\Pipeline.php


Laravel

Issue: Laravel encountered error "Function name should be a string" or "Function name must be a string" in Api or somewhere. Error reported from file "Illuminate\Pipeline\Pipeline.php"
$carry = method_exists($pipe, $this->method)
                                    ? $pipe->{$this->method}(...$parameters)
                                    : $pipe(...$parameters);
Reason: You have used some middleware by name that has not been previously declared.
Debug: Check all middleware used, make sure it is already declared in the file Kernel.php. The most common scenario is that you have not declared 'auth' middleware yet.

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        ...
}
Done ! 

Saturday, 4 July 2020

[Linux] Install PHP mongodb extension for PHP 7.2 and higher

This article will guide you to install php mongodb extension for PHP7 on linux operating system platform. The operating system we use is Centos, but it is also true for other linux distributions like Ubuntu, Redhat, Fedora ....

When upgrading to PHP7 we often encounter problems when we cannot install the php-mongo extension. You may encounter the following error message:

Package: php-pecl-mongo-1.6.14-1.el7.remi.5.4.x86_64 (remi)
Requires: php(zend-abi) = 20100525-64
* Reason: 
We have 2 mongo extensions for PHP: php-mongo and php-mongodb. Php-mongo only supports php 5.6, but php-mongodb supports the latest version 7.4. That's why you have an error when trying to install php-mongo for PHP7.
php-mongo is older and has been discontinued, but it is currently available as a library in remi repos. And php-mongodb is Pecl's latest library but it is not available and you have to install it yourself via php-pear.

* Solving problems: install php-mongodb extension for PHP7 

Step 1: Install apache(httpd) and php 7
Step 2: Install php-pear
install gcc php-pear php-devel
Step 3: Install mongodb extension 
pecl install mongodb
Step 4: Enable php-mongodb extension 
open php.ini file, then add the following line
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
extension=mongodb

Step 5: Verify PHP Mongodb extension is enabled
php -m
Done !

* Note: The syntax used in previous PHP versions ('extension=<ext>.so' and 'extension='php_<ext>.dll') is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new ('extension=<ext>) syntax.

* Refer: https://blog.remirepo.net/pages/PECL-extensions-RPM-status



Monday, 22 June 2020

[PHP] Laravel Exception: Malformed UTF-8 characters, possibly incorrectly encoded

This error can be caused from many laravel modules such as Datatables, Json Output, Monolog ... So this is a very difficult error to analyze and fix. In this article we try to find some way to fix that bug in laravel (in the common cases).
Why did you get this error? and how to fix it?

* Case 1: In case of failure due to wrong configuration of database connection
The most common is when you connect to a second database. Developers often have a configuration that lacks the "charset" and "collation" parameters, causing the error as you see it:
Exception Message:↵↵Malformed UTF-8 characters, possibly incorrectly encoded
To fix it please configure the connection parameters are complete.
Eg:

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database_name_1',
            'username'  => 'user_1',
            'password'  => 'password_1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',

            'prefix'    => '',
    ....
 ),
/*mysql2 if you use two database*/
'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'hostForDB2',
            'database'  => 'database_name_2',
            'username'  => 'user_2',
            'password'  => 'password_2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',

            'prefix'    => '',
    ...
),

* Case 2: Regex Error - Caused by some regex function in route, url validate ....
PREG_BAD_UTF8_ERROR 'Malformed UTF-8 characters, possibly incorrectly encoded'

*Case 3: JSON Encode, Json output error - Caused by Monolog, Datatables Logs..

To Fix Case 2 & 3 you can try converting the input to utf-8, or remove non-utf-8 characters.

Eg1: Function to auto convert any string to utf-8 encoding

$newString = mb_convert_encoding($inputString, "UTF-8", "auto");

Eg2: fix utf-8 encoding for Datatables column

$datatable->editColumn('title', function(Post $node) {
            return mb_convert_encoding($node->title,"UTF-8", "auto");
        });
Done ! For any other questions you can leave them in the comment section at the end of this article. Thank you.

Thursday, 7 May 2020

Composer: How to fix error "Fork failed errors" in Linux server


In many cases we encounter lack of memory errors when running "composer install" or "composer update" command to update packages in our PHP project.
Some of the error messages you may receive:

  • - proc_open(): fork failed errors - Cannot allocate memory
  • - exception is caused by a lack of memory
  • - Killed

The cause of all these errors is because our server does not have enough RAM to allocate to Composer. Increasing packages in the project, the larger the size, so this error is also becoming more and more common. To fix them you can increase the server's physical RAM but the cost will be quite expensive.

There is another solution simpler and completely free to fix Composer memory error. That is we can enable swap space for the server. This is quite easy to implement and will thoroughly fix the error we encounter. For each operating system, there will be different ways to initialize swap partitions. You can refer to one of the instructions below:

Enable Swap to fix Composer memory error for Centos, Ubuntu ...:

Step 1: Create a new Swap file (1GB to 3Gb)
sudo fallocate -l 3G /swapfile
Step 2: Add Write permission for Swap file
sudo chmod 600 /swapfile
* If your server is running under SELinux, after chmod command you must run the following command
sudo chcon -t swapfile_t /swapfile 
Step 3: set up a Linux swap area
sudo mkswap /swapfile
Step 4: Active Swap for server
sudo swapon /swapfile
opening the "/etc/fstab" file
vi /etc/fstab
then add the following line at end of file.
/swapfile swap swap defaults 0 0

Done ! If there are no errors, you have successfully enabled the swap for your server. You can try checking the swap partition with one of the following commands:
sudo swapon --show
or
top
or
sudo free -h

Now it's time to try running the composer commands again. Hopefully the bug has been fixed. Good luck.

*Note:
- /swapfile  - is file name for swap file, you can use another name or put it in another folder.
- In addition to using swap files, you can also try to use swap partitions.
- Some problems with PHP modules can also cause errors because Composer runs on PHP

*Refer: https://getcomposer.org/doc/articles/troubleshooting.md

Monday, 16 October 2017

Wordpress: Change the title of any custom page dynamically

Sometime we want to custom the title for some page eg: 404, contact, search .... It is very simple, follow these instructions.

in file "your_theme/function.php" add the following code at the end.

function setTitle($title) {
    add_filter( 'wp_title', function() use ($title) {return $title;}, 10000 );
}

Done ! From now on, which page should be customized so that you just call the function like this:

setTitle('Hello, this is my custom title');

It does not affect the pages you do not use. Have fun!

Sunday, 12 March 2017

Yii2: PHP Warning - Unable to allocate memory for pool

Yii2 error:

PHP Warning – yii\base\ErrorException

include(): Unable to allocate memory for pool.


* Reason : You have not allocated enough memory for APC cache (file cache or opcode cache)

* Solution 1: Disable APC, If you do not need it (apc.enabled=0)
* Solution 2: Increased memory for APC (apc.shm_size="64")

To do one of the two. Find php.ini or apc.ini on your server. If you do not have admin rights to the server try to use htacess file: php_flag display_errors on


Monday, 22 June 2015

Yii2: Unknown Property Exception after adding column to table

Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: app\models

What happens when you get an error Exception "Getting unknown property", after just added a field to the table in the database ?
  1. Check your property name, was it correct?
  2. Clear cache if you using cache. Yii2 will cache the table schema so if you change the table you need to clear the cache

Thursday, 29 January 2015

Yii2: Validate unique if attribute is not empty

Yii2 unique validator, empty string and null is treated the same and ignored. It not the same as mysql when only null value ignored in unique check.
But this is not a bug, not all database management systemare the same with mysql.

So if you want to validate an attribute only when it not empty. Try the following rules :

['phone', 'filter', 'filter' => 'trim'], //trim string
['phone', 'default'], //set null if empty string
['phone', 'unique'],

Refer :
http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html

Tuesday, 27 January 2015

Yii2: Using csrf token

First, if you do not understand what is the CSRF token? and why should we use it, please refer to the following link :
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)

One of the new features of Yii2 is CSRF validation enabled by default.
If you use ajax or basic form as follows :

<form action='#' method='POST'>
    ...........
</form>

You will get an error exception :

Bad Request (#400): Unable to verify your data submission

That is because you do not submit csrf token. The easiest way if you dont care about csrf just disable it in main config :

'components' => [
     'request' => [
          ....
          'enableCsrfValidation'=>false,
      ],
      .....
],

Or in Controller :

public function beforeAction($action) {
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

So how to use Csrf Validation for your strong security website:

* With basic form:
- Create form with yii\widgets\ActiveForm or yii\bootstrap\ActiveForm
ActiveForm will automatically add a token in the form

Can use like this

<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    ....
<?php ActiveForm::end(); ?>

Or

<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
      <input type='text' name='name'/>
      .........
<?php ActiveForm::end(); ?>

* With manual form:
you must manually add CSRF token in the form

<form action='#' method='POST'>
   <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
   ....
</form>

* With Ajax
- In main layout add csrfMetaTags :
<head>
   .......
   <?= Html::csrfMetaTags() ?>
</head>

- And in javascript ajax code add csrf param like this:

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
         url: 'request',
         type: 'post',
         dataType: 'json',
         data: {param1: param1, _csrf : csrfToken},
});

Monday, 29 December 2014

Yii2: Validate value without model (Ad Hoc Validation)

Sometimes you need to do ad hoc validation for values that are not bound to any model.
If you only need to perform one type of validation (e.g. validating email addresses), you may call the [[yii\validators\Validator::validate()|validate()]] method of the desired validator, like the following:
$email = 'test@example.com';
$validator = new yii\validators\EmailValidator();

if ($validator->validate($email, $error)) {
    echo 'Email is valid.';
} else {
    echo $error;
}
Note: Not all validators support this type of validation. An example is the unique core validator which is designed to work with a model only.
If you need to perform multiple validations against several values, you can use [[yii\base\DynamicModel]] which supports declaring both attributes and rules on the fly. Its usage is like the following:
public function actionSearch($name, $email)
{
    $model = DynamicModel::validateData(compact('name', 'email'), [
        [['name', 'email'], 'string', 'max' => 128],
        ['email', 'email'],
    ]);

    if ($model->hasErrors()) {
        // validation fails
    } else {
        // validation succeeds
    }
}
The [[yii\base\DynamicModel::validateData()]] method creates an instance of DynamicModel, defines the attributes using the given data (name and email in this example), and then calls [[yii\base\Model::validate()]] with the given rules.
Alternatively, you may use the following more "classic" syntax to perform ad hoc data validation:
public function actionSearch($name, $email)
{
    $model = new DynamicModel(compact('name', 'email'));
    $model->addRule(['name', 'email'], 'string', ['max' => 128])
        ->addRule('email', 'email')
        ->validate();

    if ($model->hasErrors()) {
        // validation fails
    } else {
        // validation succeeds
    }
}
After validation, you can check if the validation succeeded or not by calling the [[yii\base\DynamicModel::hasErrors()|hasErrors()]] method, and then get the validation errors from the [[yii\base\DynamicModel::errors|errors]] property, like you do with a normal model. You may also access the dynamic attributes defined through the model instance, e.g., $model->name and $model->email.
Read more : https://github.com/yiisoft/yii2/blob/master/docs/guide/input-validation.md

Monday, 24 November 2014

Yii2: createUrl method

Old Yii1 to create an url we write:

$this->createUrl(); 
or
Yii::app()->createUrl();

Now with Yii2 we have to write

\Yii::$app->getUrlManager()->createUrl(['controler/action','param1'=>'value1','param2'=>'value2']);


Yii2: Error invalid configuration with modules

Error: 
Invalid Configuration – yii\base\InvalidConfigException
The configuration for the "modules" component must contain a "class" element.
Solution: 
Check your config file.  don't put "modules" in component section.
Correct config:
'components'=>[
...
],
'modules'=>[
...
]

Readmore about module : https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-modules.md 

Friday, 19 September 2014

PHP: Create big unique ID like Facebook or MongoDB

Most of web application using a relational database management system (MSQL, SQL ..etc) to store data as records. We need an unique id to use as a key Primary.
How to do it ?
* SQL AUTO INCREMENT a Field :
--> 1,2,3,4,5..... #anyone can count the number of your records and more

* PHP uniqid :
--> 541cf7f7d685e, 541cf7f7d685e, 541cf7f7d685e .....  #somewhat similar?

* Or use a custom function like this :

function gen_id() {
    return sprintf( '%04x%04x%04x%04x%04x%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}
Result : 6800cd499f25434aac48c0bb51f46307, caa02c4831194690ad8458c3a4e07a0c, 7488a4c459d64f8dbacd2b79f44ed4bf ......

- differences
- professional (like facebook, google, MongoDB ...)
high performance
- unrestricted

Reference : PHP uuid lib

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


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();
?>