Links

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

Web-Services recapitulate

Now days most of the apps are using WebServices and the good thing is we all know what it is :)

Just adding some notes from my side on things like SOAP, REST and ......., and what? is there anything else do we have in the name of WebService.. really?

Few days ago, a guy who have experience of more then a decade came to me and told me to integrate WebService in an app. I simply asked for WebService summary which I think an usual question while we start working on something. He said to take the reference from an existing website which he pretended that using the same. First I did't get what he wanted to tell but, his steps just gave me heart attack. He just went to Chrome, opened the Website, right clicked for the Inspect element option and while logging in to that website he monitored the Network and said look here is the WebServices just replicate it in your app. After his statement I thought is it worth to ask something anymore?




Okey, letz do a quick recap on what we know:

  1. Charles, Yet simplest tool to monitor a WebService request from an iOS and Mac environment
  2. Each and every resource request to an URI is not a WebService.
  3. One is SOAP and the rest is REST, why do extensive debate
  4. SOAP is XML based definitive object access WebService protocol made for rich guys :)
  5. OAUTH is a two tear authorization framework, ie 

iOS + WS 
  1. Avoid using 3rd party wrappers like ASIHTTP for networking without exploring them
  2. NSURLRequest + NSURLConnection are not an evil
  3. Use event driven APIs
  4. Reachability is our friend
  5. Don't put sync requests on main thread
  6. Your app UI should reflect network reality 
  7. Be prepared for speed latency and packet loss
  8. Be prepared for no network and host not reachable conditions
  9. Always code for insecure connection, use end to end security 
  10. Minimize use of network connections, keep in mind that we also have push notifications 

PHP + WS
  1. Always think above $_POST, $_GET, $_REQUEST, $_FILE they are just to help you 
  2. Use and read headers generously
  3. php://input thats what you need 
  4. Don't forget your buddy "MIME types"
  5. Be prepared for Trojan and Injunction
  6. PHP is more related to network, explore its low level possibilities
  7. Take authorization and content distribution seriously

JS + WS
  1. Don't misuse client network and resources :|
  2. Just enjoy with JSON, sometime XML and leave it all for server side :)

Simple JS minification tool


ONLINE TOOL URL
http://closure-compiler.appspot.com/home



SAMPLE CODE
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js

// ==/ClosureCompiler==

// ADD YOUR CODE HERE
function hello(name) {
alert('Hello, ' + name);
}
hello('New user');



TO INCLUDE EXTERNAL FILE
add following code with the full path to the files

// @code_url https://dl.dropbox.com/u/37581115/.js
// @code_url https://dl.dropbox.com/u/37581115/.js


BDD vs TDD

If you’re not familiar with these acronyms, they stand for Behaviour-Driven Development and Test-Driven Development, BDD is little more complex as compare to TDD here are some of the basic differences:

WebSocket in HTML5

HTML5 provides a new thing called a WebSocket. Now data can flow between the browser and server without having to send HTTP headers until the connection is broken down again. Welcome to the world of PUSH technology!

What is Websocket?
WebSocket is bi-directional (full-duplex) communication channel over a single TCP (Transmission Control Protocol) socket for client or server application... goes too much technical, ok then
WebSockets opens a connection to a server and the connection stays open until you decide to close it. From there, you can start sending messages from the browser to the server and you can define a callback function for when the server send data back. Basically we got rid of each time new request for server.

Google Code Prettify

It is a truly better and easier way for syntax highlighting of code snippets in a web page with good cross-browser support. It contains a Theme based Customizable CSS file which you can chose from its gallery of theme and a Javascript module file that allows syntax highlighting of source code snippets in an html page. It is also light weighted and have basic support to all  C (and friends), Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles languages (because of commenting conventions, doesn't work on Smalltalk, or CAML-like languages), and we don't need to specify the language. Apart this for Clojure, CSS, Go, Haskell, Lua, OCAML, SML, F#, Nemerle, Protocol Buffers, Scala, SQL, TeX, LaTeX, VHDL, Visual Basic, WikiText, XQuery, and YAML. it have an extensible language handlers for other languages in such case you can specify the language.

Cross site AJAX request

For cross site AJAX request we need following headers in host site:


Access-Control-Allow-Origin : http://example1.com, http://example2.com, ..
( it is necessary to mention requesting sites reference for localhost we can use http://127.0.0.1 and to grant access to all sites we can also use * )
 
Access-Control-Allow-Headers : Header1, Header2, ..
(we need to mention the permissions for headers send by other site)

Access-Control-Allow-Methods : POST, OPTIONS, ..(we also need to mention Request methods supported by our site for other sites GET is by default open)

PHP Framework

Cake PHP

If you still need to write PHP4 compatible code, CakePHP is a great option. This PHP 4 & 5 MVC framework is one of the oldest and most popular on our list. Cake PHP has built up a reputation as a formidable and capable framework. It also has many avenues for support (groups, message boards, IRC) and excellent tutorials. CakePHP is a good framework that's easy to get into but one that you won't outgrow in a couple of weeks.

CakePHP's conventions are fairly strict, however, and it's not the most flexible framework available. This could be a plus if you want to guarantee consistency across the application regardless of the user. There are also built-in tools for unit testing, XML-RPC and feed parsing for integration with web services as well as scaffolding for rapid prototyping.


Zend Framework

The Zend Framework is for more experienced developers and those building enterprise-level applications. The framework is highly modular, meaning you can use as little or as much of the Zend code as you need. Several libraries can easily be extracted for stand-alone use. With Zend, you're not tied to the MVC pattern (though it is certainly an option), and there is a lot of built-in support for tasks such as integration with existing web services, localization and extensive unit testing.

Zend requires PHP 5.1.4+ but has multiple configuration options and excellent documentation. It's a framework with corporate backing and a strong community. You'll get long-term stability and fairly quick integration of new features, not to mention security updates tested by a team of professionals. While the Zend framework may be a large overhead for small projects, if you're building large-scale applications it is typically considered the framework of choice.


CodeIgniter

CodeIgniter is (as of v2.0) a PHP5.2+ MVC framework with a small footprint and great documentation. Often called a "beginners" framework because of its relative ease of use and short learning curve, CodeIgniter is nonetheless flexible and powerful. The framework has a large community surrounding it, so it's fairly easy to find an existing CI library for just about anything you could dream up. If you need to do it, chances are, someone out there already has.

CodeIgniter is best suited for content sites and small-to-medium web applications. You'll likely see a performance drop with very large numbers, but there is some built-in caching to help with that. If you're new to PHP frameworks or want something that can be picked up and learned in a few hours, CodeIgniter is one of the top frameworks to consider.


Symfony

Symfony is one of the oldest PHP frameworks, and is designed for enterprise-level web applications. For all its power and performance, however, Symfony has a small footprint and is easy to configure on a variety of PHP hosting environments. Since it's been around for so long, you’ll find a lot of tutorials and books available on framework use, a perk for new users.

Symfony uses command line generators for quick project setups and automatic code generation, which may be new to some developers. However, they allow you to get up and running with your code in very short order. If you feel intimidated by this, don't worry. The Symfony's web site has a large collection of tutorials, showcase applications and screencasts to get you going.

The framework has all of the advanced features you'd expect of a system designed for the development of enterprise software. For example, it offers internationalization, URL routing, test suites, a robust templating engine and a powerful plug-in API for extending Symfony's features, or adding your own.


Kohana

Kohana began as a fork of CodeIgniter, though it’s much more than a simple branch off. Like CI, Kohana strives to be a lightweight, easy-to-use framework that performs well for small-to-medium web applications and custom content management systems.

Unlike CodeIgniter, Kohana requires PHP 5.3. The developers have taken advantage of this by including some advanced functionality not present in Codeigniter. The 5.3 requirement also means less code can accomplish some of the same tasks with less concern over backwards comparability. While Kohana's documentation is a little lacking, it tends to implement features more cleanly. The community is active, so getting help shouldn't be an issue.


Yii

Yii is a highly modular, high-performance PHP5 framework designed specifically for developing web applications. Yii uses a lot of command line generators and tools to get you up and running quickly; therefore, it's best used by people that aren't intimidated by a terminal window. All those generators mean more commands to memorize, but once you do, you'll find that they greatly decrease the time it takes to set up and configure your application.

It's easy to extend Yii and add in your favorite third-party libraries. Yii also supports templating, themes and widgets, and includes tools for testing, libraries for internationalization and web service integration. Yii's performance is good and the automatic code generation makes it a great framework for rapid development. The framework is well-documented, but since so much of the work is done at the command line, it can be intimidating to some users.

license

 Copyright (c) 2011 Gaurav S Tomar, http://gauravstomar.blogspot.com/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

PHP one line to access JSON feed url

$contents = get_object_vars(json_decode(stream_get_contents(fopen("http://www.google.com/base/feeds/snippets?q=for+sale&orderby=[x%3Dbedrooms(int)%3A+if+exists(x)+then+max(x)+else+0]&alt=json","rb"))));

Data scraping with cURL and php 5


< ?php $db = mysql_pconnect('127.0.0.1', 'root', '');
mysql_select_db('crawl',$db) or die("Error In database : ".mysql_error()); set_time_limit(999999999); //error_reporting(0); if (!function_exists('array_combine')) { function array_combine($keys, $values) { if (count($keys) != count($values)) { return false; } foreach($keys as $key) { $array[$key] = array_shift($values); } return $array; } } function get_via($query,$url) { $ch=curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $query); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0"); curl_setopt($ch,CURLOPT_ENCODING , "UTF-8"); $content = curl_exec($ch); curl_close($ch); return $content; } function get_file1($file, $newfilename) { $err_msg = ''; $out = fopen($newfilename, 'wb'); if ($out == FALSE) { print "File not opened "; exit; } $ch = curl_init(); curl_setopt($ch, CURLOPT_FILE, $out); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $file); curl_exec($ch); curl_close($ch); } $dom=new domdocument; $alpha=$_REQUEST['searchInput'];
for($i=0;$i<100;$i=$i+10) page="($i=" query="$alpha&searchtype=" query="$alpha&searchtype=" pagestart="">loadhtml(get_via("",$page));
$nodes = $dom->getElementsByTagName('div');
foreach($nodes as $P)
{
if($P->getAttribute('class')=='searchResultsItemHolder searchResultsArtistItemHolder')
{
$insideDiv=$P->childNodes;
foreach($insideDiv as $divElement)
{
if($divElement->nodeName=="a")
{
if($divElement->getAttribute('class')=='artistLink')
{
$data["details"]=$divElement->getAttribute('href');
$data["name"]=$divElement->getAttribute('title');
$image=$divElement->childNodes;
foreach($image as $img)
{
$data["imagename"]="GsT".rand(0,time()).".jpg";
mysql_query("INSERT INTO `tN`.`tA` (`uid` ,`art_name` ,`art_pic` ,`Track`)
VALUES ('1', '".mysql_escape_string($data["name"])."', '".mysql_escape_string($data["imagename"])."', '".mysql_escape_string($data["details"])."')") print(mysql_error());
if(mysql_insert_id()>0)
{
get_file1($img->getAttribute('src'), "images/artist/".$data["imagename"]);
}
}
}
}
}
}
}
}
?>

URL Rewriting in zend framework

$front = Zend_Controller_Front::getInstance();


/* Check in you project $front may be differ for Zend_Controller_Front::getInstance();
now suppose we have to convert path mysite.com/user/profile/of/gauravstomar
to mysite.com/users/gauravstomar
then you need to define a route here it is $route */


$route = new Zend_Controller_Router_Route('users/:of',array('controller'=>'user','action'=>'profile'));

// here :of represents the of parameter of the url
// and put it in

$front->getRouter()->addRoute('users', $route);

Proudly launching iVotings.com

this is one of my projects @ xevoke which i made as better as i can, we have a limited time frame for this but in my opinion this is one of my best project i ever built. a very user friendly and too much fast as we have lots of calculations and each calculation have heavy data base interaction.

iVotings.com take my most of time to make it faster to download... lots of stuff i used in it to make it possible like JSON, DB Cache and lots more.

i wish that this site will go much higher.

Use of Zend Cache

Zend Cache will help you to prevent the time taken for heavy sql query.




Lines to be added in bootstrap file:

Zend_Loader::loadClass('Cache');
$backend= 'File';$frontend = 'Core';
$frontendOptions= array('lifetime' => 7200);
$backendOptions= array('cache_dir' => 'public/temp');
$cache = Zend_Cache::factory($frontend, $backend,$frontendOptions,$backendOptions);
Zend_Registry::Set('cache',$cache);




Lines to be added in init function of your controller file:


$this->cache = Zend_Registry::get('cache');


Lines to use the Zend Cache:

$data = $this->cache->load('TempVar');
if($data === FALSE)
{
$query=$this->db->query("SELECT * FROM table_name");
$data = $query->fetchAll();
$this->cache->save($data,'UserCompair');
}
$this->view->users = $data

Countrys MySql database with their flags

Here is the mysql database for country listing with there maps in different size PNG files.

Using JSON with PHP : an example

__________________________________________
index.php
______________________________________________

$array = array
(
["books"] => array(
["0"] => array
(
["book"] => array
(
["title"] => "JavaScript, the Definitive Guide"
["publisher"] => "O Reilly"
["author"] => "David Flanagan"
["cover"] => "/images/cover_defguide.jpg"
["blurb"] => "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
)

)

["1"] => array
(
["book"] => array
(
["title"] => "DOM Scripting"
["publisher"] => "Friends of Ed"
["author"] => "Jeremy Keith"
["cover"] => "/images/cover_domscripting.jpg"
["blurb"] => "Praesent et diam a ligula facilisis venenatis."
)

)

["2"] => array
(
["book"] => array
(
["title"] => "DHTML Utopia: Modern Web Design using JavaScript & DOM"
["publisher"] => "Sitepoint"
["author"] => "Stuart Langridge"
["cover"] => "/images/cover_utopia.jpg"
["blurb"] => "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
)

)

)

)
die(json_encode($array));

______________________________________
index.js
______________________________________
window.onload = xmlHttp;

function xmlHttp()
{
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else if (window.ActiveXObject){xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
else alert("XMLHttpRequest & ActiveXObject not active");
xmlhttp.open('POST', "index.php", true);
xmlhttp.onreadystatechange = function(){if(xmlhttp.readyState == 4 && xmlhttp.status == 200)setDataJSON(eval('(' + xmlhttp.responseText + ')'));}
xmlhttp.send(r);
}

function setDataJSON(req)
{
var data = eval('(' + req.responseText + ')');
for (var i=0;i {
var x = document.createElement('div');
x.className = 'book';
var y = document.createElement('h3');
y.appendChild(document.createTextNode(data.books[i].book.title));
x.appendChild(y);
var z = document.createElement('p');
z.className = 'moreInfo';
z.appendChild(document.createTextNode('By ' + data.books[i].book.author + ', ' + data.books[i].book.publisher));
x.appendChild(z);
var a = document.createElement('img');
a.src = data.books[i].book.cover;
x.appendChild(a);
var b = document.createElement('p');
b.appendChild(document.createTextNode(data.books[i].book.blurb));
x.appendChild(b);
document.getElementById('DivIdWhereChangeWillShown').appendChild(x);
}
}