Dec 04 2009

Using ORACLE and PHP in Ubuntu

Category: PHPBipin Balakrishnan @ 10:59 am

oracle-php

Last week i got a chance to try ORACLE API, as i was a fresher in oracle at that time i was having little idea how to use it.After googling a while i got the way to use it.The steps i followed are written below in future hope this will find helpful for someone .
For setting up in local machine we need to install oracle Oracle Express Edition first. Please note my machine was , Ubuntu 9.04 and this worked for me.
Installing Oracle Express Edition
First you need to add this line to your /etc/apt/sources.lst

deb http://oss.oracle.com/debian unstable main non-free

Run

sudo wget http://oss.oracle.com/el4/RPM-GPG-KEY-oracle -O- | apt-key add -
sudo apt-get update
sudo apt-get install oracle-xe

Then run

sudo /etc/init.d/oracle-xe configure

PHP-Oracle Binding
Now install PHP-oracle binding, will get it from here

Convert the rpm packages into debian packge using alien program if its not installed in your machine please install it using

sudo apt-get install alien

Run the commend in the downloaded packege folder

sudo alien oracle*.rpm

You’ll need the ‘pecl’ command, which is available in php-pear, php5-dev

sudo apt-get install php-pear php5-dev
sudo pecl install oci8

Enter 1 and check the oracle client lib path will be like this.

instantclient,/usr/lib/oracle/11.2/client/lib

Hit enter again and wait for a while.After completion add “extension=oci8.so” in your php.ini( both apache and cli) .Restart apache2 and check phpinfo();Okey our machine is ready to make calls to oracle binding functions and remote APIs.

The rest you can try out from here

Tags: , , ,


Aug 21 2008

Using Memcached with PHP

Category: PHPBipin Balakrishnan @ 11:59 am

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications by caching the frequently accessed data.By default, memcached uses the port 11211.

Danga Interactive developed memcached to enhance the speed of LiveJournal.com , a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases.

The system is used by several very large, well-known sites including YouTube, LiveJournal, Slashdot, Wikipedia, SourceForge, ShowClix, GameFAQs, Facebook, Digg, Twitter, Fotolog, BoardGameGeek, NYTimes.com, deviantART, Jamendo, Kayak and in our Mobshare too.

Installing and Configuring Memcache

sudo apt-get install memcached
sudo apt-get install php5-memcache

Configuration Files

edit sudo vim /etc/php5/apache2/conf.d/memcache.ini or

sudo vim /etc/php5/cli/conf.d/memcache.ini //for cli apps

; uncomment the next line to enable the module
extension=memcache.so

[memcache]
memcache.dbpath="/var/lib/memcache"
memcache.maxreclevel=0
memcache.maxfiles=0
memcache.archivememlim=0
memcache.maxfilesize=0
memcache.maxratio=0

Edit sudo vim /etc/memcached.conf to change the default configuration settings

Restart apache webserver

starting memcached

sudo /etc/init.d/memcached start

To see storing session on memcache on the terminal use

sudo memcached -vv

Eg 1: Using memcache in PHP

Testing Program whether it properly got installed and working fine

<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
var_dump($get_result);
?>

Outputs this as result

Server's version: 1.2.1<br/>
Store data in the cache (data will expire in 10 seconds)<br/>
Data from the cache:<br/>
object(stdClass)#3 (2) {
  ["str_attr"]=>
  string(4) "test"
  ["int_attr"]=>
  int(123)
}

Example 2: Using in database access

<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
mysql_pconnect("localhost","root","");
mysql_select_db("bestofferIVR");
//Write your time consuming query here
$key = md5("SELECT * FROM callerinfo where cnumber='9941426932'");
$get_result = $memcache->get($key);
if ($get_result) {
print_r($get_result);
echo "If condition Working";
}
else {
 // Run the query and transform the result data into your final dataset form
 $qurey="SELECT * FROM callerinfo where cnumber='9941426932';";
 $result = mysql_query($qurey);
 $row = mysql_fetch_array($result);
 print_r($row);
 $memcache->set($key, $row, TRUE, 86400); // Store the result of the query for a day
 echo "Else condition Working";
}
?>

On the First Run the output will be as below, ie directly fetcing from the DB

Array
(
    [0] => 5
    [id] => 5
    [1] => 9941426932
    [cnumber] => 9941426932
    [2] => 2008-03-20 08:28:57
    [time] => 2008-03-20 08:28:57
    [3] => mal12
    [scheme] => mal12
)
Else condition Working

From the second run onwards the result will be as below ie using the memcache not DB

Array
(
    [0] => 5
    [id] => 5
    [1] => 9941426932
    [cnumber] => 9946426932
    [2] => 2008-03-20 08:28:57
    [time] => 2008-03-20 08:28:57
    [3] => mal12
    [scheme] => mal12
)
If condition Working

Tags: , , , , ,


Jul 24 2008

PHP command line agrument

Category: PHPBipin Balakrishnan @ 12:31 pm

php.gif

We can pass command line argument to a PHP script as in any other programming language when we run it in the cli mode.For example make script called test.php in your editor.Copy paste content as follows.

<?php
echo $argv[0];
echo $argv[1];
echo $argv[2];
?>

Run the program as follows with command line argument as follows.

bipin@bipin-laptop:~/php$ php  test.php 10 22

Here the command line arguments are 10 and 22.The PHP script will take the argument as an array argv[] with the first element in the array (agrv[0]) as the program name and the arguments passed being held after that.

Tags: , ,


May 20 2008

Making PHP program as Daemon

Category: PHPBipin Balakrishnan @ 10:05 pm

It is some time necessary to make a PHP progam as a daemon .Here it explains how it is possible. Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

The process control functions come along with the php-cli in linux.So we don’t need to install extra libraries for this to work.If php-cli is not there in your machine intall it with yum or apt-get.As i am using the ubuntu os im explaining with its command Ubuntu users can follow this.

bipin@bipin-laptop:~$ sudo apt-get install php5-cli

Copy and paste the code for background process

<?php
include_once('createdb.php');
declare(ticks=1);
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
exit(); // we are the parent
} else {
// we are the child
}
// detatch from the controlling terminal
if (posix_setsid() == -1) {
die("could not detach from terminal");
}
$posid=posix_getpid();
$fp = fopen("/var/run/process.pid", "w");
fwrite($fp, $posid);
fclose($fp);
// setup signal handlers
 pcntl_signal(SIGTERM, "sig_handler");
 pcntl_signal(SIGHUP, "sig_handler");
// loop forever performing tasks
 $dbobject = new DB();
 $dbobject->getCon();
 while (1) {
// do something interesting here, here i have called a function from other flile called "createdb.php"
$dbobject->CopyCallFiles();
}
 fclose($fp);
 function sig_handler($signo)
 {
switch ($signo) {
 case SIGTERM:
 // handle shutdown tasks
 exit;
 break;
 case SIGHUP:
 // handle restart tasks
 break;
 default:
 // handle all other signals
 }
}
?>

Run the program and the function $dbobject->CopyCallFiles(); will work as a deamon here we can include a file instead of the function also here.

Tags: , ,


Mar 14 2008

Converting WAV file to GSM file

Category: PHPBipin Balakrishnan @ 3:21 pm

soundvisualizer.png

Want to convert a sound file of type wav to gsm in your web application.You can use the code below.There are may desktop application softwares such as

switch,audacity which converts the sound format.Suppose we need in a web application in which we uploads the wav file and and it got converted into a gsm or any other format(depends on our need).

For me i need the wav file in gsm format as the output for some IVR application.

Before writing the code we need a opensource software called sox

to be installed in our system.Sox is a sound converter which converts sound from any format to any other sound format.

The rest is simple

copy and paste the code below

Uploading interface: HTML

Give some file name with extension Html or PHP

<form enctype=”multipart/form-data” action=”uploader.php” method=”POST”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”10000000″ />
Choose a file to upload: <input name=”uploadedfile” type=”file” /><br />
<input type=”submit” value=”Upload File” />
</form>

Conversion program :

<?php
$target_path = “uploads/”;
$file_name=basename( $_FILES['uploadedfile']['name']);
$new = substr($file_name,0,-3).”gsm”;
$cmd = “sox “.$file_name.” -r 8000 -c1 “.$new.” resample -ql”;
exec($cmd);
rename(“$new”, “uploads/$new”);
?>


Feb 21 2008

Call to undefined function mysql_connect()

Category: PHPBipin Balakrishnan @ 8:07 pm

Today i stucked an error when i was trying to run a php script in a server eventhough my server was php5-mysql installed on it.At first i checked php, it was installed and working fine.Then checked mySQL.It was also working fine.I got the mysql prompt and the query was also working fine.I was experiencing.Tried the same solution when i experienced first.But this time it did’nt got worked.This time i had to use other solution and it got worked.The problem is actually php.ini file have enabled the mysql extension.

Solutions:

1)Remove php5-mysql with “apt-get remove php5-mysql” or “dpkg –purge remove php5-mysql and install it again or

2) Check your php.ini file to ensure it’s including the mysql.so library (extension=mysql.so) or

3)Type “dpkg-reconfigure php5-mysql” (For ubuntu and debian users)

will prompt 2 screens like this.2.jpg11.jpeg

Select “yes” both and try again hope your problem will get resolved.

In my case it got resloved :)

Tags: , ,


Feb 13 2008

PHP mysql database connection with OOPs

Category: PHPBipin Balakrishnan @ 1:51 pm

create a class file first as this with file name createdb.php

<?php
class DB

{
var $con;
function getCon()
{
$hostname=”localhost”;
$username=”root”;
$password=””;

$con = mysql_connect($hostname,$username,$password);
if (!$con)
{
die(’Could not connect: ‘ . mysql_error());
}
mysql_select_db(”creditlimitIVR”, $con);
return $con;

}
?>

Include this file “createdb.php” in your program where you want to connect the database create a class and call the function as follows in the “main.php”

<?php
include_once(’createdb.php’);
$dbobject = new DB();
if (!$dbobject->getCon())
echo “Connection Failed”;
else
{
/* Do what you want */
}

}

Similarly u can add more functions in createdb.php for inserting, deleteing, selecting etc. And can call from the program like

function InsertCallInfo($number)
{

$date_time= date(’d-m-Y g:i a’);
$sql=”INSERT INTO `callerinfo` (`number`, `time`, `status`) VALUES (’$number’, ‘$date_time’, ‘ATTEMPTED’)”;
if (!mysql_query($sql))
die(’Error: ‘ . mysql_error());
}

I am calling it as $dbobject->InsertCallInfo($oneNo);
in the main.php program.
Add more and more functions and enjoy!!!!!

Tags:


Feb 13 2008

Web Service

Category: PHPBipin Balakrishnan @ 1:49 pm

A Web service (also Web Service) is defined by the W3C as “a software system designed to support interoperable Machine to Machine interaction over a network.” Web services are frequently just Web APIs that can be accessed over a network, such as the Internet, and executed on a remote system hosting the requested services.

The W3C Web service definition encompasses many different systems, but in common usage the term refers to clients and servers that communicate using XML messages that follow the SOAP standard. Common in both the field and the terminology is the assumption that there is also a machine readable description of the operations supported by the server written in the Web Services Description Language (WSDL).Once we write a webservice and host it in a server we can call it from any language likewise a function call.

The below is simple example that demonstrate a webservice written in PHP using the library “nusoap”.To download nusoap Click Here!
The client and server part here is written in PHP, you can use any language to to call the server functions.

program discreption: The client will sent two strings to the server and server append a new string and returns to the clinet.

copy and paste the code for the server

<?php

require_once(”nusoap/lib/nusoap.php”);

$server = new soap_server();

$server->configureWSDL(’Append’, ‘urn:Append’);

$server->register(’AppendString’,

array(’string_a’ =>’xsd:string’,’string_b’ =>’xsd:string’),

array(’return’=>’xsd:string’),

‘urn:Append’, // namespace

‘urn:Append#AppendString’, // soapaction

‘rpc’, // style

‘encoded’, // use

‘Testing webservice’ // documentation

);

function AppendString($string_a, $string_b)

{

$server_msg=”I am the message from the server”;

$msg=$string_a.$string_b.$server_msg;

return $msg;

}

$server->service($HTTP_RAW_POST_DATA);

?>

“http://localhost/server.php”
will show the namespace

copy and paste code for the client

<?php

require_once(”nusoap/lib/nusoap.php”);

$client=new soapclient1(’http://localhost/server.php?wsdl’, true);

$param=array(

’string_a’=>’I am the first string from the client…’,

’string_b’=>’and am the second string from the clinet….’,

);

$result =$client->call(’AppendString’, $param, ”, ”, false, true);

print_r ($result);

?>

Tags: , ,