Monday, October 16, 2017
Friday, October 6, 2017
Connect to Microsoft SQL Server Using PHP
Connect to Microsoft SQL Server Using PHP
<?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); |
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:
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> | |
Friday, September 8, 2017
Reading Excel Spreadsheets with Python
![]() |
Excel & Python |
Reading an Excel Spreadsheet
In this section, we will look at a function that demonstrates reads the Excel sheet data and convert that data into XML file.We Used the following libraries to do the above functionality
- Openpyxl : Openpyxl is a Python library for reading and writing Excel 2010 xlsx/xlsm/xltx/xltm files.
- xml.etree.ElementTree: To create the xml tree elements
- datetime: to conver the date time column values to specified format
from openpyxl import load_workbook | |
import datetime | |
import xml.etree.cElementTree as ET | |
wb = load_workbook(filename = 'Sku Assignment 8.24 Furniture Content.xlsx') | |
sheet = wb.get_sheet_by_name('Output Sheet')#sheet name | |
root = ET.Element("skuProducts") | |
i=0 | |
for rowOfCellObjects in sheet.rows: | |
doc = ET.SubElement(root, "skuProduct"+str(i)) | |
j=0 | |
for cellObj in rowOfCellObjects: | |
print(cellObj.coordinate, cellObj.value) | |
print type(cellObj.value) | |
datatype = type(cellObj.value) | |
if( datatype is unicode): | |
ET.SubElement(doc, cellObj.coordinate).text = cellObj.value | |
elif( datatype is long): | |
print int(cellObj.value) | |
ET.SubElement(doc, cellObj.coordinate).text = str(int(cellObj.value)) | |
elif isinstance(cellObj.value, datetime.date): | |
#print cellObj.value.strftime('%m/%d/%Y') | |
#pass | |
ET.SubElement(doc, cellObj.coordinate).text = str(cellObj.value.strftime('%m/%d/%Y')) | |
else: | |
print "pass" | |
pass | |
j=j+1 | |
i=i+1 | |
print('--- END OF ROW ---') | |
tree = ET.ElementTree(root) | |
tree.write("filename.xml") |
Thursday, September 7, 2017
PHP popen() Function
![]() |
popen in php |
Parallel processing in PHP Using popen() Function
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"; | |
?> |
<?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"); | |
?> |
Make popen as synchronous
The below code will wait until child process completed.$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
Install mysql-python in windows
To Enable the mysql extension related python need to run the below command
If you are trying to use mysqlclient on WINDOWS with this failure,
"_mysql.c(29) : fatal error C1083: Cannot open include file: 'my_config.h': N
such file or directory"
try to install the lower version instead:
Configure Apache web server for Python on Windows
Run Python script as CGI program with Apache2.4 in Windows
Python: http://python.org/download/.
Apache: http://httpd.apache.org/download.cgi
2. Configure Apache to run Python CGI
The next step is to edit ‘httpd.conf’ apache configuration file located in the apache
install directory in the conf directory.
Uncomment the below line
#LoadModule cgi_module modules/mod_cgi.so
After Uncomment
LoadModule cgi_module modules/mod_cgi.so
Search the httpd.conf file for the line
Options Indexes FollowSymLinks
Add ExecCGI to the end of the line. After adding total line looks like below
Options Indexes FollowSymLinks ExecCGI
Next, search for the following:
#AddHandler cgi-script .cgi
Uncomment this line by removing the # in front of the line,
and add a .py to the end of the line. The new line should look like this:
AddHandler cgi-script .cgi .py
Search for the line: ScriptAlias /cgi-bin/ /whatever-path/ – when you find it,
comment out the line: that is add a # in front of the line:
(or)Other wise add the below line
ScriptAlias /cgi-bin/ "C:/Apache2.4/cgi-bin/"
3. Restart Apache
4. Run the sample python file
Here is an example assuming Python is installed in the C:\Python27 location
#!/Python27/python.exe | |
print("Content-type: text/html") | |
print("") | |
print("<html><head>") | |
print("") | |
print("</head><body>") | |
print("Hello from Python27 .") | |
print("</body></html>") |
Save this file as test.py to your htdocs folder under your apache installation directory.
Open your web browser and type in your apache host
(and :port if the port is something other than 80) followed by test.py,
for example: http://localhost/test.py
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 functionsFunction 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(); | |
} | |
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.*" | |
} | |
} |
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"; | |
} |
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.
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); | |
?> |
Monday, July 17, 2017
Inter Process Communication Using PHP ,ZeroMQ AND React/ZMQ

push the external changes to existing web pages
The above diagram shows the any external php file or database layer changes has happen should be notify to all our web client. We can able to achieve this using React/ZMQRequirements
ZeroMQ
All Our client web pages will be listening to port 8080 for incoming WebSocket connections...but how will it also get updates from another PHP script or another server process event. Enter ZeroMQ. We could use raw sockets, like the ones Ratchet is built on, but ZeroMQ is a library that just makes sockets easier. install zmq
React/ZMQ
Ratchet is a WebSocket library built on top of a socket library called React. React handles connections and the raw I/O for Ratchet. In addition to React, which comes with Ratchet, we need another library that is part of the React suite: React/ZMQ. This library will bind ZeroMQ sockets to the Reactor core enabling us to handle both WebSockets and ZeroMQ sockets. To install, your composer.json file should look like this:
{ | |
"autoload": { | |
"psr-0": { | |
"MyApp": "src" | |
} | |
}, | |
"require": { | |
"cboden/ratchet": "0.3.*", | |
"react/zmq": "0.2.*|0.3.*" | |
} | |
} |
<?php | |
require dirname(__DIR__) . '/vendor/autoload.php'; | |
$loop = React\EventLoop\Factory::create(); | |
$pusher = new MyApp\Pusher; | |
// Listen for the web server to make a ZeroMQ push after an ajax request | |
$context = new React\ZMQ\Context($loop); | |
$pull = $context->getSocket(ZMQ::SOCKET_PULL); | |
$pull->bind('tcp://127.0.0.1:55556'); // Binding to 127.0.0.1 means the only client that can connect is itself | |
$pull->on('message', array($pusher, 'onBlogEntry')); | |
// Set up our WebSocket server for clients wanting real-time updates | |
$webSock = new React\Socket\Server($loop); | |
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect | |
$webServer = new Ratchet\Server\IoServer( | |
new Ratchet\Http\HttpServer( | |
new Ratchet\WebSocket\WsServer( | |
new Ratchet\Wamp\WampServer( | |
$pusher | |
) | |
) | |
), | |
$webSock | |
); | |
$loop->run(); |
<?php | |
namespace MyApp; | |
use Ratchet\MessageComponentInterface; | |
use Ratchet\ConnectionInterface; | |
class Chat implements MessageComponentInterface { | |
protected $clients; | |
public function __construct() { | |
$this->clients = new \SplObjectStorage; | |
} | |
public function onOpen(ConnectionInterface $conn) { | |
// Store the new connection to send messages to later | |
$this->clients->attach($conn); | |
echo "New connection! ({$conn->resourceId})\n"; | |
} | |
public function onMessage(ConnectionInterface $from, $msg) { | |
$numRecv = count($this->clients) - 1; | |
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n" | |
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); | |
foreach ($this->clients as $client) { | |
if ($from !== $client) { | |
// The sender is not the receiver, send to each client connected | |
$client->send($msg); | |
} | |
} | |
} | |
public function onClose(ConnectionInterface $conn) { | |
// The connection is closed, remove it, as we can no longer send it messages | |
$this->clients->detach($conn); | |
echo "Connection {$conn->resourceId} has disconnected\n"; | |
} | |
public function onError(ConnectionInterface $conn, \Exception $e) { | |
echo "An error has occurred: {$e->getMessage()}\n"; | |
$conn->close(); | |
} | |
} |
<html> | |
<head> | |
<title>Testing</title> | |
<script src="autobahn.js"></script> | |
<script> | |
var conn = new ab.Session('ws://localhost:8080',function() { | |
conn.subscribe('kittensCategory', function(topic, data) { | |
// This is where you would add the new article to the DOM (beyond the scope of this tutorial) | |
console.log('New article published to category "' + topic + '" : ' + data.title); | |
}); | |
}, | |
function() { | |
console.warn('WebSocket connection closed'); | |
}, | |
{'skipSubprotocolCheck': true} | |
); | |
</script> | |
</head> | |
<body> | |
<h1> Sample Client web page </h1> | |
</body> | |
</html> |
<?php | |
// post.php ??? | |
// This all was here before ;) | |
$entryData = array( | |
'category' =>"kittensCategory" | |
, 'title' => "Ces Dialer" | |
, 'article' => "First Articale" | |
, 'when' => time() | |
); | |
// This is our new stuff | |
$context = new ZMQContext(); | |
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher'); | |
$socket->connect("tcp://localhost:55556"); | |
$socket->send(json_encode($entryData)); |
<?php | |
namespace MyApp; | |
use Ratchet\ConnectionInterface; | |
use Ratchet\Wamp\WampServerInterface; | |
class Pusher implements WampServerInterface { | |
/** | |
* A lookup of all the topics clients have subscribed to | |
*/ | |
protected $subscribedTopics = array(); | |
public function onSubscribe(ConnectionInterface $conn, $topic) { | |
echo "subscribe\n"; | |
print_r($topic->getId()); | |
$this->subscribedTopics[$topic->getId()] = $topic; | |
} | |
public function onUnSubscribe(ConnectionInterface $conn, $topic) { | |
} | |
public function onOpen(ConnectionInterface $conn) { | |
} | |
public function onClose(ConnectionInterface $conn) { | |
} | |
public function onCall(ConnectionInterface $conn, $id, $topic, array $params) { | |
// In this application if clients send data it's because the user hacked around in console | |
$conn->callError($id, $topic, 'You are not allowed to make calls')->close(); | |
} | |
public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) { | |
// In this application if clients send data it's because the user hacked around in console | |
$conn->close(); | |
} | |
public function onError(ConnectionInterface $conn, \Exception $e) { | |
} | |
/** | |
* @param string JSON'ified string we'll receive from ZeroMQ | |
*/ | |
public function onBlogEntry($entry) { | |
$entryData = json_decode($entry, true); | |
print_r($entryData); | |
// If the lookup topic object isn't set there is no one to publish to | |
if (!array_key_exists($entryData['category'], $this->subscribedTopics)) { | |
return; | |
} | |
$topic = $this->subscribedTopics[$entryData['category']]; | |
// re-send the data to all the clients subscribed to that category | |
$topic->broadcast($entryData); | |
} | |
} |
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- Download the zmq php extension from following url depends up on the installed php version
url: ZMq Download Url - Extract the folder
- Copy the php_zmq.dll to php/ext directory
- Then copy the libzmq.dll to the php/ root directory
- Add below line in php.ini file : extension=php_zmq.dll
Friday, April 7, 2017
Defining a HTML template to append using JQuery
Append Dynamic content to html template using Jquery
If we want to append the dynamic content to html template using jquery below will be the simple solution<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Modular Design Pattern</title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<div>TODO write content | |
<input type="button" name="button" value="buttonclick" id="buttonclick"/> | |
<div id="target"></div> | |
</div> | |
</body> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> | |
<script> | |
$(document).ready(function () { | |
//Clone the template | |
var template = $('#hidden-template').html(); | |
$('#buttonclick').click(function () { | |
//Clone the template | |
var item = $(template).clone(); | |
//Find the | |
$(item).find('.first').html("First"); | |
//Change 'bar' to '-Bar' | |
$(item).find('#bar').html("-Bar"); | |
//Append to the source | |
$('#target').append(item); | |
}); | |
}); | |
</script> | |
<script id="hidden-template" type="text/x-custom-template"> | |
<tr> | |
<td class="first">Foo</td> | |
<td id="bar">Bar</td> | |
<tr> | |
</script> | |
</html> |
Wednesday, April 5, 2017
Iframe communication or Accessing a cross-origin frame
Accessing a cross-origin frame.
window.postMessage allows you to send messages not only across frames (regular frame or iframe) but also across domains. This post showed interaction from parent to child. Even when we keep the iframe domain url is different for the main page url.With out using the window.postMessage will gives us below error message in console
SecurityError: Blocked a frame with origin from accessing a cross-origin frame
You can't access an iframe with Javascript, it would be a huge security flaw if you could do it.For the same-origin policy browsers block scripts trying to access a frame with a different origin.
Origin is considered different if at least one of the following parts of the address isn't maintained:
Examples
Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html
URL RESULT
http://www.example.com/home/other.html -> Success
http://www.example.com/dir/inner/another.php -> Success
http://www.example.com:80 -> Success (default port for HTTP)
http://www.example.com:2251 -> Failure: different port
http://data.example.com/dir/other.html -> Failure: different hostname
https://www.example.com/home/index.html.html -> Failure: different protocol
ftp://www.example.com:21 -> Failure: different protocol & port
https://google.com/search?q=james+bond -> Failure: different hostname & protocol
Workaround
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>My Iframe</title> | |
</head> | |
<body> | |
<button>Button</button> | |
<div id="childdiv"> </div> | |
<script type="text/javascript"> | |
//To Recive the parent frame message | |
document.querySelector('button').onclick = function () { | |
parent.postMessage("myevent", "*") | |
}; | |
</script> | |
</body> | |
</html> |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Index</title> | |
</head> | |
<body> | |
<iframe src="iframe.html" id="iframe" width="300" height="300"></iframe> | |
<script type="text/javascript"> | |
var eventMethod = window.addEventListener | |
? "addEventListener" | |
: "attachEvent"; | |
var eventer = window[eventMethod]; | |
var messageEvent = eventMethod === "attachEvent" | |
? "onmessage" | |
: "message"; | |
eventer(messageEvent, function (e) { | |
alert('Message from iframe just came!'); | |
console.log(e); | |
}); | |
//send message to child window | |
window.onload = function () { | |
document.getElementById("iframe").contentWindow.postMessage( | |
'test message', | |
"*" | |
); | |
}; | |
</script> | |
</body> | |
</html> |
Monday, April 3, 2017
Get Google contacts with Javascript using Google Contacts API and OAUTH 2.0
To get the Google Contacts with Javascript using Google Contacts Api
To Pull the google contacts we need to create a project in google developer consoleCreate a Google application in Google Developers Console for obtaining your Client id and Client secret
- Go to Google Google Developers Console and login with your google account.
- create one a project by clicking Create Project Button
- Go into the newly created project
- Click On the Menu icon and select the Api Manager Link
- Search for “Contacts API” and click on it
-
- Enable the “Contacts API” by hitting the “Enable API” button
-
-
<html> | |
<head> | |
<title>Google Contacts</title> | |
</head> | |
<body> | |
Body ..... | |
<div id="con"> </div> | |
<button onclick="auth();">GET CONTACTS FEED</button> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> | |
<script src="https://apis.google.com/js/client.js"></script> | |
<script type="text/javascript"> | |
function auth() { | |
var config = { | |
'client_id': "client_id", | |
'scope': 'https://www.googleapis.com/auth/contacts.readonly' | |
}; | |
gapi.auth.authorize(config, function() { | |
fetch(gapi.auth.getToken()); | |
}); | |
} | |
function fetch(token) { | |
$.ajax({ | |
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", | |
dataType: "jsonp", | |
success:function(data) { | |
// display all your data in console | |
// console.log(JSON.stringify(data)); | |
// $("#con").html(data); | |
var data=data; | |
var entry=data.feed.entry; | |
$( entry ).each(function( index,vaule ) { | |
var phone=""; | |
if(vaule.gd$phoneNumber){ | |
phone=" Phone No:"+vaule.gd$phoneNumber[0].$t; | |
} | |
var cont="<div> <span>"+index+" </span>"+ vaule.title.$t+phone+"</div>"; | |
$("#con").append(cont); | |
}); | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Friday, March 31, 2017
Deploy files or directory hierarchies to a server using Grunt and ppk file
Grunt Sftp Deployment using ppk file
Add Grunt sftp-deploy plugin using below command
Create the Gruntfile.js
module.exports = function(grunt) { | |
grunt.initConfig({ | |
//server deployment | |
'sftp-deploy': { | |
build: { | |
auth: { | |
host: 'wwww.hostname.com', | |
port: 22, | |
authKey: 'privateKeyCustom' | |
}, | |
cache: 'sftpCache.json', | |
src: "js_files/", | |
dest: "/var/www/root2", | |
serverSep: '/', | |
concurrency: 4, | |
progress: true | |
} | |
}, | |
}); | |
grunt.loadNpmTasks('grunt-sftp-deploy'); | |
}; |
Create the .ftppass The below file will contains the server connection details
{ | |
"privateKeyCustom": { | |
"username": "root", | |
"keyLocation": "E:/credentials/keys/serverkey.ppk" | |
} | |
} |
>> Logging in with key at E:/credentials/keys/serverkey.ppk
>> Concurrency : 4
transferred=[1/3] elapsed=[0.0s] overall=[33%] eta=[0.0s] [====== ]
>> Directories done.
transferred=[2/3] elapsed=[0.7s] overall=[67%] eta=[0.4s] [============ ]
>> Transferred : 0 Mb
Done, without errors.
Wednesday, February 8, 2017
GUI version control for Linux system
TortoiseSVN alternative for Linux is RabbitVCS.
Install RabbitVCS in Ubuntu
Not just for SVN / Nautilus
Install RabbitVCS in Ubuntu
1. Add the RabbitVCS Ubuntu PPA:sudo add-apt-repository ppa:rabbitvcs/ppa && sudo apt-get update
2. Install RabbitVCS:
- For Nautilus 2:
sudo apt-get install rabbitvcs-core rabbitvcs-nautilus rabbitvcs-cli
sudo apt-get install rabbitvcs-core rabbitvcs-nautilus3 rabbitvcs-cli
sudo apt-get install rabbitvcs-core rabbitvcs-cli rabbitvcs-thunar
Once installed, restart Nautilus / Thunar (for Nautilus, type "nautilus -q" in a terminal).
Optional: If you also want to install the RabbitVCS Gedit extension, use the following command:
sudo apt-get install rabbitvcs-gedit
Friday, February 3, 2017
Check Mod Rewrite Enabled or not in Apache
Check mod rewrite is enabled or not
1. Create sample.php file in localhost root folder with below content
output check for mod_rewrite
2.To check .htaccess is working keep the below code in .htaccess
RewriteRule ^.*$ test.php
REMOTE DEBUGGING ON IOS for Ios APACHE CORDOVA and mobile webpages
Safari Remote Debug Tool
This tutorial will show you how to remotely debug your cordova app on iOS using the safari remote debug tool to inspect the java script errors .
Enable Debugging on Desktop side
Enable Debug Mode on Mobile
Now, you need to enable Web Inspector in the advanced Safari Settings of your iOS Device. Go to Settings > Safari > Advanced and enable Web Inspector.Inspect with Safari
Now we're finally able to remotely debug our cordova webview with Safari. First, launch your app on your iOS device connected to the computer via USB.
In Safari desktop, Go to Develop > Your iPad/iPhone > Index.html.
That's it! Now you should be able to debug your app like any other website!
Debug JavaScript Step by Step
Exactly like you would do on any website, you can remotely debug step by step your JavaScript code in the Safari Web Inspector.
Wednesday, January 25, 2017
Firebase cloud messaging Push Notification for Websites (fcm)
Getting a Configuration File
- Go to firebase console and create a new project.
- Now put your app name and select your country.
- Now click on Add Firebase to Your Android App.
- Write some code for registering the service worker
- index.html
- this file is responsible to subscribe the user devices and sends the device tokens to server.
var config = { apiKey: "AIzaSyDaY7_6yfeMbXIQNLgrLa3n_IqweQ", authDomain: "push-a1eaa.firebaseapp.com", databaseURL: "https://push-a1eaa.firebaseio.com", storageBucket: "push-a3eaa.appspot.com", messagingSenderId: "3490973264967" }; firebase.initializeApp(config); const messaging = firebase.messaging(); messaging.requestPermission() .then(function () { console.log('Have permission'); return messaging.getToken(); }) .then(function (token) { document.getElementById("bigone").innerHTML = token; console.log(token); }) .catch(function (err) { console.log('Unable to get permission to notify.', err); }); messaging.onMessage(function (payload) { console.log("Message received. ", payload); });
- firebase-messaging-sw.js
include two files : https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js
// Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': '3490973264967' }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging(); // If you would like to customize notifications that are received in the // background (Web app is closed or not in browser focus) then you should // implement this optional method. // [START background_handler] messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, }; return self.registration.showNotification(notificationTitle, notificationOptions); });
- this file is responsible to receive the messages from fcm and shows the notification information
- Send Push notifications to client
- Curl request on the server side:
curl "https://fcm.googleapis.com/fcm/send" --request POST --header "Authorization: key=server_key" --header "Content-Type: application/json" -d "{\"to\":\"client_token\"}"
method: POST
Authorization:key=AIzaSyDJK8dkx_7-7RdJ3YsIg_ueGFnPgOGQD0k
{
"notification": {
"title": "Portugal vs. Denmark",
"body": "5 to 1",
"icon": "firebase-icon.png",
"click_action": "http://localhost:8081"
},
"registration_ids":["eBdhRIGunJk:APA91bFVvA9XMJoXrKrgvY57wiY4tIsYJFLjW5AjgZOIZ-dRDIDxkM87eCEokvRW9jk01kyFN-
ypGYTQ_PymwbAglwS00tQqrKiG1ex29V_Uplje7dbqV988MuyifJ1zBAesHGI0vger","coWde0lMz-Q:APA91bFZB9MRqO04ZOfk80VV8WAnmDng7_NPTPDGP2Bi0PbVhPPOT-
Nr7vfmLiDDLA1N9Y-wAYv0pGDgKImKoN1uVgCQ_2uAfVexo0wM8UEs7tY8UNNXnZjSdzEK67XSlB8o6TIZQs0G"]
}
- Reference youtube url
Getting Started with Firebase Cloud Messaging on the Web - Firecasts
Friday, January 13, 2017
Create Ftp User
2. mkdir /var/www/mydomain.com/html
3. useradd <-username>
4. passwd <-username>
5. chown –R <-username> /var/www/mydomain.com
Set the home directory of the user with the following command
Add Remote Origin to local Git Repository
Steps to add local files to new git repository
Step 1: Switch to your repository's directory
Step 2: Connect your existing repository to github
git remote add origin https://kotturs@github.org/tech/tech.git
git pull origin master
git add
git commit -m "message"
git push origin master