How to use SOAP client in PHP

This tutorial will helps you to understand the way of invoking SOAP Web Service from PHP SOAP Client.

Before Start using PHP Soap client, You need to verify that Whether SOAP Client is enabled in your PHP Web Server. To verify that create new php file with the following code.

[php]
<?php
phpinfo();
?>
[/php]

Now run it, You will get the list of configuration details of your PHP server. In that verify whether SOAP section available and SOAP client is enabled. If SOAP section is enabled in your PHP server, its look like this.

PHP SOAP Client

PHP SOAP Client

If SOAP client is enabled you can proceed the steps further, Else you need to enable the PHP SOAP client in your PHP Web Server.

Note: If you are using Shared hosting and you will not be able to enable / change the PHP Server configurations. So you can use another alternative PHP SOAP client is nusoap.

Steps to invoke on SOAP Web Service in PHP:

To invoke SOAP Web Service, you need to aware about the following items:

1) WSDL/WADL location of your Web Service to invoke from PHP.

2) Actions available in the respective Web Service.

3) Parameters are required to invoke Web Service with the respective actions in it.

4) Optional, If its have any header information like authentication / namespace of Web Service.

Simple Web Service Method:

[php]

$soapClient = new SoapClient("https://test.soapws.com/globalweather.php?wsdl");
<pre>// Setup the parameters of the action
$requestParams = array(
    ‘CityName’ => ‘Chennai’,
    ‘CountryName’ => ‘India’
);

// Call Soap action
$soapResponse = $soapClient->GetWeather($requestParams);</pre>

// Soap Response
print_r($soapResponse);

[/php]

As the result of invoking the Web Service, you will get response as stdClass Object. Now you can easily iterate the result-sets and display it however you like.

Headers with Web Service Method:

[php]

$soapClient = new SoapClient("https://test.soapws.com/globalweather.php?wsdl");

// Setup SoapHeader parameters
$headerParams = array(
            ‘Username’    =>    ‘username’,
            ‘Password’    =>    ‘password’);
$soapHeaders = new SoapHeader(‘https://test.soapws.com/weather’, ‘UserCredentials’, $headerpParams);

// Prepare Soap Client with headers
$soapClient->__setSoapHeaders(array($soapHeaders));

// Setup the parameters of the action
$requestParams = array(
    ‘CityName’ => ‘Chennai’,
    ‘CountryName’ => ‘India’
);

// Call Soap action
$soapResponse = $soapClient->GetWeather($requestParams);

// Soap Response
print_r($soapResponse);

[/php]

As the result of invoking Web Service, you will get the response from the Web Service as stdClass Object.

To verify the SOAP Client response you can use SOAPUI tool.

Permanent link to this article: https://blog.openshell.in/2014/06/how-to-use-soap-client-in-php/

How to use Jsonp method in JQuery

JSONP is JQuery(JavaScript) method used to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on<script> tags. JSONP is a viable solution for cross-domain Ajax.

JSONP does not work with JSON – formatted results. JSONP to work, Server must reply with JSONP – formatted results. JSONP requires to wrap the JSON response into a JavaScript function call. When you do the JSONP request the query string will set a parameter called ‘callback’ that will tell the server how to wrap the JSON response.

How it works:
JQuery script:

[js]
$.ajax({
dataType: ‘jsonp’,
data: ‘catid=10’,
url: ‘http://remote-domain.com/getdata’,
success: function () {
// do stuff
},
});

[/js]

PHP Code:
The Server Request will need to return the response as JSON with the requested call back.

[php]
$response = json_encode(getPostsAsArray($_GET[‘catid’]));
echo $_GET[‘callback’] . ‘(‘ . $response . ‘);’;
[/php]

Result:
[code]
callback([
{"id": "1", "title": "Post title 1"},
{"id": "2", "title": "Post title 2"},
{"id": "3", "title": "Post title 3"}
]);
[/code]

Permanent link to this article: https://blog.openshell.in/2014/06/how-to-use-jsonp-method-in-jquery/

Mysql Query Cache

As we know, speed is always the most important element in developing a website especially for those high traffic database driven website. You can try to turn on query cache to speed up query.

To speed up query, enable the MySQL query cache, before that you need to set few variables in mysql configuration file (usually is my.cnf or my.ini)

 

– 1st, set query_cache_type to 1. (There are 3 possible settings: 0 (disable / off), 1 (enable / on) and 2 (on demand).

query-cache-type = 1

– 2nd, set query_cache_size to your expected size. I’d prefer to set it at 20MB.

query-cache-size = 20M

To check if your mysql server already enable query cache, simply run this query:-

SHOW VARIABLES LIKE ‘%query_cache%’;

You will see this result:-

+——————-+———+
| Variable_name | Value |
+——————-+———+
| have_query_cache | YES |
| query_cache_limit | 1048576 |
| query_cache_size | 20971520 |
| query_cache_type | ON |
+——————-+———+
4 rows in set (0.06 sec)

To check if your MySQL query cache is working, simply perform a sql query for 2 times and check the query cache variable like below:-

SHOW STATUS LIKE ‘%qcache%’;

+————————-+———-+
| Variable_name | Value |
+————————-+———-+
| Qcache_queries_in_cache | 1 |
| Qcache_inserts | 3 |
| Qcache_hits | 0 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 2 |
| Qcache_free_memory | 20947592 |
| Qcache_free_blocks | 1 |
| Qcache_total_blocks | 4 |
+————————-+———-+

For the first time you execute your SQL query, the time it should take take be longer compare to the second time query. This is due to the MySQL query cache is working!

Permanent link to this article: https://blog.openshell.in/2014/06/mysql-query-cache/

How to declare dependencies and use composer in php

Using Composer:

We will now use Composer to install the dependencies of the project. To use Composer in your project, you’ll need one file: composer.json. In this file you will describe the dependencies of your project. So let’s create the file:

[code]vim composer.json[/code]

Declaring Dependencies:

Once you created a composer.json file within your project which describes the project’s dependencies.

[code]
{
"require": {
"package-name 1": "version",
"package-name 2": "version"
}
}
[/code]

Installing Dependencies:

Once you updated your composer.json file with required packages, now you are able to install the mentioned packages.

To resolve and download dependencies, run the install command:

[code]$ php composer.phar install[/code]

If you did a global install and do not have the phar in that directory run this instead:

[code]$ composer install[/code]

Upgrade the dependent libraries to newer versions, you can run the following command:

[code]$ php composer.phar update[/code]

[code]$ composer update[/code]

Autoloading – Include packages into your project:

Another cool thing about Composer is its autoloading feature. For those libraries that provide autoloading information, Composer automatically generates an autoload.php file directly in the vendor folder that you can include in your project. Then you can directly start using the classes from those libraries. In your PHP project, you can just specify this:

[code]require ‘vendor/autoload.php’;[/code]

For more information: visit https://getcomposer.org.

Permanent link to this article: https://blog.openshell.in/2014/05/how-to-declare-dependencies-and-use-composer-in-php/

How To Install and Use Composer on Ubuntu

Introduction

Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

Dependency management

Composer is not a package manager. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

This idea is not new and Composer is strongly inspired by node’s npm and ruby’s bundler. But there has not been such a tool for PHP.

The problem that Composer solves is this:

a) You have a project that depends on a number of libraries.

b) Some of those libraries depend on other libraries.

c) You declare the things you depend on.

d) Composer finds out which versions of which packages need to be installed, and installs them (meaning it downloads them into your project).

prerequisites:

1) PHP 5.3.2+

2) Curl

Installation:

[code]
$ curl -s http://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin/composer.phar
[/code]

If you want, you can create an alias:

[code]
$ alias composer=’/usr/local/bin/composer.phar’
[/code]

This way you can invoke composer with just composer, else you need to invoke by composer.phar

Permanent link to this article: https://blog.openshell.in/2014/04/how-to-install-and-use-composer-on-ubuntu/

Rails 3 GEM to handling where the error has occurred

It’s Better Errors GEM. It will handle the error and we can see exactly where the error has occurred in development machine.

GITHUB : https://github.com/charliesome/better_errors

Steps to configure in our rails3 application

1.  Install the  gem install airbrake -v ‘3.1.8’

2. In your Gemfile add

group :development do
  gem "better_errors"
end

If you would like to use Better Errors’ advanced features you need to add the binding_of_caller

group :development do
  gem "better_errors"
  gem "binding_of_caller"
end

3. Add in below line at the end config/environments/development.rb
   BetterErrors::Middleware.allow_ip! ENV['TRUSTED_IP'] if ENV['TRUSTED_IP']

4. Thats it!
   TRUSTED_IP=127.0.0.1 rails s

Permanent link to this article: https://blog.openshell.in/2014/03/rails-3-better-errors-gem-handling-where-the-error-has-occurred/

How to download file from remote URL in PHP

There are many ways in PHP to download file from the remote server. We can use php functions like copy, file_get_content, fopen, fsockopen & Curl to download the remote files. For your reference here I have explained about copy, fopen and Curl method, I have choosen these methods based on simplify and easily everyone can understand & use it. We can download large file with minimum memory usages.

Method 1:
[php]
// Copy method
$fullPath = "http://serverurl";
$path_parts = pathinfo($fullPath);
$my_file = urldecode($path_parts['basename']);
if(@copy($fullPath,$my_file))
 echo "Download successful";
else
 echo "Unable to download file";
[/php]
Method 2:
[php]
// Curl method
set_time_limit(0);
$url ="http://serverurl";
$file = basename($url);
// Open file to write
$fp = fopen($file, 'w+');
$ch = curl_init($url);
// increase timeout to download big file
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
echo (filesize($file) > 0)? "Download successful": "Unable to download file";
[/php]



Method 3:
[php]
// File method
$fullPath = "http://serverurl";
$path_parts = pathinfo($fullPath);
$handle = @fopen($fullPath, "r");
$data = "";
while(!feof($handle)) {
 $data .= fread($handle, 2048);
}
fclose ($handle);
$my_file = urldecode($path_parts['basename']);
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $data);
fclose ($handle);
[/php]

Permanent link to this article: https://blog.openshell.in/2014/03/how-to-download-file-from-remote-url-in-php/

Use Number() instead of parseInt() in javascript

Recently I came across the issue in converting string to integer in Javascript(JS). I was used parseInt() method to convert string value into integer value. unfortunately, I was faced issue in chrome browser but all other browsers like firefox, ie and safari are worked fine.

Its too hard time for me to find out the mistake in code, After a long time of struggling with code I came to know the problem with parseInt() method.

In chrome browser

[code]

parseInt(’08’); // return 0

parseInt(’09’); // return 0

[/code]

Because the function tries to determine the correct base for the numerical system used. In Javascript numbers starting with zero are considered octal and there’s no 08 or 09 in octal.

Solution:

Instead of parseInt() method use Number() method, It will solve our problem. It will exactly convert the string value into numeric value.

Permanent link to this article: https://blog.openshell.in/2014/01/use-number-instead-of-parseint-in-javascript/

Accessing external website from PhoneGap application

To create a PhoneGap application, To load external webpage into android application by following the instruction.

Steps:

1) Create phonegap application and configure with android.

2) Then open your activity file and make the changes, onCreate() method is calling super.loadUrl(“http://your-domain.com”); so that http://your-domain.com page is opened in the WebView as soon as application starts

super.loadUrl(“file:///android_asset/www/index.html”); change to super.loadUrl(“http://your-domain.com”);

3) Now it will load external website in android application.

Sample code for your reference:

[java]
import org.apache.cordova.CordovaActivity;
import android.os.Bundle;

public class RssFeed extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("loadUrlTimeoutValue", 70000); // The connection to the server was unsuccessful. URL=http://your-domain.com, 7000 Milliseconds which equals 7 seconds.
super.setStringProperty("loadingDialog", "Loading…"); // Loading screen until the web page load
super.loadUrl("http://your-domain.com");
}
}
[/java]

Permanent link to this article: https://blog.openshell.in/2014/01/accessing-external-website-from-phonegap-application/

Serailization & Unserialization in PHP

Serialization which help us to store or transport PHP data structure such as an array or object. All the storage meduim or database can store String type. It will generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

i.e, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode()  both the concept is similar.

Using Serialize method, We can store multiple field key & its values in single column. You can easily extend your forms without changing table structure.

Permanent link to this article: https://blog.openshell.in/2014/01/serailization-unserialization-in-php/