Wednesday 25 December 2013

post and get method


    GET requests can be cached
    GET requests remain in the browser history
    GET requests can be bookmarked
    GET requests should never be used when dealing with sensitive data
    GET requests have length restrictions
    GET requests should be used only to retrieve data
    since form data is in the URL and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server.
   

    POST supports advanced functionality such as support for multi-part binary input used for file uploads to web servers.
    POST requests are never cached
    POST requests do not remain in the browser history
    POST requests cannot be bookmarked
    POST requests have no restrictions on data length

Tuesday 24 December 2013

array_merge and array_combine

array_merge merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings  key  then the later value overrides the previous value for that key .
<?php
$array1 = array("course1" => "java","course2" => "sql");
$array2 = array(("course1" => "php","course3" => "html");
$result array_merge($array1$array2);
print_r($result);
?>
OUTPUT :  
Array
(
[course1] => php
[course2] => sql
[course3] => html
)
Array_combine creates a new array by using the key of one array as keys and using the value of other array as values.
It returns the combine array of array 1 and array2 .
<?php
$array1    = array("course1","course2","course3");
$array2    = array(("php","html","css");
$new_array array_combine($array1$array2);
print_r($new_array);
?>
OUTPUT :
Array
(
[course1]  => php
[course2]    => html
[course3]    =>css
)

Wednesday 25 September 2013

http and https

What is HTTPS?
HTTPS (Hypertext Transfer Protocol over Secure Socket Layer, or HTTP over SSL) is a web protocol developed by Netscape.
One can say: HTTPS = HTTP + SSL
HTTPS uses Secure Socket Layer (SSL) as a sublayer under its regular HTTP application layering.
Need of HTTPS:
Hypertext Transfer Protocol (HTTP) is a protocol for transmitting and receiving information across the Internet. HTTP serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. You normally use HTTP when you are browsing the web, its not secure, so someone can eavesdrop on the conversation between your computer and the web server. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape corporation to allow authorization and secured transactions.
Similarity between HTTP and HTTPS:
In many ways, https is identical to http, because it follows the same basic protocols. The http or https client, such as a Web browser, establishes a connection to a server on a standard port. When a server receives a request, it returns a status and a message, which may contain the requested information or indicate an error if part of the process malfunctioned. Both systems use the same Uniform Resource Identifier (URI) scheme, so that resources can be universally identified. Use of https in a URI scheme rather than http indicates that an encrypted connection is desired.
Difference between HTTP and HTTPS:
1. URL begins with “http://" in case of HTTP while the URL begins with “https://” in case of HTTPS.
2. HTTP is unsecured while HTTPS is secured.
3. HTTP uses port 80 for communication while HTTPS uses port 443 for communication.
4. HTTP operates at Application Layer while HTTPS operates at Transport Layer.
5. No encryption is there in HTTP while HTTPS uses encryption.
6. No certificates required in HTTP while certificates required in HTTPS.
How HTTPS works?
For HTTPS connection, public key and signed certificates are required for the server.
When using an https connection, the server responds to the initial connection by offering a list of encryption methods it supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both parties exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. In order to host https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Most certificates are verified by a third party so that clients are assured that the key is secure.
In other words, we can say, HTTPS works similar to HTTP but SSL adds some spice in it.
HTTP includes the following actions:
1. The browser opens a TCP connection.
2. The browser sends a HTTP request to the server
3. The server sends a HTTP response to the browser.
4. The TCP connection is closed.
SSL will include the following actions:
1. Authenticate the server to the client.
2. Allow the client and server to select the cryptographic algorithms, or ciphers, that they both support.
3. Optionally authenticate the client to the server.
4. Use public-key encryption techniques to generate shared secrets.
5. Establish an encrypted SSL connection.
6. Once the SSL connection is established the usual transfer of HTTP requests will continue.
Where should https be used?
HTTPS should be used in Banking Websites, Payment Gateway, Shopping Websites, Login Pages, Emails (Gmail offers HTTPS by default in Chrome browser) and Corporate Sector Websites. For example:

Sunday 15 September 2013

Trait

What a Trait Looks Like

A trait is similar to an abstract class which cannot be instantiated on its own (though more often it’s compared to an interface). The PHP documentation defines traits as follows:
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

Saturday 14 September 2013

good php interview question

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)
Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: *Cause:* body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.

Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.

Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...

Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.

Friday 13 September 2013

date formate check

<?php
$format =array('m','d','y');
$strDate = date("m-d-Y");
$ex = "-";
echo isValidDate($strDate,$format,$ex);
function isValidDate($strDate,$format,$ex) {
      $valid = false;
      if(is_array($format) && count($format) == 3 && count(explode($ex,$strDate))==3)
      {
         $date = array_combine($format,explode($ex,$strDate));
         //print_r($date);
         if(intval($date['m']) && intval($date['d']) && intval($date['y'])){
           $m = $date['m']; $d = $date['d']; $y = $date['y'];
            $valid = checkdate($m,$d,$y);
         }
      }
      return $valid;
   }
?>

Friday 30 August 2013

date compare validation

javascript


$(document).ready(function(){
    $("#txtFromDate").datepicker({
        minDate: 0,
        maxDate: "+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });
    $("#txtToDate").datepicker({ 
        minDate: 0,
        maxDate:"+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });  
});
 
 
html
 
 
From: <input type="text" id="txtFromDate" />
To: <input type="text" id="txtToDate" /> 

Monday 26 August 2013

date picker

 <script>
$(function() {
$( "#datepicker").datepicker({
numberOfMonths: 3, showCurrentAtPos: 0,minDate: 0,dateFormat: 'dd-mm-yy', showOn: "button",
buttonImage: "image/cicon.png",
buttonImageOnly: true,
showOn: 'both',
});
});
</script>

Sunday 18 August 2013

what is the session



(1) The session of activity that a user with a unique IP address spends on a Web site during a specified period of time. The number of user sessions on a site is used in measuring the amount of traffic a Web site gets. The site administrator determines what the time frame of a user session will be (e.g., 30 minutes). If the visitor comes back to the site within that time period, it is still considered one user session because any number of visits within that 30 minutes will only count as one session. If the visitor returns to the site after the allotted time period has expired, say an hour from the initial visit, then it is counted as a separate user session.
Contrast with unique visitor, hit, click-through and page view, which are all other ways that site administrators measure the amount of traffic a Web site gets.
(2) The period of time a user interfaces with an application. The user session begins when the user accesses the application and ends when the user quits the application.

Saturday 6 July 2013

XML TO PHPMYADMIN DATA INSERT THROUGH PHP

<?php
include_once('conf/conf.php');
?>
<?php
$xml=simplexml_load_file("CityList.xml");
foreach($xml as $child)
  {
  mysql_query("INSERT INTO `tr_in_city`set CityCode='$child->CityCode',CityName='$child->CityName',CountryCode='$child->CountryCode'") or die("not inserted");
  }
?>

Tuesday 21 May 2013

url rewrite

URL rewriting on Linux Apache and wamp
For rewriting url on Centos Please do these steps.
  1. First go to '/etc/httpd/conf/httpd.conf' and for wamp left click on wamp icon and go to Apache then httpd.conf and uncomment - #LoadModule rewrite_module modules/mod_rewrite.so and #AddModule mod_rewrite.c, so do so please remove trailing #.

  2. Now Edit directory section in this file for directory /var/www/html and change 'AllowOverride none' to 'AllowOverride All'.

    Eg.
    Options Indexes FollowSymLinks
    AllowOverride none
    Order allow,deny
    Allow from all
    ;
    TO

    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    ;
  3. Now make a file in server root directory '/var/www/html' name .htaccess and write these line in this

Options +FollowSymlinks

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^(.*).php$ $1.html [NC]

RewriteRule ^(.*).html$  $1.php [NC]



4-Now this will replace php extension in your file to .html extension  so now if you want to open index.php then write only http://url/index.html only instead of http://url/index.php

Tuesday 7 May 2013

for submit form on change jquery




<script>
$(document).ready(function() {
alert("hello");
    $('#catname').change(function() {
        $('form').submit();
    });
});


</script>

Tuesday 9 April 2013



//for js
$("select.gw").live("change",function()
    {
   
        var gpid = $(this).attr("data");
        var thid = $(this).attr("id");
        var gwid = $("select#"+thid+" option:selected").val();
        var tmpp = "select#"+thid+" option:selected";
        if(gwid!='')
        {
       
        $.post("ajax/dropdown.php", { gwid: gwid },
        function(data) {
       
        $("select#"+gpid).attr("disabled",false);
        $("select#"+gpid).html(data);
        });
        }
        else
        {
       
        $("select#"+gpid).html("");
        $("select#"+gpid).attr("disabled",true);
        }
   
    });
   
           
            //drop down list
<select name="gw1" id="gw1" class="gw" data="gp1"><option value="">Please Select</option>
                <?php $fetRefre = mysql_query("select * from  table");
                while($rowGate = mysql_fetch_array($fetRefre))
                {?>
                <option value="<?=$rowGate['id']?>"><?=$rowGate['name']?>       
                <?php }?>
                </select>


//ajax page
if($_POST['gwid']) {
  $id = $_POST['gwid'];
  $sql=mysql_query("SELECT * FROM table where gw_id =$id ");

    while($row = mysql_fetch_array($sql)) {
      $id=$row['id'];
      $data=$row['name'];
      echo "<option value=$id>$data</option>";
    }
 }

Friday 5 April 2013

chain delete recursive

function recursiveDelete($id) {
                        $result=mysql_query("SELECT * FROM vb_users WHERE parent_uid = '$id'");
                                if (mysql_num_rows($result)>0) {
                                     while($current=mysql_fetch_array($result)) {
                                      recursiveDelete($current['id']);
                                     }
                                }
                                echo $id."<br>";
                      // mysql_query("DELETE FROM cc_reseller WHERE id='$id'") or die("some thing error 1");
                       
                     
                        }   
     recursiveDelete($_GET['id']);

Wednesday 20 March 2013

Anil Yadav: memcache

Anil Yadav: memcache: Memcached with PHP. Memcahced open source distributed memory object caching system it helps you to speeding up the dynamic web appli...

Tuesday 19 March 2013

memcache

Memcached with PHP.

Memcahced open source distributed memory object caching system it helps you to speeding up the dynamic web applications by reducing database server load. In this post I want to explain how I had implemented Memcached object caching system for  This system is very helpful for high traffic media and blog related websites.

Memcached



Database
Sample database demos table contains id, title and link.
CREATE TABLE demos
(
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(300),
link VARCHAR(300),
);

First User Request
First request goes to database server at the same time data object storing in Memcached server.
Memcached

Second User Request
Second user request data comes from Memcached object.
Memcached

Memcached Installation
Lots of better resources available on web please follow the links. php_memcache.dll
INSTALLING MEMCACHED ON AMAZON LINUX AMI - QUICK AND EASY.
INSTALLING MEMCACHED ON Windows.
install Memcached on Xampp on Windows 7
Memcached for PHP 5.3 on Windows 7.

index.php
Contains PHP code.
<?php
include('db.php');
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$key = md5('List 9lessons Demos'); // Unique Words
$cache_result = array();
$cache_result = $memcache->get($key); // Memcached object 

if($cache_result)
{
// Second User Request
$demos_result=$cache_result;
}
else
{
// First User Request 
$v=mysql_query("select * from demos order by id desc");
while($row=mysql_fetch_array($v))
$demos_result[]=$row; // Results storing in array
$memcache->set($key, $demos_result, MEMCACHE_COMPRESSED, 1200);
// 1200 Seconds
}

// Result
foreach($demos_result as $row)
{
echo '<a href='.$row['link'].'>'.$row['title'].'</a>';
}

?>

db.php
You have to change hostname, username, password and database name.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

pay pal intigration

Payment System with Paypal


I received a tutorial requests from my reader that asked to me how to implement payment gateway system with Paypal API. In this post I want to explain how to work with Paypal Sandbox test accounts for payment system development and sending arguments while click buy now button. It’s simple and very easy to integrate in your web projects.

Payment System

Download Script     Live Demo

Sample database design for Payment system. Contains there table users, products and sales.
Payment process database design

Users
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(255),
`email` varchar(255) UNIQUE KEY,
)

Products
CREATE TABLE `products`
(
`pid` int(11) AUTO_INCREMENT PRIMARY KEY,
`product` varchar(255),
'product_img` varchar(100),
`price` int(11),
`currency` varchar(10),
 )

Sales
CREATE TABLE `sales`
(
`sid` int(11) AUTO_INCREMENT PRIMARY KEY,
`pid` int(11),
`uid` int(11),
`saledate` date,
`transactionid` varchar(125),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(pid) REFERENCES products(pid)
)


Step 1
Create a Paypal Sandbox account at https://developer.paypal.com/

Step 2
Now create test accounts for payment system. Take a look at Sandbox menu left-side top Sandbox->Test Accounts
Creating Paypal Test Account

Step 3
Here I have created two accounts Buyer (personal) and Seller (merchant/business)
Paypal test accounts

products.php
Contains PHP code. Displaying records from products table product image, product name and product price. Here you have to give your business(seller) $paypal_id id. Modify paypal button form return and cancel_return URLs.
<?php
session_start();
require 'db_config.php';
$uid=$_SESSION['uid'];
$username=$_SESSION['username'];
$paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr'; // Test Paypal API URL
$paypal_id='your_seller_id'; // Business email ID
?>

<body>
<h2>Welcome, <?php echo $username;?></h2>
<?php
$result = mysql_query("SELECT * from products");
while($row = mysql_fetch_array($result))
{
?>
<img src="images/<?php echo $row['product_img'];?>" />
Name: <?php echo $row['product'];?>
Price: <?php echo $row['price'];?>$
// Paypal Button 
<form action='<?php echo $paypal_url; ?>' method='post' name='form<?php echo $row['pid']; ?&gt;'>
<input type='hidden' name='business' value='<?php echo $paypal_id; ?>'>
<input type='hidden' name='cmd' value='_xclick'>
<input type='hidden' name='item_name' value='<?php echo $row['product'];?>'>
<input type='hidden' name='item_number' value='<?php echo $row['pid'];?>'>
<input type='hidden' name='amount' value='<?php echo $row['price'];?>'>
<input type='hidden' name='no_shipping' value='1'>
<input type='hidden' name='currency_code' value='USD'>
<input type='hidden' name='cancel_return' value='http://yoursite.com/cancel.php'>
<input type='hidden' name='return' value='http://yoursite.com/success.php'>
<input type="image" src="https://paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" name="submit">
</form>


<?php
}
?>
</body>

success.php
Paypal payment success return file. Getting Paypal argument like item_number. Paypal data success.php?tx=270233304D340491B&st=Completed&amt=22.00&cc=USD&cm=&item_number=1
<?php
session_start();
require 'db_config.php';
$uid = $_SESSION['uid'];
$username=$_SESSION['username'];
$item_no = $_GET['item_number'];
$item_transaction = $_GET['tx']; // Paypal transaction ID
$item_price = $_GET['amt']; // Paypal received amount
$item_currency = $_GET['cc']; // Paypal received currency type

//Getting product details
$sql=mysql_query("select product,price,currency from producst where pid='$item_no'");
$row=mysql_fetch_array($sql);
$price=$row['price'];
$currency=$row['currency'];

//Rechecking the product price and currency details
if($item_price==$price && item_currency==$currency)
{

$result = mysql_query("INSERT INTO sales(pid, uid, saledate,transactionid) VALUES('$item_no', '$uid', NOW(),'$item_transaction')");
if($result)
{
echo "<h1>Welcome, $username</h1>";
echo "<h1>Payment Successful</h1>";
}
}
else
{
echo "Payment Failed";
}
?>

Positive approach


cancel.php
Paypal API cancel_return file.
<?php
session_start();
$username=$_SESSION['username'];
echo "<h1>Welcome, $username</h1>";
echo "<h1>Payment Canceled</h1>";
?>

Negative approach


Step 4
When your web application test payment system workflow is completed. Change the form action development API URLs to original API URLs and give valid $paypal_id seller email id.
$paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr';
to
$paypal_url='https://www.paypal.com/cgi-bin/webscr';

Saturday 9 March 2013

php udp socket client

<?php

/*
        Simple php udp socket client
*/

//Reduce errors
error_reporting(~E_WARNING);

$server = '127.0.0.1';
$port = 9999;

if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
        $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

//Communication loop
$i=1;
while(1)
{
$i++;
        //Take some input to send
        echo 'Enter a message to send : ';
        $input = $i;
sleep(5);

        //Send the message to the server
        if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port))
        {
                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);

                die("Could not send data: [$errorcode] $errormsg \n");
        }

//Now receive reply from server and print it
/*      if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE)
        {
                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);

                die("Could not receive data: [$errorcode] $errormsg \n");
        }
echo "Reply : $reply";
*/}
?>
          

socket create through php socket

<?php
error_reporting(~E_WARNING);

//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
        $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 9999) )
{
        $errorcode = socket_last_error();
  $errormsg = socket_strerror($errorcode);

    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

//Do some communication, this loop can handle multiple clients
while(1)
{
        echo "Waiting for data ... \n";

        //Receive some data
        $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
        echo "$remote_ip : $remote_port -- " . $buf;

        //Send back the data to the client
        socket_sendto($sock, "OK " . $buf , 100 , 0 ,$remote_ip ,$remote_port);
                                                              }

socket_close($sock);
?>
       

install node.js

install dependencies to retrieve, build and browse.
            
$ sudo apt-get install g++ curl libssl-dev apache2-utils
$ sudo apt-get install git-core

Retrieve from repository.
            
$ git clone git://github.com/ry/node.git

Build node.js.
$ cd node
$ ./configure
$ make
$ sudo make install

Create ‘helloworld.js’.
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

Run ‘helloworld.js’.
            
$ node helloworld.js
Server running at http://127.0.0.1:1337/

Browse to verify

            
http://127.0.0.1:1337/