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

Thursday, August 31, 2017

phpbrew (Install Php 5.3 in Ubuntu 16.04)

While working on multiple projects and if we needed multiple PHP versions then basic solution is install  multiple versions of PHP.

But this option not works if you needed lower  PHP versions in current Linux distributions(In my case it is Ubuntu).Like installing php5.3 version on Ubuntu 16.04.

To solve this one way is compile the code.But it takes time and porting it to unsupported environment is time taking.In attempt of finding the solution come across a tool/utility i.e. phpbrew (https://github.com/phpbrew/phpbrew)

It is quite handy and helpful for managing php versions on the fly.

Steps for installating and using phpbrew

Step 1(Download and configure phpbrew)

# curl -L -O https://github.com/phpbrew/phpbrew/raw/master/phpbrew
# chmod +x phpbrew
# sudo mv phpbrew /usr/bin/phpbrew
Step 2(Entry into configuration file)
Configuring this in root account so in /root/.bashrc file needed to make following entry

[[ -e ~/.phpbrew/bashrc ]] && source ~/.phpbrew/bashrc

Step 3
Initialize phpbrew

#phpbrew init

Step 4
List all known versions of php

#phpbrew known

Step 5
If in step 4 it not shows your required version then 

#phpbrew update --old

Now perform step 4 it will list older version as well.

Step 6
After this we have to install php-5.3(I tried 5.3.29 and other versisons but these are not working here only 5.3.24 installed)

#phpbrew install 5.3.24 +bz2 +calendar +cli +gd +ctype +dom +iconv +fileinfo +filter +ipc +json +mbregex +mbstring +mhash +mcrypt +pcntl +pcre +pdo +phar +posix +readline +sockets +tokenizer +xml +curl +zip +mysql +debug +apxs2

If you face any error then install respective library using apt-get

Step 7
List all installed version in phpbrew

#phpbrew list

Step 8
Before enabling versions from phpbrew needed to do following configuration in

#vim /etc/apache2/mods-enabled/php5.load
LoadModule php5_module /usr/lib/apache2/modules/libphp5.3.24.so 
AddType application/x-httpd-php .php


If it is any varient of php-5.6 or php7 then we have to either create php5.6.so/php7.so file in mods-enabled

Step 9
Before restarting apache2 disabled all other varient using a2dismod

Step 10
Choose Version using phpbrew

#phpbrew use php-5.3.24

Step 11
Check php version using

#php -v
 
And in apache2.Check phpinfo() output

Step 12
After choosing version using phpbrew as done on step 10.You can install any available extension using
#phpbrew ext install redis
#phpbrew ext install mongo

After installing this in php cli changes will be reflect but for apache it is needed to restart the apache for reflecting changes.

References
http://enzolutions.com/articles/2014/10/17/manage-php-versions-with-phpbrew/
https://bitbucket.org/snippets/sergiy_opentag/4LLrMR


Friday, May 27, 2016

Generate all possible permutation of string using PHP.


(Date : 28-May 12:05 IST)

I tried to solve it by recursion but at the end come to this solution i.e.

1)Run a loop so that each char come to first position one by one

2)Remove the char(i.e. now in first position) from that position so that remaining string is still in sequence

3)And rotate the whole remaining string like
cat
i)'c' remains constant(Prefix)
ii)rotate 'at'

4)Rotating 'at' is also tricky.So come to this solution that
i)Run a for loop divide it into two parts(I not look into php function for doing so)
First part start from the counter from where this loop working
Second part start from 0 upto the counter

5)And form an array.(Array dimension is (string length)*(String length-1))


Here is the code.

Updated solution( Aug-2017 )
(Can rotate any length of string)

<?php
$string="abc";
$array=array();
for($i=0;$i<strlen($string);$i++)
{
$array[]=$string[$i];
}
$rotate=rotate($array);

$rotate=array_unique($rotate);
print_r($rotate);
function rotate($array)
{
if(count($array)==2)
{
$data0=array_pop($array);
$data1=array_pop($array);
return array($data0.$data1,$data1.$data0);
}
else
{
$finalArray=array();
for($i=0;$i<count($array);$i++)
{
$tempArray=array();
for($k=0;$k<count($array);$k++)
{
if($k==$i)
{
continue;
}
$tempArray[]=$array[$k];
}
if(count($tempArray)>=2)
{
$tempData=rotate($tempArray);
}
for($j=0;$j<count($tempData);$j++)
{
$finalArray[]=$array[$i].$tempData[$j];
}
}
return $finalArray;
}
}
?>

Past solution( May-2017 )
(Can rotate 3 character string)

function generatePermutation($string)
{
  #----------------
  #---act
  #---atc
  #---cat
  #---cta
  #---tac
  #---tca
  #--------------
    for($i=0;$i<strlen($string);$i++)
    {  
$j=0;
 $tempString="";
 #--------------------------
 #---Get later portion of string
 #--------------------------------
 for($k=0;$k<strlen($string);$k++)
 {
if($i==$k)
{
continue;
}
else
{
$tempString.=$string[$k];
}
 }
 #---------------------------------------
 #----Generate all permutation
          #------------------------------------------
 for($l=0;$l<strlen($tempString);$l++)
 {
$tempTempString="";
for($m=$l;$m<strlen($tempString);$m++)
{
$tempTempString.=$tempString[$m];
}
for($m=0;$m<$l;$m++)
{
$tempTempString.=$tempString[$m];
}
$array[$i][$j++]=$string[$i].$tempTempString;
 }
    }
    return $array;
}

Sunday, January 18, 2015

PHP Debugging tool/scripts(Like firebug for debugging javascript)

I used different tools for debugging or profiling PHP like xdebug,xhprof.

But I am looking for some tool(script) that can display PHP bebug log on the same page(Like firebug for javascript debugging).So that for debugging i not have to do echo,print_r in between of page.All those variables output come separately i can view them etc.

In that attempt i come across different tool like

1)Kint
http://raveren.github.io/kint/

2)PHP Debugbar
http://phpdebugbar.com/

3)PHP Debug
http://www.php-debug.com/www/

and there is more debug tool available for this.

I tried these three

1)Kint.

Overview:Simplest to integrate.
How to Use:It is simplest one to integrate.Just needed to include one php file.Then you can use dump/d/dd function to dump any variable.That variable will be displayed on the page

2)PHP Debug Bar

Overview:A bit more complicated(More steps) then Kint in terms of intallation etc.
It has more feature then kint.Like it has different tabs for different things(Can customized them also.)

Preparation before use

Download it from github.

Get the composer.phar file

#wget "https://getcomposer.org/composer.phar"

Run following command

#php composer.phar install

It will create vendor folder inside that directory

How to Use

Use following lines at the start of code

require <folder where debug bar unzipped>/vendor/autoload.php';

use DebugBar\StandardDebugBar;

(setBaseUrl needed if you unzipped debugbar other then root dir)

$debugbar = new StandardDebugBar();
$debugbarRenderer = $debugbar->getJavascriptRenderer()
                ->setBaseUrl('<Debug bar unzipped folder>/src/DebugBar/Resources');


$debugbar["messages"]->addMessage("hello world!");


In the head section needed to add this line.

<?php echo $debugbarRenderer->renderHead(); ?>

At the end of body needed to add this

<?php echo $debugbarRenderer->render() ?>

3)PHP-Debug

Overview:It is complicated one in comparison of previous two because of no of different features.But as per my use it is more useful.

Preperation before use

Download it from github.

How to Use

For ref

http://www.php-debug.com/www/install.php

I integrate it like this.

In the starting needed to add this section

$options = array(
    'HTML_DIV_images_path' => '<PHP Debug image folder url >',
    'HTML_DIV_css_path' => '<PHP Debug css folder location>',
    'HTML_DIV_js_path' =>  '<PHP Debug js folder location>',
);

// Additional ini path for PEAR
define('ADD_PEAR_ROOT', '<PHP Debug directory>');
set_include_path(ADD_PEAR_ROOT . PATH_SEPARATOR. get_include_path());

require_once '<PHP debug directory>/PHP/Debug.php';

// Debug object
$Dbg = new PHP_Debug($options);


Needed to add following lines in the head section

    <script type="text/javascript" src="<?php echo $options['HTML_DIV_js_path']; ?>/html_div.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="<?php echo $options['HTML_DIV_css_path']; ?>/html_div.css" />

At the end of body section needed following line

$Dbg->display();


PHP Debug output looks like this




Wednesday, December 31, 2014

Insert into Solr (Using PHP) throws Invalid Date String:'' Error

In attempt of inserting some data into Solr using PHP i face this error

[Thu Jan 01 02:27:18.513778 2015] [:error] [pid 4766] [client 127.0.0.1:50488] PHP Fatal error:  Uncaught exception 'SolrClientException' with message 'Unsuccessful update request. Response Code 400. <?xml version="1.0" encoding="UTF-8"?>\n<response>\n\n<lst name="responseHeader">\n  <int name="status">400</int>\n  .......................

In attempt of finding solution i come across this point that

Documentation of Date accepted by Solr is

http://lucene.apache.org/solr/4_4_0/solr-core/org/apache/solr/schema/DateField.html

So,fix in PHP code is

Instead of using

date("Y-m-d H:i:s")

I needed to use something like this

gmdate("Y")."-".gmdate("m")."-".gmdate("d")."T".gmdate("H").":".gmdate("i").":".gmdate("s")."Z"

So that date should be in format as accepted by Solr.

Ref
-----
http://stackoverflow.com/questions/18831782/solr-invalid-date-string-exception

Friday, December 26, 2014

PHPUnit (How-To Tutorial)

Here is the list of some PHPUnit How-To Begineer tutorial

http://www.sitepoint.com/getting-started-with-phpunit/
http://codesamplez.com/development/phpunit-tutorial-beginners
http://www.sitepoint.com/tutorial-introduction-to-unit-testing-in-php-with-phpunit/


For Reference(Becoming expert please refer)
https://phpunit.de/manual/current/en/phpunit-book.pdf

PHP Profiling with Xhprof (Output Screenshots)

This article is mainly for how-to enable profiling with Xhprof and viewing output in normal html format.

Xhprof Setup

1)You needed to install xhprof.

apt-get install php5-xhprof

2)Enable that.
Create file /etc/php5/apache2/conf.d/20-xhprof.ini (As my os is Ubuntu;So i am creating this ini file into that location(As per your server directory may be different) Or you can choose alternate way that is you can directly paste the below given conf into php.ini under [xhprof].

As paramter mentioned below output directory.Give that directory 777 if it is not tmp directory.
Ex-
chmod 777 <directory name> -R .
)

extension=xhprof.so
xhprof.output_dir="/tmp"

3)Download xhprof from pecl

http://pecl.php.net/package/xhprof

Extracted that and store it into web root directory (Use case will be find in Point 6)

Php Code


4)xhprof_enable (With all possible option.From where you wanted to start).

Example

//xhprof_enable();
//xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY); //Memory and cpu usage


5)xhprof_disable (Save it into variable.Where you wanted to stop.).

$prof=xhprof_disable();


6)Include library and save_run as mentioned below(after disable)

$XHPROF_ROOT="/var/www/xhprof/xhprof";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

// save raw data for this profiler run using default
// implementation of iXHProfRuns.
$xhprof_runs = new XHProfRuns_Default();

// save the run under a namespace "xhprof_foo"
$run_id = $xhprof_runs->save_run($prof, "xhprof_test");
echo "Run Id:".$run_id;


7)Open the xhprof_html/index.php you will see your listed run id there like <runid>.xhprof_test.xhprof

For answering output imagination i am attaching screenshot have a look







References
------------------
Referenced from Various Sources.

For more details explanation and other possibilities go through this
http://erichogue.ca/2011/03/linux/profiling-a-php-application/

Thursday, May 1, 2014

PHP listing files inside directory i.e. sorted by modifcation date.

Normally for listing files from directory normally we use the following methods : readir()/scandir() etc.

But if we needed file list sorted by modification date.Then one of the possible simple solution(using DirectoryIterator) is


<?php
$fileListing = array();
$directory=".";
$directoryToProcess = new DirectoryIterator($directory);
foreach ($directoryToProcess as $listedFileInfo) {     
if ($listedFileInfo->getFileName() != "." && $listedFileInfo->getFileName() != "..")
        {
$fileListing[$listedFileInfo->getFileName()]=$listedFileInfo->getMTime();
}
}
arsort($fileListing);
foreach($fileListing as $fileName=>$fileNameTimeStamp)
{
      #Perform action here
echo $fileName."\n";
}
?>


Reference
----------------
Different answers in Stackoverflow

Thursday, December 5, 2013

Couchbase php ext installation on centos

I tried to install couchbase php sdk on centos system.As it looks like simple;but there are some known problems(http://www.couchbase.com/communities/q-and-a/centos5-cant-get-php-client-library-cant-install-php-sdk) so i got stucked.

In attempt of finding solution;I find following way of installation


  1. #wget http://packages.couchbase.com/clients/c/libcouchbase-2.2.0_centos62_i686.tar
  2. #tar -xvf libcouchbase-2.2.0_centos62_i686.tar
  3. #cd libcouchbase-2.2.0_centos62_i686
  4. #rpm -ivh libcouchbase2-bin-2.2.0-1.i686.rpm libcouchbase2-core-2.2.0-1.i686.rpm libcouchbase-devel-2.2.0-1.i686.rpm
  5. #pecl install couchbase
  6. #vim /etc/php.d/couchbase.ini
extension=couchbase.so

But adding couchbase.so raises following error
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/couchbase.so' - /usr/lib/php/modules/couchbase.so: undefined symbol: php_json_encode in Unknown on line 0

  • For fixing this
 #rm -f /etc/php.d/couchbase.ini
#vim /etc/php.d/json.ini

and at the end of this file(json.ini) add

extension=couchbase.so

Save it and it will start working

(Ref-http://www.couchbase.com/forums/thread/couchbaseso-undefined-symbol-phpjsonencode-unknown-line-0)

Thursday, June 14, 2012

Manually Setup WAMP on local PC


Note: If you want no pain of installing them seperately and configuring them manually.You can try EasyPhp/Xampp

1: Download apache
http://httpd.apache.org/download.cgi
Install it(As normally doing this other softwares)

2: Download php
http://windows.php.net/download/ (copy zip package that i done in my setup)
Extract it
copy that folder into c: and rename that as c:/php (If you not done this or copy it somewhere else then Configure httpd.conf as per your location)

3: Download MySQL from
http://dev.mysql.com/downloads/mysql/ (As per system Configuration)
Install it.


4:  Dont forget to add these lines in httpd.conf( For reference : http://www.php.net/manual/en/install.windows.apache2.php )
---------------------------------------------
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
PHPIniDir 'c:\php\'

5: Restart Apache

6: Go to Apache Directory then /htdocs
Create a simple file
index.php


phpinfo();
?>

7: Try to run it http://127.0.0.1/index.php (I configure this on local laptop so i used 127.0.0.1.Inplace of 127.0.0.1 you can use your ip server name etc)

Imagick Configuration (It is not mandory) 
Imagick configuration for php in windows


Follow this document 

http://www.elxsy.com/2009/07/installing-imagemagick-on-windows-and-using-with-php-imagick/


In Simplified Terms
1: Download and Install Imagemagick(Q-16)
2: Download php_imagick.dll and copy it into ext directory of php
3: Add this line in php.ini file (php.ini-production)
If it is  commented (; line start with semicolon)
Or there is no entry of this line in php.ini


extension=php_imagick.dll







Tuesday, April 26, 2011

Removing garbage(non ascii) character from string

When you copy and paste some data from some source then sometime you got some non ascii garbage values like

♠ &spades;

♣ &clubs;

♥ &hearts; etc.


You can remove this using preg_replace function of php

$name="Sandeep♠ Singh♣ Bisht♥";
$name = preg_replace('/[^(\x20-\x7F)]*/','', $name);

echo $name;


Your input is : Sandeep♠ Singh♣ Bisht♥

And the output is :Sandeep Singh Bisht


For more reference:

http://php.net/manual/en/function.preg-replace.php
http://www.stemkoski.com/php-remove-non-ascii-characters-from-a-string/

Sunday, March 20, 2011

How to handle php-mysql connection timeout?

How to increase time period of mysql connection timeout through php.Or how to handle php-mysql connection time out.

By default php-mysql connection timeout is 60 sec.

It is define in php.ini.

These are the steps to change it as per requirement

Step 1: Default location of php.ini file is /etc/php.ini other wise locate it.
Step 2: In php.ini file search from "mysql.connect_timeout" it is bydefault set up to 60 sec.
If you change 60 to -1 then there is no limit on connection timeout.
Step 3: Save file and exit


For other option of mysql in php.ini file you can check in php.ini file.Other location for reference is 

w3school php-mysql functions