Pages

Showing posts with label Php. Show all posts
Showing posts with label Php. Show all posts

Friday, 23 August 2013

Insert, Edit and Delete operations in PHP

In this article we will learn how to insert, edit, update and delete records from the database using PHP. Here we have to create five pages such as config.php (to provide the connection), view.php (to display the records from the database), insert.php (to insert records into the database), edit.php (to edit records), and delete.php (to delete records).

Table Structure



SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `Sample`
--

-- --------------------------------------------------------

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
`id` int(12) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `address`, `city`) VALUES
(1, 'Raj', '10 street dane', 'Pune'),
(2, 'Ravi', '12907A 53 St NW', 'Mumbai'),
(3, 'Rahul', '3rd Floor, 888 Fort Street', 'Noida'),
(4, 'Harry', 'Sir Frederick W Haultain Building 9811 109 ST NW', 'London'),
(5, 'Ian', 'Suite 303, 13220 St. Albert Trail', 'Sydney'),
(6, 'Shaun', '9700 Jasper Avenue', 'Perth');

Code part

Config.php

<?php

/* Database Connection */

$sDbHost = 'localhost';
$sDbName = 'Sample';
$sDbUser = 'root';
$sDbPwd = '';

$dbConn = mysql_connect ($sDbHost, $sDbUser, $sDbPwd) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($sDbName,$dbConn) or die('Cannot select database. ' . mysql_error());

?>
View.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php

include('config.php');

$result = mysql_query("SELECT * FROM employee")
or die(mysql_error());

echo "<table border='1' cellpadding='10'>";
echo "<tr>
<th><font color='Red'>Id</font></th>
<th><font color='Red'>Name</font></th>
<th><font color='Red'>Address</font></th>
<th><font color='Red'>City</font></th>
<th><font color='Red'>Edit</font></th>
<th><font color='Red'>Delete</font></th>
</tr>";

while($row = mysql_fetch_array( $result ))
{

echo "<tr>";
echo '<td><b><font color="#663300">' . $row['id'] . '</font></b></td>';
echo '<td><b><font color="#663300">' . $row['name'] . '</font></b></td>';
echo '<td><b><font color="#663300">' . $row['address'] . '</font></b></td>';
echo '<td><b><font color="#663300">' . $row['city'] . '</font></b></td>';
echo '<td><b><font color="#663300"><a href="edit.php?id=' . $row['id'] . '">Edit</a></font></b></td>';
echo '<td><b><font color="#663300"><a href="delete.php?id=' . $row['id'] . '">Delete</a></font></b></td>';
echo "</tr>";

}

echo "</table>";
?>
<p><a href="insert.php">Insert new record</a></p>
</body>
</html>
Insert.php

<?php
function valid($name, $address,$city, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Insert Records</title>
</head>
<body>
<?php

if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>

<form action="" method="post">
<table border="1">
<tr>
<td colspan="2"><b><font color='Red'>Insert Records </font></b></td>
</tr>
<tr>
<td width="179"><b><font color='#663300'>Name<em>*</em></font></b></td>
<td><label>
<input type="text" name="name" value="<?php echo $name; ?>" />
</label></td>
</tr>

<tr>
<td width="179"><b><font color='#663300'>Address<em>*</em></font></b></td>
<td><label>
<input type="text" name="address" value="<?php echo $address; ?>" />
</label></td>
</tr>

<tr>
<td width="179"><b><font color='#663300'>City<em>*</em></font></b></td>
<td><label>
<input type="text" name="city" value="<?php echo $city; ?>" />
</label></td>
</tr>

<tr align="Right">
<td colspan="2"><label>
<input type="submit" name="submit" value="Insert Records">
</label></td>
</tr>
</table>
</form>
</body>
</html>
<?php
}

include('config.php');

if (isset($_POST['submit']))
{

$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$address = mysql_real_escape_string(htmlspecialchars($_POST['address']));
$city = mysql_real_escape_string(htmlspecialchars($_POST['city']));

if ($name == '' || $address == '' || $city == '')
{

$error = 'Please enter the details!';

valid($name, $address, $city,$error);
}
else
{

mysql_query("INSERT employee SET name='$name', address='$address', city='$city'")
or die(mysql_error());

header("Location: view.php");
}
}
else
{
valid('','','','');
}
?>
Edit.php

<?php
function valid($id, $name, $address,$city, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Records</title>
</head>
<body>
<?php

if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>

<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>

<table border="1">
<tr>
<td colspan="2"><b><font color='Red'>Edit Records </font></b></td>
</tr>
<tr>
<td width="179"><b><font color='#663300'>Name<em>*</em></font></b></td>
<td><label>
<input type="text" name="name" value="<?php echo $name; ?>" />
</label></td>
</tr>

<tr>
<td width="179"><b><font color='#663300'>Address<em>*</em></font></b></td>
<td><label>
<input type="text" name="address" value="<?php echo $address; ?>" />
</label></td>
</tr>

<tr>
<td width="179"><b><font color='#663300'>City<em>*</em></font></b></td>
<td><label>
<input type="text" name="city" value="<?php echo $city; ?>" />
</label></td>
</tr>

<tr align="Right">
<td colspan="2"><label>
<input type="submit" name="submit" value="Edit Records">
</label></td>
</tr>
</table>
</form>
</body>
</html>
<?php
}

include('config.php');

if (isset($_POST['submit']))
{

if (is_numeric($_POST['id']))
{

$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$address = mysql_real_escape_string(htmlspecialchars($_POST['address']));
$city = mysql_real_escape_string(htmlspecialchars($_POST['city']));


if ($name == '' || $address == '' || $city == '')
{

$error = 'ERROR: Please fill in all required fields!';


valid($id, $name, $address,$city, $error);
}
else
{

mysql_query("UPDATE employee SET name='$name', address='$address' ,city='$city' WHERE id='$id'")
or die(mysql_error());

header("Location: view.php");
}
}
else
{

echo 'Error!';
}
}
else

{

if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{

$id = $_GET['id'];
$result = mysql_query("SELECT * FROM employee WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);

if($row)
{

$name = $row['name'];
$address = $row['address'];
$city = $row['city'];

valid($id, $name, $address,$city,'');
}
else
{
echo "No results!";
}
}
else

{
echo 'Error!';
}
}
?>
Delete.php

<?php
include('config.php');

if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];

$result = mysql_query("DELETE FROM employee WHERE id=$id")
or die(mysql_error());

header("Location: view.php");
}
else

{
header("Location: view.php");
}
?>


Output







After inserting 6 records






After editing the address of Name (Raj)

Thursday, 22 August 2013

Connecting Nav Web Services from PHP Part - 3

Previously we have discussed Part - 1 and Part - 2, here I will discussed how to Invoke the Codeunit methods.

<?php

try
{
            require_once("NTLMStream.php");
           
            require_once("NTLMSoapClient.php");
           
            stream_wrapper_unregister('http');
           
            stream_wrapper_register('http', 'NTLMStream') or die("Failed to register protocol");
                     
         
            $pageURL = 'http://localhost:7047/dynamicsnav/ws/Test%20Products/Codeunit/acceptwebcustomerdetail';
            echo "<br>URL of Customer page: $pageURL<br><br>";
           
            // Initialize Page Soap Client
            $page = new NTLMSoapClient($pageURL);
            $page->fuck_you_ms = TRUE;
           
          
            //echo '<pre>acceptwebcustomerdetail class functions</pre>';
           
            //$functions =$page->__getFunctions();
           
            //var_dump($functions);
           
            echo '<pre></pre>';
            $accept=array('SecurityTokenID'=> '*786','MemberID'=>'12885','CustomerName'=>'TestUser','EmailAddress'=>'test@gmail.com','ReponsibilityCenter'=>'BIND',
                            'Website'=>'http://testcompany.com','GroupID'=>'8','Group'=>'General','CreatedIn'=>'Admin');
            $acceptp=array('acceptcustomer'=>$accept);       
                       
            $outsec='';
            $status='';
            $errorcode='';
           
            $params=array('acceptwebcustomerp'=>$acceptp,'outsecuritytokenidp'=>$outsec,'statusp'=>$status,'errorcodep'=>$errorcode);
           
           
            $Cre = $page->Addorupdatecustomer($params);
           
            echo '<br/>';
           
            echo 'Create Order successfully <br/>';

           

// restore the original http protocole
stream_wrapper_restore('http');

}
catch(Exception $ex){
    echo 'Soap Exception<br/>';
    echo $ex->getMessage();
}

?>


Friday, 9 August 2013

Connecting to NAV Web Services from PHP Part - 2


Prerequisites

Please read this post to get an explanation on how to modify the service tier to use NTLM authentication and for a brief explanation of the scenario I will implement in PHP.
BTW. Basic knowledge about PHP is required to understand the following post:-)

Version and download

In my sample I am using PHP version 5.3, which I downloaded from http://www.php.net, but it should work with any version after that.
In order to make this work you need to make sure that SOAP and CURL extensions are installed and enabled in php.ini.
PHP does not natively have support for NTLM nor SPNEGO authentication protocols, so we need to implement that manually. Now that sounds like something, which isn’t straightforward and something that takes an expert.   Fortunately there are a lot of these experts on the internet and I found this post (written by Thomas Rabaix), which explains about how what’s going on, how and why. Note that this implements NTLM authentication and you will have to change the Web Services listener to use that.


<?php
class NTLMStream
{
    private $path;
    private $mode;
    private $options;
    private $opened_path;
    private $buffer;
    private $pos;
    /**
     * Open the stream
      *
     * @param unknown_type $path
     * @param unknown_type $mode
     * @param unknown_type $options
     * @param unknown_type $opened_path
     * @return unknown
     */
    public function stream_open($path, $mode, $options, $opened_path) {
        $this->path = $path;
        $this->mode = $mode;
        $this->options = $options;
        $this->opened_path = $opened_path;
        $this->createBuffer($path);
        return true;
    }
    /**
     * Close the stream
     *
     */
    public function stream_close() {
        curl_close($this->ch);
    }
    /**
     * Read the stream
     *
     * @param int $count number of bytes to read
     * @return content from pos to count
     */
    public function stream_read($count) {
        if(strlen($this->buffer) == 0) {
            return false;
        }
        $read = substr($this->buffer,$this->pos, $count);
        $this->pos += $count;
        return $read;
    }
    /**
     * write the stream
     *
     * @param int $count number of bytes to read
     * @return content from pos to count
     */
    public function stream_write($data) {
        if(strlen($this->buffer) == 0) {
            return false;
        }
        return true;
    }
    /**
     *
     * @return true if eof else false
     */
    public function stream_eof() {
        return ($this->pos > strlen($this->buffer));
    }
    /**
     * @return int the position of the current read pointer
     */
    public function stream_tell() {
        return $this->pos;
    }
    /**
     * Flush stream data
     */
    public function stream_flush() {
        $this->buffer = null;
        $this->pos = null;
    }
    /**
     * Stat the file, return only the size of the buffer
     *
     * @return array stat information
     */
    public function stream_stat() {
        $this->createBuffer($this->path);
        $stat = array(
            'size' => strlen($this->buffer),
        );
        return $stat;
    }
    /**
     * Stat the url, return only the size of the buffer
     *
     * @return array stat information
     */
    public function url_stat($path, $flags) {
        $this->createBuffer($path);
        $stat = array(
            'size' => strlen($this->buffer),
        );
        return $stat;
    }
    /**
     * Create the buffer by requesting the url through cURL
     *
     * @param unknown_type $path
     */
    private function createBuffer($path) {
        if($this->buffer) {
            return;
        }
        $this->ch = curl_init($path);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
        curl_setopt($this->ch, CURLOPT_USERPWD, USERPWD);
        $this->buffer = curl_exec($this->ch);
        $this->pos = 0;
    }
}


class NTLMSoapClient extends SoapClient {

    public $fuck_you_ms = FALSE; // very important variable -> indicates if we are going to process request "before" sending (all thanks to MS SOAP implementation - hence the name)

    //function __doRequest($request, $location, $action, $version) {
    function __doRequest($request, $location, $action, $version, $one_way = 0) {
        $headers = array(
            'Method: POST',
            'Connection: Keep-Alive',
            //'User-Agent: PHP-SOAP-CURL',
            'Content-Type: text/xml; charset=UTF-8',
            'SOAPAction: "'.$action.'"',
        );

        if($this->fuck_you_ms) {
            // some fancy processing before passing stuff to ms
            $request = fix_ms_xml($request);
            //echo "\n<hr><pre>\n".htmlspecialchars( str_replace("<Item>","\n\t<Item>",$request) )."\n</pre><hr>\n";
        }
           
        $request = str_replace(array("\n","\r","\t"),"",$request); // clean XML before sending
       
        $this->__last_request_headers = $headers;
        $ch = curl_init($location);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
        curl_setopt($ch, CURLOPT_USERPWD, USERPWD);
        $response = curl_exec($ch);
        //echo "\n<hr>response:".$response."\n";
        return $response;
    }

    function __getLastRequestHeaders() {
        return implode("\n", $this->__last_request_headers)."\n";
    }
}


function fix_ms_xml($request,$level=1){
    $out='';
   
    $dom = new DOMDocument();
    $dom->loadXML($request, LIBXML_NOBLANKS);
    $envelopes = $dom->getElementsByTagName('Envelope');
    foreach($envelopes as $envelope){ // i know we have only one attr...
        //echo '<hr>GOT ENVELOPE:';
        if($envelope->hasAttribute("xmlns:ns1")){
//            echo '<hr> - YAAHAH WE HAVE ATTR';
            $attr1 = (String)$envelope->getAttribute("xmlns:ns1");
            ///$attr2 = (String)$envelope->getAttribute("xmlns:ns2");
            //var_dump($envelope->getAttribute("xmlns:ns1"));
           
            $envelope->removeAttributeNS($attr1,"ns1");
            //$envelope->removeAttributeNS($attr2,"ns2");
           
//            $envelope->setAttributeNS('urn:microsoft-dynamics-schemas/codeunit/Drupal_OrderImport',"drup");
/*
            echo "<hr>--[";
            var_dump($envelope->removeAttributeNS($attr1,"ns1"));
            echo "]--<hr>";
*/
            //var_dump($envelope->removeAttributeNS($attr2,"ns2"));
            //$envelope->setAttribute("xmlns:ns1",111);
        }

    }

/*      $node_list = $dom->getElementsByTagName('Body');
    $node = $node_list->item(0)->childNodes->item(0);
    $node->setAttribute('xmlns:ns1',$attr2);
   
    $node = $node_list->item(0)->childNodes->item(0);
    $node->setAttribute('xmlns:ns2',$attr1);     */
   
/*   
    $node_list = $dom->getElementsByTagName('Address');
    $node = $node_list->item(0);
    echo "ADDR:".$node->nodeValue;
*/
    //$attr1=$envelope->getAttribute('ns1');
   
   

   
    return $dom->saveXML();
    //return $dom->C14N(true, false);
}

?>
Putting this into the PHP script now allows you to connect to NAV Web Services system service in PHP and output the companies available on the service tier:
<?php

require('nav_soap_client.php'); // or... die it's not gonna work without it anyway

class commerce_nav_crons{

    function __construct() {
        $this->service_url_main = 'http://localhost:7047/dynamicsnav/ws'; // just a sample - i read it from db
        // we unregister the current HTTP wrapper
        stream_wrapper_unregister('http');
        // we register the new HTTP wrapper
        stream_wrapper_register('http', 'NTLMStream') or die("Failed to register protocol");
        define('USERPWD', 'testdomain\testuser:testpassword'); // put your own values - mine are actually taken from db
    }

    function __destruct() {
        // restore the original http protocole
        stream_wrapper_restore('http');
    }

    /**
     *
     * this is a main run function to send Order Returns to NAV, very basic, just to illustrate sample
     *
     * @return bool
     */
    function sample_run(){
        $ret  = FALSE;
        $service_url = $this->service_url_main . '/Test%20Products/Company';
        $service_params = array(
            'trace' => TRUE,
            'cache_wsdl' => WSDL_CACHE_NONE,
        );
       
        //echo $service_url . '<br/>';
       
        $service = new NTLMSoapClient($service_url, $service_params);
        $service->fuck_you_ms = TRUE; // because fuck you, that's why!

       
// Find the first Company in the Companies
            $result = $client->Companies();
            $companies = $result->return_value;
            echo "Companies:<br>";
            if (is_array($companies)) {
              foreach($companies as $company) {
                echo "$company<br>";
              }
              $cur = $companies[4];
            }
            else {
              echo "$companies<br>";
              $cur = $companies;
            }
       

        return $
cur ;
    }

}


$cl = new commerce_nav_crons();
$cl->sample_run();









Next part -3 I will explain how to connect the CodeUnit services..

Note:
Here I collecting the information from Freedy and Arte blogs. They are explain the two different ways here I explain the both scenarios.

always welcome any queries and comments....

Connecting to NAV Web Services from PHP part - 1



Here I will explain how to connect to NAV Web Services from php languages/platform. 


Scenario

For all these I will create some code that:
  • Connects to NAV Web Services System Service and enumerates the companies in the database
  • Constructs a URL to the Customer Page (based on the first company in the list)
  • Get the name of Customer number 10000
  • Get the Customers in GB that have Location Code set to RED or BLUE.
  • And Constructs a URL to the Codeunit methods.
Here is an example of the output of the PHP web site:

Note, that the code is not necessarily perfect PHP code and the intention is not to teach people how to code in these language to overcome some of the obstacles when trying to work with NAV.


Authentication

The very first obstacle is authentication. As you probably know, NAV 2009 only supported SPNEGO (Negotiate) authentication and PHP doesn’t currently have any support natively for that.
In NAV 2009 SP1 we added a key in the Service Tier configuration file called WebServicesUseNTLMAuthentication. If you set this key to true the Web Services listener will only use NTLM authentication and as such be easier accessible from other systems.
The config file you need to modify is placed in the directory where the Service Tier executable is and is called CustomSettings.config. The section you are looking for is:
    <!--
  Turns on or off NTLM authentication protocol for Web Services
      false: Use SPNEGO (recommended)
      true: Use NTLM only
  -->
    <add key="WebServicesUseNTLMAuthentication" value="true"></add>

Note that .net works with both values of this settings.



Note:
Here I collecting the information from Freedy and Arte blogs. They are explain the two different ways here I explain the both scenarios.

any queries welcomes you...

Monday, 5 August 2013

Creating and Invoking Web Service using nusoap in PHP

              
Today I am writing my web service using SOAP. If you are wondering “How to create SOAP service?” , Then solution is here. Here I have created web service. All you need to do is, you just have to call service and function to perform particular task.
So let’s follow steps to do this stuffs,

Step 1 : Download nusoap zip file from here.  And paste it inside your www folder if you are using wamp, for xampp user paste it inside htdocs/xampp folder.
Step 2:  create two file call server.php and client.php.
Step 3 :  Inside server.php write below lines of code.
 
<?php

    function MyFunction()
    {
        $temparray = array();
        mysql_connect('localhost','root','') or die(mysql_errno());
        mysql_select_db('Sample') or die(mysql_errno());
        $myquery = 'SELECT * FROM books';
        $result = mysql_query($myquery) ;
        if(!$result)
        {
            $temparray[] = array('Error' =>'Database Error');
            return $temparray;
        }
        else{
           
            while($row = mysql_fetch_assoc($result)){
                $temparray[] = array('BookId' => $row['BookId'], 'BookTitle' => $row['Title'],'BookAuthor' => $row['Author'],'BookPublisherName' => $row['PublisherName'],'BookCopyrightYear' => $row['CopyrightYear']);
        }
    }
        return $temparray;
    }
     
/////////////////////////////////////////////////////////////////////////////////////   

  require_once("nuSOAP/lib/nusoap.php");
    $namespace = "http://localhost/api/tstserver.php";
    // create a new soap server
    $server = new soap_server();
    $server->configureWSDL("WSDLTST");
    $server->soap_defencoding = 'UTF-8';
    $server->wsdl->schemaTargetNamespace = $namespace;
       
$server->wsdl->addComplexType(
    'Book',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'BookId' => array('name'=>'BookId','type'=>'xsd:int'),
        'BookTitle' => array('name'=>'Title','type'=>'xsd:string'),
        'BookAuthor' => array('name'=>'Author','type'=>'xsd:string'),
        'BookPublisherName' => array('name'=>'PublisherName','type'=>'xsd:string'),
        'BookCopyrightYear' => array('name'=>'CopyrightYear','type'=>'xsd:string')
    )
);
$server->wsdl->addComplexType(
    'BookArray',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
        array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:Book[]')
    ),
    'tns:Book'
);
      
    $server->register(
           'MyFunction',
           array(),
           array('return'=>'tns:BookArray'),
           $namespace,false,'rpc','encoded','ClassDescription');
          
   $server->service(isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '');
   exit();
?>
 That’s it you have created your server file to access and fetch details from database.
Step 4:    Now create client.php and inside it just  write below code. Create client object and call your server function to retrieve details.
<html>
<head>
<title>Invoking Web Services in PHP</title>
</head>
<body>

<?php

 require_once('nuSOAP/lib/nusoap.php');
    $client = new soapclient('http://localhost/final/server.php?wsdl');
   
    $result = $client->MyFunction(); 
    var_dump($result);
    }
   
?>
</body>
</html>
Finally we have a result as given below.



 

Wednesday, 10 July 2013

Difference between heredoc and nowdoc

Introduction

In this article I will explain the difference between Heredoc and Nowdoc in PHP. Heredoc and Nowdoc are two methods for defining a string. A third and fourth way to delimit strings are the Heredoc and Nowdoc; Heredoc processes $variable and special character but Nowdoc does not processes a variable and special characters. First of all I will discuss Heredoc.

Heredoc allows a multi-line string to be easily assigned to variables or echoed. Heredoc text behaves just like a string without the double quotes.

Example

The following is a simple example of Heredoc:

<?php
class ABC
{
    public $ABC;
    public $bar;
    function ABC()
    {
        $this->ABC = 'ABC';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}
$ABC = new ABC();
$name = 'Tom';
echo <<<EOT
My name is "$name". I am printing some $ABC->ABC.
Now, I am printing some {$ABC->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>

OutPut:


Next, I will discuss Nowdoc. Nowdoc is an identifier with a single quote string and Nowdoc is specified similarly to a Heredoc but no parsing is done inside a Nowdoc. A Nowdoc is identified with the same "<<<" sequence used for heredoc. When you use Nowdoc then you cannot pass the space character.

Note Nowdoc is supported only PHP 5.3

Example
<?php
class ABC
{
    public $ABC;
    public $bar;
    function ABC()
    {
        $this->ABC = 'ABC';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}
$ABC = new ABC();
$name = 'Tom';
echo <<<'EOT'
My name is "$name". I am printing some $ABC->ABC.
Now, I am printing some {$ABC->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>
OutPut:




 

Tuesday, 9 July 2013

Access/Invoking Asp.Net WebService from Php Client


Creating and consuming webservices in asp.net is an easy task with the help of Visual Studio. Although most of the scenarios I worked with were always with asp.net applications consuming asp.net web services, which makes things even easier. This week however I learned something new when I had to invoke a PHP client application to connect to my asp.net webservices.

Asp.Net Web Service

/// <summary>
/// Summary description for WebService1/// </summary>[WebService(Namespace = "http://tempuri.org/")][
WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.ComponentModel.
ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService]public class WebService1 : System.Web.Services.WebService{
[
WebMethod]
public string HelloWorld(string StrValue){

return StrValue;}
}

And I host this web service in my localhost using IIS, and when I ping this url in explorer I have wsdl like this.

<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://tempuri.org/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <wsdl:types>
    <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
      <s:element name="HelloWorld">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="0" maxOccurs="1" name="StrValue" type="s:string" />
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="HelloWorldResponse">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="0" maxOccurs="1" name="HelloWorldResult" type="s:string" />
          </s:sequence>
        </s:complexType>
      </s:element>
    </s:schema>
  </wsdl:types>
  <wsdl:message name="HelloWorldSoapIn">
    <wsdl:part name="parameters" element="tns:HelloWorld" />
  </wsdl:message>
  <wsdl:message name="HelloWorldSoapOut">
    <wsdl:part name="parameters" element="tns:HelloWorldResponse" />
  </wsdl:message>
 
  <wsdl:portType name="WebService1Soap">
    <wsdl:operation name="HelloWorld">
      <wsdl:input message="tns:HelloWorldSoapIn" />
      <wsdl:output message="tns:HelloWorldSoapOut" />
    </wsdl:operation>
  
  </wsdl:portType>
  <wsdl:binding name="WebService1Soap" type="tns:WebService1Soap">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="HelloWorld">
      <soap:operation soapAction="http://tempuri.org/HelloWorld" style="document" />
      <wsdl:input>
        <soap:body use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal" />
      </wsdl:output>
    </wsdl:operation>
   
  </wsdl:binding>
  <wsdl:binding name="WebService1Soap12" type="tns:WebService1Soap">
    <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="HelloWorld">
      <soap12:operation soapAction="http://tempuri.org/HelloWorld" style="document" />
      <wsdl:input>
        <soap12:body use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap12:body use="literal" />
      </wsdl:output>
    </wsdl:operation>   
  </wsdl:binding>
  <wsdl:service name="WebService1">
    <wsdl:port name="WebService1Soap" binding="tns:WebService1Soap">
      <soap:address location="http://localhost:7777/WebService1.asmx" />
    </wsdl:port>
    <wsdl:port name="WebService1Soap12" binding="tns:WebService1Soap12">
      <soap12:address location="http://localhost:7777/WebService1.asmx" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

As you can see there’s nothing to it.

The PHP code is not much harder once you know, First you have to have test the requested url is working or not which has the webservices infrastructure for PHP. Then you code a simple client to access our service.

<?php
$client = new SoapClient("http://localhost:7777/WebService1.asmx?wsdl");
$strRestult = $client->HelloWorld(array('StrValue' => 'ICS'))->HelloWorldResult;
echo "Welcome to " . $strRestult;

?>

Then run this have get a result from .Net WebService.





Friday, 5 July 2013

Php Installation

Necessary Setup:


           To begin working with PHP you must first have access to either of the following:

  • A web hosting account that supports the use of PHP web pages and grants you access to MySQL databases. If you do not have a host, but are interested in signing up for one, we recommend that you first read our Web Host Guide to educate yourself about web hosting and avoid getting ripped off.
  • Have PHP and MySQL installed on your own computer. Read this lesson thorougly for more information on installing PHP.
Although MySQL is not absolutely necessary to use PHP, MySQL and PHP are wonderful complements to one another and some topics covered in this tutorial will require that you have MySQL access.

Installing Php:

For those who are experienced enough to do this yourself, simply head over to PHP.net - Downloads and download the most recent version of PHP.
However, if you are like most of us, you will most likely want to follow a guide to installing PHP onto your computer. These guides are kindly provided by PHP.net based on the operating system that you are using.
Installing MySQL:

As we mentioned before, MySQL is not a requirement to use PHP, however they often go hand in hand.
Visit MySQL's MySQL Installation Guide for help on installing MySQL.

Installation troubles:

If you have any installation troubles feel free to ask.

Content Management System

What is CMS?

        CMS  means Content Management System . CMS  is easily  to  use  and maintains and powerful features set allows you to quickly and easily create and manage an entire website.CMS is a web application you run on your web server to help facilitate creating a website.


           CMS Made Simple is an open source ( GPL) package.PHP Content Management System is  allows creation, editing, publishing, organizing and managing of content of a website.For a small website, adding and deleting a page manually is simple.CMS is easy way the process of adding and modifying new content to a webpage.

           PHP content management system which allows publishing and editing and deleting  content as well as site management from an easy-to-use administration page.In PHP CMS is a SEO optimized, professional grade content management system .

Examples of MOST USED CMS IN PHP

1)Wordpress:

          WordPress is a free and open source blogging tool and a content management system (CMS) based on PHP and MySQL. It has many features including a plug-in architecture and a template system

FOUNDER: Matthew Charles Mullenweg

2)Drupal:

            Drupal is a free software package that allows you to easily organize, manage and publish your content, with an endless variety of customization.

FOUNDER: Dries Buytaert   

3)Joomla:
               
           Joomla is an award-winning content management system (CMS), which enables you to build Web sites and powerful online applications.

FOUNDER:   Joomla Leadership Team 

E-Commerce Best CMS

1)Magento:

            
            Magento is a feature-rich eCommerce platform built on open-source technology that provides online merchants with unprecedented flexibility and control over the look, content and functionality of their eCommerce store.

FOUNDER:IT was launched on March 31, 2008. It was developed by Varien (now Magento Inc).


Feel free to ask if you have any suggessions or questions?
 


Php Tutorial

Php Tutorial

            PHP is the widely-used  Server side Scripting Language and it is free Software to download and use. PHP is perfectly suited for Web development and can be embedded directly into the HTML code.you have to learn php in this php tutorial small php example and small php programming  code is  available.
Start learning PHP now!



What is Php?

              Taken directly from PHP's home, PHP.net, "PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly."

              This is generally a good definition of PHP. However, it does contain a lot of terms you may not be used to. Another way to think of PHP is a powerful, behind the scenes scripting language that your visitors won't see!When someone visits your PHP webpage, your web server processes the PHP code. It then sees which parts it needs to show to visitors(content and pictures) and hides the other stuff(file operations, math calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the webpage to your visitor's web browser.

What's it do!

It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to:
  • Reduce the time to create large websites.
  • Create a customized user experience for visitors based on information that you have gathered from them.
  • Open up thousands of possibilities for online tools. Check out PHP - HotScripts for examples of the great things that are possible with PHP.
  • Allow creation of shopping carts for e-commerce websites.
What you should know?

Before starting this tutorial it is important that you have a basic understanding and experience in the following:
  • HTML - Know the syntax and especially HTML Forms.
  • Basic programming knowledge - This isn't required, but if you have any traditional programming experience it will make learning PHP a great deal easier
Tutorial Overview

              This tutorial is aimed at the PHP novice and will teach you PHP from the ground up. If you want a drive-through PHP tutorial this probably is not the right tutorial for you.

              Remember, you should not try to plow through this tutorial in one sitting. Read a couple lessons, take a break, then do some more after the information has had some time to sink in.