Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Friday, October 6, 2017

Connect to Microsoft SQL Server Using PHP

Connect to Microsoft SQL Server Using PHP


Below Code will connect to the Microsoft Sql Server using php script.

<?php
$serverName = "*****.*****.****.**";//Host Name
$uid = "mtcdb";//User Name
$pwd = "******";//Password
$databaseName = "Mobile_Dev";//Database Name
$connectionInfo = array("UID" => $uid,
"PWD" => $pwd,
"Database" => $databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect($serverName, $connectionInfo);
if( $conn )
{
echo "Connected";
}
else
{
echo "<pre>";
die( print_r( sqlsrv_errors(), true));
}
//var_dump($conn);exit;
$tsql = "SELECT * FROM users";
/* Execute the query. */
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt) {
echo "Statement executed.<br>\n";
} else {
echo "Error in statement execution.\n";
die(print_r(sqlsrv_errors(), true));
}
/* Iterate through the result set printing a row of data upon each iteration. */
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
// print_r($row);exit;
echo "Col1: " . $row[0] . "\n";
echo "Col2: " . $row[1] . "\n";
echo "Col3: " . $row[2] . "<br>\n";
echo "-----------------<br>\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
view raw mssqlserver.php hosted with ❤ by GitHub

Thursday, September 21, 2017

Authenticating with OAuth 2.0 For LinkedIn Api Access using PHP

Authenticating with OAuth 2.0 For LinkedIn Api Access using PHP


LinkedIn Oauth 2.0 PHP Access


Follow these steps to enable your application to make
authenticated API calls to LinkedIn using OAuth 2.0:


Step 1: Configuring your LinkedIn application.

Create application in linkedin Developers Panel Link.

After Clicking on Create App. Fill the form information.


Once you save your configuration, your application will be assigned a unique "Client ID"   and "Client Secret" value.


Step2: Using the below PHP code to get the LinkedIn access Token to access there apis


<?php
error_reporting(-1);
echo " testing";
/**
*
*The below is the url to get the Authorization code using our LinkedIn App Details
*/
$url="https://www.linkedin.com/".
'oauth/v2/authorization?response_type=code&client_id=81vfvatntv3k0&'
. 'redirect_uri=http://localhost/servers/link.php&state=DCEeFWf45A53sdfKef424';
$code=$_GET['code'];
if(isset($code)){
$myUrl = "https://www.linkedin.com/oauth/v2/accessToken";
$myData = array(
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => '********',//Redirect Url
'client_id'=>'CLINETId',//Linkedin App Client Id
'client_secret'=>'******'//Linkedin App Secret Key
);
$myHeaders = array(
'Content-type: application/x-www-form-urlencoded'
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $myUrl);
curl_setopt($handle, CURLOPT_HTTPHEADER, $myHeaders);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_POST, true);
//curl_setopt($handle, CURLOPT_POSTFIELDS, $myData);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($myData));
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
print "return code = $code <br/>";
print "response = <br/> $response <br/><br/>";
$myRespArr = json_decode($response, true);
print "<pre>";
print_r($myRespArr['access_token']);
print "</pre>";
exit;
}
?>
<html>
<head>
<title>Linkedin Api </title>
</head>
<body>
<a href="<?php echo $url?>">Click Link
</a>
</body>
</html>





Thursday, September 7, 2017

PHP popen() Function

popen in php

Parallel processing in PHP Using popen() Function


Since PHP does not offer native threads, we have to get creative to do parallel processing.
There will be scenarios where PHP takes much time to complete a task. Example scenarios are attaching a large file and and sending an email, or processing a large video file 
to make thumbnails. Imagine  a user having to wait until PHP finishes the all that job.

All the heavy work might being going on at the server. 
But, if a user doesn't see any activity on a page for some time, they might think that the page is not working and leave the page.  In such cases, we can make use of a background process.


Example of popen as a Async processing

<?php
/*
* This is the child process, it'll be launched
* from the parent process.
*/
/* Do some work */
echo "large process is running";
?>
view raw child.php hosted with ❤ by GitHub
<?php
echo "\n doning the work in Main file\n";
echo date("h:i:s");echo "\n";
$commandName="/var/www/html/main.php"; //Provide full path of the php file
$handle = popen('php ' . $commandName , 'r');
echo date("h:i:s");
?>
view raw main.php hosted with ❤ by GitHub

Make popen as synchronous

The below code will wait until child process completed.
echo date("h:i:s");echo "\n";
$ph = popen('php ' . $commandName , 'r') or die($php_errormsg);
while (! feof($ph)) {
$s = fgets($ph) or die($php_errormsg);
}
pclose($ph) or die($php_errormsg);
echo date("h:i:s");echo "\n";

Friday, September 1, 2017

PHP Array insert, delete, view operation using php array functions

PHP Array Functions

Insert the array element, View the array values and delete the array value using php array functions
Function Name Description
array_search() Searches an array for a given value and returns the key
array_splice() Removes and replaces specified elements of an array


Sample php array functions code


<?php
class arrayFunctions{
public $dialedCustomers;
function __construct($array) {
$this->dialerCustomersCount=$array;
}
public function getValue(){
var_dump($this->dialerCustomersCount);
}
public function insertData($value)
{
$this->dialerCustomersCount[]=$value;
}
public function checkValue($searchValue)
{
return array_search($searchValue, $this->dialerCustomersCount);
}
public function deleteValue($deleteIndex){
array_splice($this->dialerCustomersCount, $deleteIndex, 1);
}
}
$input = array("red", "green", "blue", "yellow");
$values= new arrayFunctions($input);
$values->insertData("57@1000");
$values->getValue();
//checking the value
$status=$values->checkValue("green");
$values->getValue();
if($status != false){
$values->deleteValue($status);
$values->getValue();
}
view raw array.php hosted with ❤ by GitHub

Friday, August 4, 2017

Asterisk Call Originate Action Using Pami

asterisk

What is Asterisk?

Asterisk is an open source framework for building communications applications. Asterisk turns an ordinary computer into a communications server. Asterisk powers IP PBX systems, VoIP gateways, conference servers and other custom solutions. It is used by small businesses, large businesses, call centers, carriers and government agencies, worldwide. Asterisk is free and open source.

About PAMI

PAMI means PHP Asterisk Manager Interface. It is an OOP client for the Asterisk Manager Protocol, implemented in PHP.

About PAMI Features

  • TCP and TLS connections.
  • Event Driven (the framework will dispatch events to your listener).
  • Lightweight, easy of use, and useful.
  • Supports synchronous and asynchronous events (Actions with Responses, and 
  • Responses with Events associated).
  • Supports SMS via VGMS boards.

{
"require": {
"marcelog/pami": "dev-master",
"educoder/pest": "1.0.0",
"react/zmq": "0.2.*|0.3.*"
}
}
view raw composer.json hosted with ❤ by GitHub
require_once 'vendor/autoload.php';
require_once 'configlocal.php';
use PAMI\Client\Impl\ClientImpl;
use PAMI\Listener\IEventListener;
use PAMI\Message\Event\EventMessage;
use PAMI\Message\Action\OriginateAction;
use PAMI\Message\Action\StatusAction;
class PamiEventListener implements IEventListener
{
public function __construct($cli)
{
$this->cli = $cli;
}
/**
* To Handle the All Pami Events
* @param EventMessage $event
*/
public function handle(EventMessage $event)
{
echo $strevt = $event->getKeys()['event'];
$this->var_error_log($event->getKeys());
if ($strevt == 'DialBegin') {
echo "DialBegin event --- \n";
}
if ($strevt == 'DialEnd') {
echo "Dial end event --- \n";
}
if ($strevt == 'Hangup') {
echo "Hangup event --- \n";
}
}
public function var_error_log($object = null)
{
$datetime = date("Y-m-d h:i:s a");
$contents = PHP_EOL . $datetime . " :";
ob_start(); // start buffer capture
var_dump($object); // dump the values
$contents .= ob_get_contents(); // put the buffer into a variable
ob_end_clean(); // end capture
//create the log file if not exist
$log_file_path = "log.txt";
if (file_exists($log_file_path) == false) {
fopen($log_file_path, "w");
}
error_log($contents, 3, $log_file_path);
}
}
////////////////////////////////////////////////////////////////////////////////
// Code STARTS.
////////////////////////////////////////////////////////////////////////////////
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
$options = array(
'host' => 122.111.111.222,
'scheme' => 'tcp://',
'port' => 5038,
'username' => 'testuser',
'secret' => '#######',
'connect_timeout' => 10,
'read_timeout' => 10000000
);
$phonenumber=1000;
$sipNumber=20000;
$a = new ClientImpl($options);
$eventListener = new PamiEventListener($a);
$a->registerEventListener($eventListener);
$a->open();
$time = time();
while (true) {
//(time() - $time) < 60) // Wait for events.
usleep(1000); // 1ms delay
//check the Avilable Agents status
$actionid = md5(uniqid());
$response = $a->send(new StatusAction());
$originateMsg = new OriginateAction('SIP/' . $phonenumber . "@voipgw");
$originateMsg->setContext('dialer');
$originateMsg->setPriority('1');
$originateMsg->setExtension($sipNumber);
$originateMsg->setCallerId($sipNumber);
$originateMsg->setAsync(false);
$originateMsg->setActionID($actionid);
$orgresp = $a->send($originateMsg);
$orgStatus = $orgresp->getKeys()['response'];
// Since we declare(ticks=1) at the top, the following line is not necessary
$a->process();
}
$a->close(); // send logoff and close the connection.
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
view raw index.php hosted with ❤ by GitHub

Tuesday, July 18, 2017

Getting Started with Redis in PHP

What is Redis?

Redis created by Salvatore Sanfilippo is an open source, in-memory data structure server with advanced key-value cache and store, often referred to as a NoSQL database. It is also referred to as a data structure server, since it can store strings, hashes, lists, sets, sorted sets, and more.

The essence of a key-value store is the ability to store some data, called a value inside a key. This data can later be retrieved only if we know the exact key used to store it.

Usage of Redis

  • Caching can be used in the same manner as memcached.
  • Leaderboards or related problems.
  • Counting stuff.
  • Real time analysis.
  • Deletion and filtering.
  • Show latest item listings in your home page.

Install on Windows

Now, let us check how to set up Redis PHP driver.

You need to download the phpredis from github repository https://github.com/nicolasff/phpredis. Once you’ve downloaded it, extract the files to phpredis directory.

extension = redis.so

Connect to Redis Server

<?php
//echo phpinfo();exit;
//Connecting to Redis server on localhost
$redis = new Redis();
$status=$redis->connect('XXX.XXXX.XXX.XXX', $portnumber);
echo "<pre>";
echo "Connection to server sucessfully";
//check whether server is running or not
echo "Server is running: ".$redis->ping();
//creating the key
$key="Key_Name";
$redis->set($key, 'MAK Key Venki');
//Retreving the specified key value
echo $redis->get($key);
// Get the stored keys and print it
$arList = $redis->keys("*");
echo "Stored keys in redis:: " ;
print_r($arList);
?>
view raw redis.php hosted with ❤ by GitHub

Monday, July 17, 2017

PHP ZMQ extension Installation in Apache 2.4 & php 5.6


PHP ZMQ extension we will look at how you can easily distribute work to background processes, provide flexible service brokering for your next service oriented architecture, and manage caches efficiently and easily with just PHP and the ZeroMQ libraries. Whether the problem is asynchronous communication, message distribution, process management or just about anything, ZeroMQ can help you build an architecture that is more resilient, more scalable and more flexible, without introducing unnecessary overhead or requiring a heavyweight queue manager node..

Installing ZMQ in Windows

Required Softwares Apache 2.4 & PHP 5.6
  1. Download the zmq php extension from following url depends up on the installed php version
    url: ZMq Download Url
  2. Extract the folder
  3. Copy the php_zmq.dll to php/ext directory
  4. Then copy the libzmq.dll to the php/ root directory
  5. Add below line in php.ini file : extension=php_zmq.dll

Friday, November 18, 2016

Get magento session variable in php page

Mage::app('admin'); //get the admin session
Mage::getSingleton('core/session', array('name'=>'adminhtml')); //verify if the user is logged in to the backend
if(Mage::getSingleton('admin/session')->isLoggedIn()){
echo "logged in";
}else{
$url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
header('Location: '.$url."index.php/admin");
exit;
}