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

PHP Execute a HTTP POST Using PHP CURL

PHP Execute a HTTP POST Using PHP CURL

Today Discussed PHP Curl Post Means PHP Execute a HTTP POST Using PHP Curl.Well, there's a hurdle -- the information isn't going to be saved on the localhost database -- it needs to be stored in a remote database that I cannot connect directly to.

PHP Execute a HTTP POST Using PHP CURL
PHP Execute a HTTP POST Using PHP CURL

  1. User will submit the form, as usual.
  2. In the form processing PHP, I use cURL to execute a POST transmission to a PHP script on the customer's server.
  3. The remote script would do a MySQL INSERT query into the customer's private database.
This solution worked quite well so I thought I'd share it with you. Here's how you execute a POST using the PHP CURL library.


Curl Post Code Follows

//extract data from the post
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
 'lname' => urlencode($_POST['last_name']),
 'fname' => urlencode($_POST['first_name']),
 'title' => urlencode($_POST['title']),
 
);

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

PHP Image delete Common Function Jquery Ajax Call

PHP Image delete Common Function Jquery Ajax Call


Today Discussed PHP Image delete Common Function Jquery Ajax Call Normal Core PHP Commonly Write one function just put table name and primary id and path get delete the image and unlink this page follows code.

PHP Image delete Common Function Jquery Ajax Call
PHP Image delete Common Function Jquery Ajax Call


Form.php

 <div class="col-md-6" id="delimage">
                                    <label> </label>
                                    <?php if (getprofile('image', $_SESSION['UID']) != '') { ?>
                                                                                        <img src="<?php echo $sitename . 'pages/profile/image/' . getprofile('image', $_SESSION['UID']); ?>" style="padding-bottom:10px;" height="100" /><!--&nbsp;<buttton type="button" style="cursor:pointer;" class="btn btn-danger" name="del" id="del" onclick="javascript:dellocationimage();"><i class="fa fa-close">&nbsp;Delete Image</i></buttton>-->
                                        <button type="button" style="cursor:pointer;" class="btn btn-danger" name="del" id="del" onclick="javascript:deleteimage('<?php echo getprofile('image', $_SESSION['UID']); ?>', '<?php echo $_SESSION['UID']; ?>', 'manageprofile', '../pages/profile/image/', 'image', 'pid');"><i class="fa fa-close">&nbsp;Delete Image</i></button>
                                    <?php } ?>
                                </div>
Ajax.js(Javascript)
function deleteimage(a, b, c, d, e, f)
{
    if (window.XMLHttpRequest)
    {
        oRequestsubcat = new XMLHttpRequest();
    } else if (window.ActiveXObject)
    {
        oRequestsubcat = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (a != '' && b != '' && c != '' && d !='' && e !=''&& f !='')
    {
        document.getElementById("delimage").innerHTML = '<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>';
        oRequestsubcat.open("POST", Settings.base_url + "config/functions_ajax.php", true);
        oRequestsubcat.onreadystatechange = delimg;
        oRequestsubcat.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        oRequestsubcat.send("image=" + a + "&id=" + b + "&table=" +c + "&path=" + d + "&images=" +e + "&pid=" + f);
        console.log(a,b,c,d,e,f);
    }
}
function delimg()
{
    if (oRequestsubcat.readyState == 4)
    {
        if (oRequestsubcat.status == 200)
        {
            document.getElementById("delimage").innerHTML = oRequestsubcat.responseText;
        }
        else
        {
            document.getElementById("delimage").innerHTML = oRequestsubcat.responseText;
        }
    }
}
or

Ajax.js(Jquery)
function deleteimage(a,b,c,d)
{
    $.post(Settings.base_url + "config/functions_ajax.php",{ a:a,b:b,c:c,d:d },function(data){
        console.log(data);
        $('#delimage').html(data);
        //alert(data);
    });
}

Function.php

if (($_REQUEST['image'] != '') && ($_REQUEST['id'] != '') && ($_REQUEST['table'] != '')&& ($_REQUEST['path'] != '')&& ($_REQUEST['images'] != '')&& ($_REQUEST['pid'] != '')) {
    unlink($_REQUEST['path'].$_REQUEST['image']);
 // $s = "UPDATE `".$_REQUEST['table']."` SET `".$_REQUEST['images']."`='' WHERE `".$_REQUEST['pid']."`='" . $_REQUEST['id'] . "'";
   // echo $s;
    //return $s;
   // exit;
    DB("UPDATE `".$_REQUEST['table']."` SET `".$_REQUEST['images']."`='' WHERE `pid`='" . $_REQUEST['id'] . "'");
    DB("INSERT `history` (`page`,`pageid`,`action`,`userid`,`ip`,`actionid`,`info`) VALUES ('Manage Profile','9','Delete','" . $_SESSION['UID'] . "','" . $_SERVER['REMOTE_ADDR'] . "','" . $_REQUEST['b'] . "','Image Deletion')");
  echo '<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="icon fa fa-close"></i>Succesfully Deleted</h4><!--<a href="' . $sitename . 'settings/adddepartment.htm">Add another one</a>--></div>';

PHP Security ImagesCaptcha

PHP security imagesCaptcha

PHP Security imagesCaptcha is a simple test to determine if a user is a computer or a human.  It is used to prevent spam abuse on the websites. Just Avoid spamers and crackers in the sites. So if you use CAPTCHA on your web forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms. Normal Core PHP simple Shopping Cart

PHP security imagesCaptcha
PHP security imagesCaptcha


Captcha.php

<?php
session_start();
class CaptchaSecurityImages {

 var $font = 'monofont.ttf';

 function generateCode($characters) {
  /* list all possible characters, similar looking characters and vowels have been removed */
  $possible = '23456789bcdfghjkmnpqrstvwxyz';
  $code = '';
  $i = 0;
  while ($i < $characters) { 
   $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
   $i++;
  }
  return $code;
 }

 function CaptchaSecurityImages($width='60',$height='50',$characters='5') {
  $code = $this->generateCode($characters);
  /* font size will be 75% of the image height */
  $font_size = $height * 0.85;
  $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
  /* set the colours */
  $background_color = imagecolorallocate($image, 255, 255, 255);
  $text_color = imagecolorallocate($image, 20, 40, 100);
  $noise_color = imagecolorallocate($image, 200, 200, 200);
  /* generate random dots in background */
  for( $i=0; $i<($width*$height)/3; $i++ ) {
   imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
  }
  /* generate random lines in background */
  for( $i=0; $i<($width*$height)/150; $i++ ) {
   imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
  }
  /* create textbox and add text */
  $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
  $x = ($width - $textbox[4])/2;
  $y = ($height - $textbox[5])/2;
  imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
  /* output captcha image to browser */
  header('Content-Type: image/jpeg');
  imagejpeg($image);
  imagedestroy($image);
  $_SESSION['keycode'] = $code;
 }

}

$width = isset($_GET['width']) ? $_GET['width'] : '90';
$height = isset($_GET['height']) ? $_GET['height'] : '21';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '5';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>
Your Form Page Added Following Script.
<script type="text/javascript">

function refreshCaptcha(abspath){

document.getElementById('refcaptimg').src="Captcha.php?t=" + new Date().getTime();

}</script>
Form

<form name="frmContact" method="post" action="contact-us.html">
<table width="175" border="0" cellpadding="2" cellspacing="0">
 <tr>
   <td  height="81" align="left" valign="middle"><a href="full_certificate.pdf" target="_blank"><img src="images/svc.gif" alt="" border="0"/></a></td>

  </tr>
<tr>

<td style="padding-bottom:10px;">
<div>
<!-- End Comm100 Live Chat Button Code -->

</td>
  </tr>

  <tr>
    <td class="page_heading"> </td>
  </tr>
  <tr>

   <td class="fnt_sml" style="padding-top:10px;"><img src="images/FORM/OPT-1.png" width="39" height="8" /><span style="color:#FF0000"></span></td>
  </tr>
  <tr>
   <td  ><input type="text" name="Name" id="Name" class="input_left" value='<?php echo $LastName?>' />
<span style="clear:left;" class="input_left_error" ><?php echo $msgName?></span></td>
  </tr>
 <tr>
    <td class="fnt_sml"><img src="images/FORM/OPT-3.png" /></span></td>

  </tr>
  <tr>
    <td><input type="text" name="Email" id="Email" class="input_left" value='<?php echo $Email ?>' />

<span style="clear:left;" class="input_left_error" ><?php echo $msgEmail ?></span></td>

  </tr>
  <tr>
    <td class="fnt_sml"><img src="images/FORM/OPT-4.png" /></td>
  </tr>
  <tr>
    <td><input type="text" name="Phone" id="Phone" class="input_left" value='<?php echo $Phone ?>' />

<span style="clear:left;" class="input_left_error" ><?php echo $msgPhone ?></span></td>

  </tr>
  <tr>
   <td class="fnt_sml"><img src="images/FORM/OPT-5.png" width="57" height="10" /></td>

  </tr>
  <tr>
    <td class="fnt_sml"><input type="text" name="TelPhone" class="input_left" id="TelPhone" value='<?php echo $TelPhone?>' />
    <span style="clear:left;" class="input_left_error"><?php echo $msgTelPhone ?></span></td>
  </tr>
 <tr>
   <td class="fnt_sml"><img src="images/FORM/OPT-2.png" /></td>

  </tr>
  <tr>
    <td><textarea name="Message" id="Message" rows="5" cols="25" class="input_left" value='<?php echo $Message?>'></textarea>

<span style="clear:left;" class="input_left_error" ><?php echo $msgMessage ?></span></td>
   </tr>
  <tr>
    <td class="fnt_sml"><img src="images/FORM/OPT-6.png" width="89" height="8" /></td>

  </tr>
  <tr>
    <td align="center"><input type="text" name="keycode" id="keycode" size="20" class="input_left" style="width:170px;" value='<?php echo $keycode ?>' />

<span style="clear:left;" class="input_left_error" > <?php echo $msgkeycode ?> </span>

<img src="CaptchaSecurityImages.php" id="refcaptimg" align="middle" style="margin-top:5px;" alt="" />&nbsp;<a href="javascript:refreshCaptcha('images/')"><img  src="images/hip_reload.gif" width="22" height="22" border="0" align="middle" style="margin-top:1px;" alt="" /></a>
          <a href="javascript:refreshCaptcha('images/')"><span class="style1" style="color: #FE4819"></span></a>

      <div class="input_left_error"></div></td>
  </tr>
  <tr>
    <td align="center"><input type="submit" name="Submit" value="Submit" style="background-color:#2172B8; color:#ffffff; border:solid 1px #2172B8;" />
</td>
</tr>
</table>
</form>

PHP Code Follow us : Contact-us.php

<?php if(isset($_POST[Submit])){

if(empty($_POST[Name])){$msgName='Please Enter Your Name.'; $Name= false;}
 else{$Name=$_POST[Name];}

if(empty($_POST[Message])) {$msgMessage= 'Please Enter your message.'; $Message=false; }
       else{$Message=$_POST[Message];}

if(empty($_POST[Email])){$msgEmail='Please Enter Your Email-Id';$Email= false; }
 else{$Email=$_POST[Email];}
 if (!eregi("^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$", $_POST[Email])){ $msgEmail= 'Please Enter A Valid Email Address'; $Email = false; }
 else{$Email=$_POST[Email];}

if(empty($_POST[Phone])){$msgPhone='Please Enter Your Contact No. '; $Phone= false;}
 else{$Phone=$_POST[Phone];}
 if(!eregi("[0-9.-\+]", $_POST[Phone])) {$msgPhone='Please enter a valid contact no. '; $Phone=false;}
 else{ $Phone=$_POST[Phone];}

 $TelPhone=$_POST[TelPhone];

if($_POST[keycode]!=$_SESSION[keycode] OR $_SESSION[keycode]==''){$msgkeycode = 'Incorrect verification code';$keycode = false;}
 else{$keycode=$_POST[keycode];}
 if($Name  && $Message && $Email && $Phone && $Message && $keycode)
 {
  header("Location: $tpage");
exit;
}else{ index.php } ?>

Paypal Integration With PHP & MYSQL

PAYPAL INTEGRATION WITH PHP & MYSQL


Paypal Integration
Paypal Integration
Previously Discussed Simple PHP shopping cart stored a cart payment integration is discussed Follow us
Simple Way to PHP Paypal Integration following steps.

Step : 1

First Setup your Paypal Account

Signup Paypal Account if you don't already have one.  In order to use PIN, the paypal account you are selling from must be a Business Account

Select ‘edit profile’ from your PayPal account and check the following settings.

Under ‘My Selling Preferences’ >> ‘Getting paid and managing risk’ >> ‘Instant Payment Notification Preferences’
  1. Set the IPN value to ‘On’
  2. Set the IPN URL to the PHP page containing the IPN code shown in steps 3 & 4 of this tutorial. (http://www.example.com/payment.php)
Step : 2

Your Website Looking UI design and must now send all required value to paypal so that the payment can be processed.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paypal Integration Test</title>
</head>
<body>
<form class="paypal" action="payments.php" method="post" id="paypal_form" target="_blank">
<input type="hidden" name="command" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="UK" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
<input type="hidden" name="first_name" value="Customer's First Name" />
<input type="hidden" name="last_name" value="Customer's Last Name" />
<input type="hidden" name="payer_email" value="customer@example.com" />
<input type="hidden" name="item_number" value="123456" / >
<input type="submit" name="submit" value="Submit Payment"/>
</form>
</body>
</html>

Step:3 

Paymen Page REQUEST 

// Database variables
$hostname = "localhost"; //database location
$username = ""; //database username
$password = ""; //database password
$db_name = ""; //database name
// PayPal settings
$paypal_email = 'user@domain.com';
$return_url = 'http://domain.com/payment-successful.html';
$cancel_url = 'http://domain.com/payment-cancelled.html';
$notify_url = 'http://domain.com/payments.php';
$item_name = 'Test Item';
$item_amount = 5.00;
// Include Functions
include("functions.php");
// Check if paypal request or response
if (!isset($_POST["txn_id"]) &amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp; !isset($_POST["txn_type"])){
    $querystring = '';
    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&amp;amp;amp;amp;amp;amp;";
    // Append amount&amp;amp;amp;amp;amp;amp; currency (£) to quersytring so it cannot be edited in html
    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&amp;amp;amp;amp;amp;amp;";
    $querystring .= "amount=".urlencode($item_amount)."&amp;amp;amp;amp;amp;amp;";
    //loop for posted values and append to querystring
    foreach($_POST as $key =&amp;amp;amp;amp;amp;gt; $value) {
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&amp;amp;amp;amp;amp;amp;";
    }
    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&amp;amp;amp;amp;amp;amp;";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&amp;amp;amp;amp;amp;amp;";
    $querystring .= "notify_url=".urlencode($notify_url);
    // Append querystring with custom field
    //$querystring .= "&amp;amp;amp;amp;amp;amp;custom=".USERID;
    // Redirect to paypal IPN
    header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
    exit();
} else {
   // Response from PayPal
}
Step: 4 

Payment Page Response

 // Database variables
$hostname = "localhost"; //database location
$username = ""; //database username
$password = ""; //database password
$db_name = ""; //database name

// PayPal settings
$paypal_email = 'user@domain.com';
$return_url = 'http://domain.com/payment-successful.html';
$cancel_url = 'http://domain.com/payment-cancelled.html';
$notify_url = 'http://domain.com/payments.php';

$item_name = 'Test Item';
$item_amount = 5.00;

// Include Functions
include("functions.php");

// Check if paypal request or response
if (!isset($_POST["txn_id"]) &amp;amp;amp;&amp;amp;amp; !isset($_POST["txn_type"])){
    $querystring = '';
    
    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&amp;amp;amp;";
    
    // Append amount&amp;amp;amp; currency (£) to quersytring so it cannot be edited in html
    
    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&amp;amp;amp;";
    $querystring .= "amount=".urlencode($item_amount)."&amp;amp;amp;";
    
    //loop for posted values and append to querystring
    foreach($_POST as $key =&amp;amp;gt; $value){
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&amp;amp;amp;";
    }
    
    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&amp;amp;amp;";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&amp;amp;amp;";
    $querystring .= "notify_url=".urlencode($notify_url);
    
    // Append querystring with custom field
    //$querystring .= "&amp;amp;amp;custom=".USERID;
    
    // Redirect to paypal IPN
    header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
    exit();
} else {
    //Database Connection
    $link = mysql_connect($host, $user, $pass);
    mysql_select_db($db_name);
    
    // Response from Paypal

    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key =&amp;amp;gt; $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
        $req .= "&amp;amp;amp;$key=$value";
    }
    
    // assign posted variables to local variables
    $data['item_name']          = $_POST['item_name'];
    $data['item_number']        = $_POST['item_number'];
    $data['payment_status']     = $_POST['payment_status'];
    $data['payment_amount']     = $_POST['mc_gross'];
    $data['payment_currency']   = $_POST['mc_currency'];
    $data['txn_id']             = $_POST['txn_id'];
    $data['receiver_email']     = $_POST['receiver_email'];
    $data['payer_email']        = $_POST['payer_email'];
    $data['custom']             = $_POST['custom'];
        
    // post back to PayPal system to validate
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    
    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
    
    if (!$fp) {
        // HTTP ERROR
        
    } else {
        fputs($fp, $header . $req);
        while (!feof($fp)) {
            $res = fgets ($fp, 1024);
            if (strcmp($res, "VERIFIED") == 0) {
                
                // Used for debugging
                // mail('user@domain.com', 'PAYPAL POST - VERIFIED RESPONSE', print_r($post, true));
                        
                // Validate payment (Check unique txnid &amp;amp;amp; correct price)
                $valid_txnid = check_txnid($data['txn_id']);
                $valid_price = check_price($data['payment_amount'], $data['item_number']);
                // PAYMENT VALIDATED &amp;amp;amp; VERIFIED!
                if ($valid_txnid &amp;amp;amp;&amp;amp;amp; $valid_price) {
                    
                    $orderid = updatePayments($data);
                    
                    if ($orderid) {
                        // Payment has been made &amp;amp;amp; successfully inserted into the Database
                    } else {
                        // Error inserting into DB
                        // E-mail admin or alert user
                        // mail('user@domain.com', 'PAYPAL POST - INSERT INTO DB WENT WRONG', print_r($data, true));
                    }
                } else {
                    // Payment made but data has been changed
                    // E-mail admin or alert user
                }
            
            } else if (strcmp ($res, "INVALID") == 0) {
            
                // PAYMENT INVALID &amp;amp;amp; INVESTIGATE MANUALY!
                // E-mail admin or alert user
                
                // Used for debugging
                //@mail("user@domain.com", "PAYPAL DEBUGGING", "Invalid Response
data =
&amp;amp;lt;pre&amp;amp;gt;".print_r($post, true)."&amp;amp;lt;/pre&amp;amp;gt;

");
            }
        }
    fclose ($fp);
    }
}


Step 5 - Function.php


// functions.php
function check_txnid($tnxid){
global $link;
return true;
$valid_txnid = true;
//get result set
$sql = mysql_query("SELECT * FROM `payments` WHERE txnid = '$tnxid'", $link);
if ($row = mysql_fetch_array($sql)) {
$valid_txnid = false;
}
return $valid_txnid;
}

function check_price($price, $id){
$valid_price = false;
//you could use the below to check whether the correct price has been paid for the product

/*
$sql = mysql_query("SELECT amount FROM `products` WHERE id = '$id'");
if (mysql_num_rows($sql) != 0) {
while ($row = mysql_fetch_array($sql)) {
$num = (float)$row['amount'];
if($num == $price){
$valid_price = true;
}
}
}
return $valid_price;
*/
return true;
}

function updatePayments($data){
global $link;

if (is_array($data)) {
$sql = mysql_query("INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES (
'".$data['txn_id']."' ,
'".$data['payment_amount']."' ,
'".$data['payment_status']."' ,
'".$data['item_number']."' ,
'".date("Y-m-d H:i:s")."'
)", $link);
return mysql_insert_id($link);
}
}


Step: 6 Databast Table

Website Paypal Integration store payment details inset database table is most Important.

CREATE TABLE IF NOT EXISTS `payments` (
 `id` int(6) NOT NULL AUTO_INCREMENT,
 `txnid` varchar(20) NOT NULL,
 `payment_amount` decimal(7,2) NOT NULL,
 `payment_status` varchar(25) NOT NULL,
 `itemid` varchar(25) NOT NULL,
 `createdtime` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;







PHP Shopping Cart

PHP Shopping Cart


PHP Shopping Cart
PHP Shopping Cart


php product shopping cart application. In this tutorial we are going to see a PHP example for creating shopping cart application. This shopping cart application is purposely kept as simple as possible. php shopping create own site.  In this example, we are displaying list of products from database. For each product, we have given options for selecting product quantity and adding to cart. The cart items are stored in a session. We can clear this session by removing items from the cart. cart Page Image

Adding Products  to Shopping Cart

Normal PHP Shopping Cart Product added Simple Code for Follows

<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) { 
foreach($product_array as $key=>$value){
?>
<div class="product-item">
 <form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
 <div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
 <div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
 <div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
 <div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" class="btnAddAction" /></div>
 </form>
</div>
<?php }} ?>

Removing Cart Item

Product Adding to the shopping cart, and following switch case will be executed this code to store selected items information and details into the session. If the selected item is already in session inthe cart, and then the quantity will be checked whether it is changed. If so, it will be updated.

case "remove":
 if(!empty($_SESSION["cart_item"])) {
  foreach($_SESSION["cart_item"] as $k => $v) {
   if($_GET["code"] == $k) unset($_SESSION["cart_item"][$k]);    
   if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]);
  }
 }
break;
case "empty":
 unset($_SESSION["cart_item"]);
break;

Shppoing Cart Store Database MySql Query


Shopping cart selected Item Product stored database
CREATE TABLE IF NOT EXISTS `tblproduct` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `code` varchar(255) NOT NULL,
  `image` text NOT NULL,
  `price` double(10,2) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_code` (`code`)
)