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

Wednesday, August 4, 2010

Dynamic Pagination by Selecting Page No

Pagination by selecting page no for navigation,


This code will help u send page no as parameter in url for navigate in paging.

we send page no 1,2,3 not sending record start position for record show or navigate.




//paging style css code start


.paging { padding:10px 0px 0px 0px; text-align:center; font-size:13px;}
  .paging.display{text-align:right;}
  .paging a, .paging span {padding:2px 8px 2px 8px;}
  .paging span {font-weight:bold; color:#000; font-size:13px; }
  .paging a {color:#000; text-decoration:none; border:1px solid #dddddd;}
  .paging a:hover { text-decoration:none; background-color:#6C6C6C; color:#fff; border-color:#000;}
  .paging span.prn { font-size:13px; font-weight:normal; color:#aaa; }
  .paging a.prn { border:2px solid #dddddd;}
  .paging a.prn:hover { border-color:#000;}
  .paging p#total_count{color:#aaa; font-size:12px; padding-top:8px; padding-left:18px;}
  .paging p#total_display{color:#aaa; font-size:12px; padding-top:10px;}



//paging style css code end


 


 


// paging php code start


$num; //total no of record from sql query


$display;//no of record display on page


$noDisplayPageNo=10; // no of page no range want to show on page


$query=""; // addition parameter or sending data need to send with page no in url


$display=10;
if(!isset($_REQUEST['init']) || $_REQUEST['init']==""){
$init=$start=0;

}else{
$init=$_REQUEST['init'];
$start=($init)*$display;
}


$pages=ceil($num/$display);

$current = ($start/$display)+1;

$startpageNo=max($current-intval($noDisplayPageNo/2), 1); // start page no range
$endpageNo=$start+$noDisplayPageNo-1; // end page no range



if(strlen($query)>0){
$query = "&".$query_string;
}


echo '<div class="paging">';

if($current==1) {
echo '<span class="prn">&lt; Previous</span> ';
} else {
$i = $current-1;
//echo '--'.$i;
echo '<a class="prn" title="go to page '.$i.'" rel="nofollow" href="'.$_SERVER['PHP_SELF'].'?init='.($i-1).$query.'">&lt; Previous</a>';
echo '<span class="prn">...</span> ';
}



for ($i = $startpageNo; $i <= $endpageNo && $i <= $pages; $i++){
if($i==$current) {
echo '<span>'.$i.'</span> ';
} else {
echo '<a title="go to page '.$i.'" href="'.$_SERVER['PHP_SELF'].'?init='.($i-1).$query.'">'.$i.'</a> ';
}
}


if($current < $pages) {
$i = $current;
echo '<span class="prn">...</span> ';
echo '<a class="prn" title="go to page '.$i.'" rel="nofollow" href="'.$_SERVER['PHP_SELF'].'?init='.$i.$query.'">Next &gt;</a> ';
} else {
echo '<span class="prn">Next &gt;</span> ';
}


if ($total != 0){
//prints the total result count just below the paging
echo '(total '.$pages.' results)</div>';
}

Wednesday, May 5, 2010

Php Script for Check Email open

How to check that send email is open by receiver or not

If we send email use Php mail() function and want that you get information when receiver open that mail or want to keep record of open mail send in mass sending of mail using Php mail() function. To do that we use following code.




$to=""; //email receiver id
$subj=""; // subject of mail
$msg=""; // message that send to receiver
$senderheaders  = "From: news@example.com\r\n";
$senderheaders .= "Content-type: text/html\r\n";
$senderheaders.="<img src=\"http://www.example.com/trackemail.php?receiverId=$id\" width=\"1\" height=\"1\" />";

mail($to,$subj,$msg,$senderheaders);
?>

In above code we send image of 1*1px with the header of the mail. when receiver open that mail that will send back to tracking file of sender site and tell them that email is check by receiver.




Monday, May 3, 2010

Integration of CCAVENUE Payment gateway

Integration of CCAVENUE Payment Cart in Your Shopping Section 


CCavenue is most popular Payment gateway for online Shopping. It provide payment through using International credit card as well using your Bank (who have bond with CCavenue) online Account or using it's debit card(ATM card). It is one of the most secure place for given your money to online shop.

For Integrate it with your website you should have ccavenue account and they give you a merchant id and a unique key for your site that is most important for money transaction.


Php Function's Require TO Validate Require Value for CCAvenue Payment.


<?php


function getchecksum($MerchantId,$Amount,$OrderId ,$URL,$WorkingKey)
  {
  $str ="$MerchantId|$OrderId|$Amount|$URL|$WorkingKey";
  $adler = 1;
  $adler = adler32($adler,$str);
  return $adler;
  }


function verifychecksum($MerchantId,$OrderId,$Amount,$AuthDesc,$CheckSum,$WorkingKey)
  {
  $str = "$MerchantId|$OrderId|$Amount|$AuthDesc|$WorkingKey";
  $adler = 1;
  $adler = adler32($adler,$str);

  if($adler == $CheckSum)
  return "true" ;
  else
  return "false" ;
  }


function adler32($adler , $str)
  {
  $BASE =  65521 ;


$s1 = $adler & 0xffff ;
  $s2 = ($adler >> 16) & 0xffff;
  for($i = 0 ; $i < strlen($str) ; $i++)
  {
  $s1 = ($s1 + Ord($str[$i])) % $BASE ;
  $s2 = ($s2 + $s1) % $BASE ;
  //echo "s1 : $s1 <BR> s2 : $s2 <BR>";


}
  return leftshift($s2 , 16) + $s1;
  }


function leftshift($str , $num)
  {


$str = DecBin($str);


for( $i = 0 ; $i < (64 - strlen($str)) ; $i++)
  $str = "0".$str ;


for($i = 0 ; $i < $num ; $i++)
  {
  $str = $str."0";
  $str = substr($str , 1 ) ;
  //echo "str : $str <BR>";
  }
  return cdec($str) ;
  }


function cdec($num)
  {


for ($n = 0 ; $n < strlen($num) ; $n++)
  {
  $temp = $num[$n] ;
  $dec =  $dec + $temp*pow(2 , strlen($num) - $n - 1);
  }


return $dec;
  }
  ?>







CCAvenue Passing Parameter That Require for Complete the Shopping


<?php
    $Merchant_Id = "";//This id(also User Id)  available at "Generate Working Key" of "Settings & Options"
    $Amount = $orderdata[5];//your script should substitute the amount in the quotes provided here
    $Order_Id = $orderdata[0];;//your script should substitute the order description in the quotes provided here
    $WorkingKey = "";//Given to merchant by ccavenue
    $Redirect_Url ="http://www.example.com/shopping.php";
    $Checksum = getCheckSum($Merchant_Id,$Amount,$Order_Id ,$Redirect_Url,$WorkingKey); // Validate All value
    ?>
<p align="center" style="font-family:Calibri; font-size:18px;"><img src="http://www.example.com/images/loader.gif" alt="loader"></p>
<p align="center" style="font-family:Calibri; font-size:24px;color:#3670A7;">Processing to CCAvenue..............</p>
<form id="form2" method="post" action="https://www.ccavenue.com/shopzone/cc_details.jsp">
<input type=hidden name=Merchant_Id value="<?php echo $Merchant_Id; ?>">
<input type="hidden" name="Amount" value="<?php echo $Amount; ?>">
<input type="hidden" name="Order_Id" value="<?php echo $Order_Id; ?>">
<input type="hidden" name="Redirect_Url" value="<?php echo $Redirect_Url; ?>">
<input type="hidden" name="Checksum" value="<?php echo $Checksum; ?>">
<input type="hidden" name="billing_cust_name" value="<?= $orderdata[7].' '.$orderdata[8];?>"> <!--Pass Customer Full Name -->
<input type="hidden" name="billing_cust_address" value="<?= $orderdata[9].' '.$orderdata[10];?>"><!--Pass Customer Full Address-->
<input type="hidden" name="billing_cust_country" value="<?= $orderdata[15];?>"> <!--Pass Customer Country -->
<input type="hidden" name="billing_cust_state" value="<?= $orderdata[14];?>"><!--Pass Customer State -->
<input type="hidden" name="billing_cust_city" value="<?= $orderdata[13];?>"> <!--Pass Customer City -->
<input type="hidden" name="billing_zip" value="<?= $orderdata[16];?>"> <!--Pass Customer Zip Code-->
<input type="hidden" name="billing_cust_tel" value="<?= $orderdata[11];?>"> <!--Pass Customer Phone No-->
<input type="hidden" name="billing_cust_email" value="<?= $orderdata[12];?>"> <!--Pass Customer Email address-->
<input type="hidden" name="delivery_cust_name" value="<?= $orderdata[7].' '.$orderdata[8];?>"> <!--Pass Same or other other detail fill by customer-->
<input type="hidden" name="delivery_cust_address" value="<?= $orderdata[9].' '.$orderdata[10];?>">
<input type="hidden" name="delivery_cust_country" value="<?= $orderdata[15];?>">
<input type="hidden" name="delivery_cust_state" value="<?= $orderdata[14];?>">
<input type="hidden" name="delivery_cust_tel" value="<?= $orderdata[11];?>">
<input type="hidden" name="delivery_cust_notes" value="">
<input type="hidden" name="Merchant_Param" value="">
<input type="hidden" name="billing_zip_code" value="<?= $orderdata[16];?>">
<input type="hidden" name="delivery_cust_city" value="<?= $orderdata[13];?>">
<input type="hidden" name="delivery_zip_code" value="<?= $orderdata[16];?>">


</form>



Friday, April 30, 2010

Paypal Webstie Standard Payment Method

Paypal Webstie Standard Payment Method for website

    
When we use Paypal website standard payment method for shopping cart with multiple buy item. On this method customer complete it's shopping on website and the time of payment he completely move to paypal website with complete detail of his buy item name, item qty , item amount and with Total Amount. On paypal site all detail will display as display on his shopping cart. here all necessary field that is will on site like first name, address,etc. will automatically filled and here customer need to just fill their credit card and it’s related field’s to complete the process.    

    
When customer complete the payment process then one url of success payment is also send form the site to paypal (in return input type) site will appear in form button on click on that button customer will reach to success page of website.      

    
There is on link of fail on cancel for not to complete the process.

    






Paypal Require Code:-





<form id="form1" action="https://www.paypal.com/cgi-bin/webscr" method="post">
  <input type="hidden" name="business" value="{$merchantId}" />


<!--merchant paypal id in which payment will go-->
  <input type="hidden" name="cmd" value="_cart" />
  <input type="hidden" name="paymentaction" value="sale" />
  <?php

 // $itemresult result set of customer buy item fetch form order_item table and table where final order item is store
 $i=1;
 while($row = mysql_fetch_array($itemresult))
 {
 $amountinrupee = $row[1];
 $amount = round(intval($amountinrupee)/46.180,2);

 ?>
  <input type="hidden" name="item_name_<?= $i;?>" value="<?= $row[0];?>" />
  <input type="hidden" name="amount_<?= $i;?>" value="<?= $amount;?>" />
  <input type="hidden" name="quantity_<?= $i;?>" value="<?= $row[2];?>" />
  <?php
 $i++;
 }
 ?>
  <input type="hidden" name="first_name" value="<?= $orderdata[7];?>" /><!--customer first name -->
  <input type="hidden" name="last_name" value="<?= $orderdata[8];?>" /><!--customer last name -->
  <input type="hidden" name="address1" value="<?= $orderdata[9];?>" /><!--customer address 1 name -->
  <input type="hidden" name="address2" value="<?= $orderdata[10];?>" /><!--customer add2 name -->
  <input type="hidden" name="email" value="<?= $orderdata[12];?>" /><!--customer email name -->
  <input type="hidden" name="city" value="<?= $orderdata[13];?>" /><!--customer city name -->
  <input type="hidden" name="state" value="<?= $orderdata[14];?>" /><!--customer state name -->
  <input type="hidden" name="country" value="<?= $orderdata[15];?>" /><!--customer country name -->
  <input type="hidden" name="zip" value="<?= $orderdata[16];?>" /><!--customer zip name -->
  <input type="hidden" name="currency_code" value="USD" /><!--currrecy in which payment u need-->
  <input type="hidden" name="upload" value="1" /><!--paypal parameter-->
  <input type="hidden" name="return" value="http://www.example.com/shopcomplete.php" />
  <input type="hidden" name="cancel_return" value="http://www.example.com/shopfail.php" />
  </form>



Friday, December 25, 2009

Dayanmic Pagination in PHP

Creating dyanamic pagination for any site or section of site with Display page rang of display page no of all pages in PHP.

Creating Following Pagination format

Example :-




 $strPosition=$_REQUEST['startPostion']; //Record Start Position

  if(isset($strPosition) && $strPosition>=1){
  $start=$strPosition;

  }else{
  $start=0;
  }
  $display=15; //No. of record dispaly onl single page or one Page

  $rsCount; //No. of record fetch from recordset (database table)


$pages=ceil($rsCount/$display); //Calculate pages will display or get from database table



<div align="left" style="width:500px; border:#666666 solid 1px; display:block;">


<!-- Display Previous Page Button(Link) -->


<div align="left" style="float:left">
  <?php


  
  // echo $currentPage;
  if($pages>1){

  $currentPage=($start/$display)+1; //Current Page No. on which page is have

  $stPageNo=$currentPage-4; //Set Start Page no for page range

  $endPageNo=(($currentPage+5)<$pages)? $currentPage+5 : $pages;    //Set End Page No for page range

  if($currentPage>=1){

  echo '<a href="'.$_SERVER["PHP_SELF"].'?startPostion='.($start-$display).'">
  <span style="color:#FF9933; font-family:Arial, Helvetica, sans-serif; font-size:14px">Previous Page</span>
  </a>';
  }
  }
  ?>
  </div>

Ex:-




  <!-- List of Page No in Block Format-->


<div align="left" style="float:left; padding-left:5px;">
  <?php
  for($i=$stPageNo;$i<=$endPageNo;$i++){
  if($i>0){
  if($i==$currentPage){
  echo'<span title="Current Page">'.$i.'</span>';
  }else{
  echo '<a title="page '.$i.'" href="'.$_SERVER['PHP_SELF'].'?startPostion='.($display*($i-1)).'" class="no-underline">
  <span style="color:#FF9933; font-family:Arial, Helvetica, sans-serif; font-size:14px; display:block; border:#CCCCCC solid 1px; width:15px; text-align:center;">'.$i.'&nbsp;'.'</span></a>';
  }

  }
  }
  ?>
  </div>

Ex:-




 <!-- Display Next Page Button(Link) -->



<div align="left" style="float:right">
  <?php
  if($pages>1){
  if($currentPage!=$pages){

  echo '<a href="'.$_SERVER["PHP_SELF"].'?startPostion='.($start+$display).'"><span style="color:#FF9933; font-family:Arial, Helvetica, sans-serif; font-size:14px">Next Page</span></a>';

  }
  }
  ?>
  </div>

Ex:-


  </div>


Out Put:-





Saturday, December 19, 2009

Spelling Checking in php

Spelling Check in php. Pass checking string to function and get result in from of any error.

function checkSpell($input)
{
    $word=new COM("word.application") or die("Cannot create Word object");
    $word->Visible=false;
    $word->WindowState=2;
    $word->DisplayAlerts=false;
    $doc=$word->Documents->Add();
    $doc->Content=$input;
    $doc->CheckSpelling();
    $result= $doc->SpellingErrors->Count;
    if($result!=0)
    {
        echo "Input text contains misspelled words.\n\n";
        for($i=1; $i <= $result; $i++)
        {      
            echo "Original Word: " .$doc->SpellingErrors[$i]->Text."\n";
            $list=$doc->SpellingErrors[$i]->GetSpellingSuggestions();
            echo "Suggestions: ";
            for($j=1; $j <= $list->Count; $j++)
            {
                $correct=$list->Item($j);
                echo $correct->Name.",";
            }
            echo "\n\n";
        }
    }
    else
    {
        echo "No spelling mistakes found.";
    }
    $word->ActiveDocument->Close(false);
    $word->Quit();
    $word->Release();
    $word=null;
}

$str="Hellu world. There is a spellling error in this sentence.";
SpellCheck($str);
?>

Friday, December 18, 2009

Upload video

<?php


set_time_limit(0);

define('ffmpeg', '/usr/bin/ffmpeg');
define('FFMPEG_BINARY', '/usr/bin/ffmpeg');
define('FFMPEG_movie', '/usr/bin/ffmpeg_movie');
define('flvtool2Path', '/usr/bin/flvtool2');


$submit=$_POST['submitted']; //Get value form submitted Field
$video_file=$_FILES['vfile']; // Uploaded video file
$videoTitle=$_REQUEST['vTitle']; // upload file title

if(isset($submit)){
function getName($name){


$type=$name;


$type = str_replace( ' ', '_', $type );
return($type);
}

function getImageName($name){
$occur=strrpos($name,'.');
//echo $occur;
$name=substr($name,0,$occur);
return($name);
}


function getFileExtension($fileName){

$fileNameParts = explode( ".", $fileName );
$fileExtension = end( $fileNameParts );
$fileExtension = strtolower( $fileExtension );


return($fileExtension);

}

$videoDirName=$_SERVER['DOCUMENT_ROOT']."/files/video/video/"; //Folder name where video will save
$videoThumDir=$_SERVER['DOCUMENT_ROOT']."/files/video/thum/"; //folder name for where upload video cut thum will save


$newFileName=getName(getImageName($_FILES['videoUpload']['name'])); //Get new file for video file will save with that name

$destinationThum=$videoThumDir.getName(getImageName($_FILES['videoUpload']['name'])).'.jpg'; // complete path for save video cut thum

if(getFileExtension($_FILES['videoUpload']['name'])!="flv"){
$tempUpload=$_SERVER['DOCUMENT_ROOT']."/totalbhakti/files/video/temp/".$newFileName.'.'.getFileExtension($_FILES['videoUpload']['name']);
}else{
$tempUpload=$destinationVideo;

}

function create_thumbnail($source,$destination,$thum_width,$thum_height){
//echo $source.'<br>';
$size=getimagesize($source);
//echo $size[0];
$width=$size[0];
echo 'width-'.$width;
$height=$size[1];
$x=0;
$y=0;
/*if($width>$height){
$x=ceil(($width-$height)/2);
$width=$height;
}if($width<$height){
$x=ceil(($height-$width)/2);
$height=$width;
}*/
echo '<br>'.$thum_width.'--'.$thum_height;
$new_image=imagecreatetruecolor($thum_width,$thum_height)or die('Cannot Initialize new GD image stream');
$extension=getExtension($source);
echo '<br>Exten:-'.$extension.'<br>';

if($extension=='jpg'||$extension=='jpeg'){

$image=imagecreatefromjpeg($source);
}

imagecopyresampled($new_image,$image,0,0,$x,$y,$thum_width,$thum_height,$width,$height);

if($extension=='jpg'||$extension=='jpeg'){

imagejpeg($new_image,$destination,40);

}

}

function getExtension($name){

return('jpg');
}



if(move_uploaded_file($_FILES['videoUpload']['tmp_name'],$tempUpload)){


shell_exec("ffmpeg -i $tempUpload -ar 22050 -ab 32 -f flv -s 450×370 $destinationVideo");

$img=shell_exec("ffmpeg -i $destinationVideo -f mjpeg -t 0.050 $destinationThum");

create_thumbnail($destinationThum,$destinationFirstThum,124,100);

$mov = new ffmpeg_movie($destinationVideo);
$totTime=ceil($mov->getDuration());
$fps=$mov->getFrameRate();
echo '<div style="height:150px; display:block; border:#006600 solid 2px; height:20px; background-color:#66CC99 ">
Your Video Information<br>Uploaded Video Length:-'.($totTime/60).'</div><br>';
}else{
echo 'not uploaded';
}
}

if ($_FILES['videoUpload']['error'] > 0) {
echo '<p class="error">The file could not be uploaded because: <strong>';
switch ($_FILES['videoUpload']['error']) {

case 1:
echo 'The file exceeds the upload_max_filesize setting in php.ini.';
break;
case 2:

echo 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
break;
case 3:

echo 'The file was only partially uploaded.';
break;

case 4:
echo 'No file was uploaded.';
break;

case 6:
echo 'No temporary folder was available.';
break;

case 7:
echo 'Unable to write to the disk.';
break;

case 8:
echo 'File upload stopped.';
break;

default:
echo 'A system error occurred.'.$_FILES['videoUpload']['error'];
break;
}
echo '</strong></p>';
}
}

?>
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="">

<table width="688" border="1" align="center" cellpadding="5" cellspacing="5">
<tr>
<td width="300"><div align="left"><strong>Select Video for Upload </strong></div></td>
<td width="196"><div align="center">

<label>
<input name="vfile" type="file" id="vfile" />
<input name="submitted" type="hidden" id="submitted" value="true" />
</label>

</div></td>
</tr>
<tr>
<td><div align="left"><strong>Enter Title for Video </strong></div></td>
<td>
<label>
<input name="vTitle" type="text" id="vTitle" size="40" />
</label>

</td>
</tr>
<tr>
<td>
<label>
<input type="submit" name="Submit" value="Submit" />
</label>
</td>

<td>&nbsp;</td>
</tr>
</table>
</form>

Tuesday, December 15, 2009

Navigation Using Mysql Query in php


If u want to navigate record without passing id array or other value sting following code will help u to move forward and backword on basis of present display id.

<div>
<?php
$selPre="select id from table where id<$imgId  and status='Yes' order by id Desc";
$preRs=mysql_query($selPre,$dbc)or die('error in previous id : '.mysql_error());
$preId=mysql_fetch_array($preRs);
if(mysql_num_rows($preRs)>0){
?>
 <a title="Previous" href="Selffilename.php?Id=<?php echo $preId["id"];?>" class="no-underline">
<span style="color: rgb(105, 105, 105); font-weight: bold;">PREVIOUS</span>
<span class="paginate-first">&lt;&lt;</span>
</a>
</div>
<div align="right" style="width:50%; float:left">
<?php
}
$selNxt="select id from table where id>$Id and status='Yes' order by id ASC";
$NxtRs=mysql_query($selNxt,$dbc)or die('error in previous id : '.mysql_error());
$nxtId=mysql_fetch_array($NxtRs);
if(mysql_num_rows($NxtRs)>0){
?>
<a title="Last Page" href="Selffilename.php?Id=<?php echo $nxtId["id"];?>" class="no-underline">
<span class="paginate-last">&gt;&gt;</span>
<span style="color: rgb(105, 105, 105); font-weight: bold;">NEXT</span>
</a>
<?php
}?>

Sunday, December 13, 2009

Fetch record in table format using Ajax,PHP


This is example for fetch email address group by and count them and display every result in table format. this example is apply for all type of fetching record in display in table format using ajax and php.

//************************** Server site fetchEmail.php for fetch record and return in table format******************


<?php

  header("Cache-Control: no-cache, must-revalidate" );
  header("Pragma: no-cache" );
  header("Content-Type: text/html; charset=utf-8");

$dbc=mysql_connect(HOSTNAME,USERNAME,PASSWORD) or die('There is error to connect to server:-'.mysqli_connect_error());
  $db_selected = mysql_select_db(DATABASE,$dbc);

  $groupName=$_GET['group'];

  function emailCount($emailId){
  $EmailArray=explode(",",$emailId);
  $totemail=count($EmailArray);
  return($totemail);
  }
  function format($txt){ //Function for RIght syntex for html format
  $txt=str_replace(',','<br>',$txt);
  return($txt);

  }

  $selectGroupRS="select group_name,emailId from emailgroup where group_name='$groupName'  ";
  $result1=mysql_query($selectGroupRS,$dbc) or die('error in group:-'.mysql_error());
  echo"<table width=\"90%\" cellpadding=\"0\" cellspacing=\"0\" border=\"1\">
  <tr>
  <td width=\"15%\" align=\"center\"><strong>Group Name</strong></td>
  <td align=\"center\"><strong>Email Id's</strong></td>
  <td align=\"center\"><strong>Count of Email Id's</strong></td>

  </tr>";
  while($row1=mysql_fetch_row($result1)){
  $name=$row1[0];
  $email.=','.$row1[1];

  }
  echo"
  <tr>";
  echo "<td align=\"center\">".$name."</td>";
  echo "<td ><div style=\"height:300px; overflow:scroll\">".format($email)."</div></td>";
  echo "<td align=\"center\">".emailCount($email)."</td>";
  echo"</tr>";
  echo "</table>";
  ?>


//****************************** End of fetchEmail.php***************************************************************



//************************Php file where record display****************************************

  <script language="javascript">

  function getXmlHttpRequestObject(){
  //alert('in xmlhttp');
  if(window.XMLHttpRequest){
  return new XMLHttpRequest();
  }else if(window.ActiveXObject){
  return new ActiveXObject("Microsoft.XMLHTTP");
  }else {
  alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
  }

  }

  var searchemail = getXmlHttpRequestObject();

  function searchResult(){

  //alert('on search');

  //alert('in search');
  var groupName=escape(document.getElementById('searchgroup').value);
  //alert(groupName);
  searchemail.open("GET",'fetchEmail.php?group=' + groupName,true);
  searchemail.onreadystatechange=SearchEmailHandler;
  searchemail.send(null);



  }

  function SearchEmailHandler(){

  if(searchemail.readyState==4 || searchemail.readyState=="complete"){
  //alert('in hand');
document.getElementById('fetchId').innerHTML=searchemail.responseText;
  
  
  }
  }


  </script>


<strong> List of All group with Email Id</strong>
  <br />
  <select id="searchgroup">
  <?php


  $dbc=mysql_connect(HOSTNAME,USERNAME,PASSWORD) or die('There is error to connect to server:-'.mysqli_connect_error());
  $db_selected = mysql_select_db(DATABASE,$dbc);



  $selectGroup="select group_name from emailgroup group by group_name";
  $result=mysql_query($selectGroup,$dbc) or die('error in group:-'.mysql_error());
  while($row=mysql_fetch_row($result)){
  echo'<option>'.$row[0].'</option>';

  }

  ?>


</select>
  <input  type="button" value="search" onclick="searchResult();" />
  <br />



  <div id="fetchId"></div>


  //************************Php File End***************************************************


Wednesday, December 9, 2009

Place multiple submit form on page

Fetch all record form image table and create form as per record on a single page. and submit form on button. With the following example code u can place multiple submit form on single page and submit single form according to button submit. display form with pagination.
 This example will help in understand pagination in php.


<!--
  Javascript Function for submit Form

  -->

  <script language="javascript">


  function function1(theForm){

  theForm.submit();

  }
  </script>


<?php



$dbc=mysql_connect('hostname','username','password');
  mysql_select_db('databasename',$dbc);

  $start=$_REQUEST['startPostion'];
  $display=20;

  if(isset($start)&&is_numeric($start)){
  $startNo=trim($start);
  }else{
  $startNo=0;
  }

  /*

  Get TotalNo of Images in images table for calculate the no of pages

  */


  $selCount="select count(id) from images where status='Ok'";
  $countRs=mysql_query($selCount,$dbc);

  $count=mysql_fetch_row($countRs);

  if($count[0]>$display){

  $pages=ceil($count[0]/$display);

  }else{

  $pages=1;
  }





if($pages>1){
  $currentPage=($startNo/$display)+1;

  $stPageNo=$currentPage-4;
  $endPageNo=(($currentPage+5)<$pages)? $currentPage+5 : $pages;
  if($currentPage!=1){
  echo '<a href="imageManager.php?startPostion='.($startNo-$display).'"><span class="nextpre">Previous&nbsp;</span></a>';
  }

  for($i=$stPageNo;$i<=$endPageNo;$i++){
  if($i>0){
  if($i==$currentPage){

  echo '<span class="currpagingNo">'.$i.' '.'</span>';
  }else{
  echo '<a href="imageManager.php?startPostion='.($display*($i-1)).'"><span class="pagingNo">'.$i.' '.'</span></a>';
  }
  }



  } echo '<span class="nextpre">...of '.$pages.'</span>';
  if($currentPage!=$pages){
  echo '<a href="wallpaperManager.php?startPostion='.($startNo+$display).'"><span class="nextpre">Next</span></a>';
  }
  }
  ?>

  <table border="1" cellspacing="0" cellpadding="0">
  <tr>
  <td width="360" align="center"><span class="style1">Wallpaper Detail </span> </td>
  <td width="72" align="center"><span class="style1">Added Date</span> </td>
  <td align="center"><span class="style1">Action </span></td>
  </tr>
  <?php
  $selImage="select * from images where status='Ok' limit $startNo,$display";
  $imageResult=mysql_query($selImage,$dbc);

  while($row=mysql_fetch_row($imageResult)){
  ?>
  <tr>
  <td height="150" valign="top" >
  <table width="340" border="1" cellspacing="0" cellpadding="0">
  <form id="form1" name="forms<?php echo $row[0]; ?>" method="post" action="imageManager.php">
  <tr>
  <td width="80"> <span class="style1">Title</span> </td>
  <td width="254">
  <input type="text" name="photo_title" size="50" value="<?php echo $row[1]; ?>">  <input type="hidden" name="ask" value="activate" >
  </td>
  </tr>
  <tr>
  <td width="80"> <span class="style1">Description</span> </td>
  <td width="254">
  <input type="text" name="photo_desi" size="50" value="<?php echo $row[2]; ?>">  <input type="hidden" name="ask" value="activate" >
  </td>
  </tr>

  </form>
  </table>

  </td>

  <td align="center"><span id="textstyle"><?php  echo $row[3]; ?></span></td>
  <td align="center" width="38" valign="middle"><img src="../../All Users/Documents/images/yes.png" border="0" title="Activate" onclick="function1(forms<?php echo $row[0]; ?>)"></a></td>

  </tr>

  <?php
  }
  ?>
  </table>

Monday, November 30, 2009

Paypal Pro use in php for payment gateway

Implement payment gateway in your site using paypal pro account. use below script by changing some variable and value






<?php



$paymentType = $this->input->post('paymentType');

  $creditCardType= $this->input->post('creditCardType'); //Contain information about card type

  $creditCardNumber = $this->input->post('creditCardNumber'); //contain information about no of card

  $expDateMonth = $this->input->post('expDateMonth'); //contain information about expire month of card

  $expDateYear = $this->input->post('expDateYear'); //contain information about expire year of card

  $cvv2Number = $this->input->post('cvv2Number'); //contain security code of card which is card dependent

  $firstname =$this->input->post('user_fname'); //customer first name

  $lastname= $this->input->post('user_lname'); //customer last name

  $addr=   $this->input->post('address'); //customer postal address 1

  $addr1=   $this->input->post('address1'); //customer postal address 2

  $city =   $this->input->post('city'); //customer postal address city

  $state =   $this->input->post('state');


$zipcode =   $this->input->post('user_postalcode'); //customer postal code

  $phone =   $this->input->post('phone'); //customer phone no

  $email=   $this->input->post('user_email'); //customer Email address

  $package=   $this->input->post('pack'); //customer pack information if needed

  $a=explode('-',$package);

  $cochid = $a[0];

  $amount = $a[1]; //amount to pay

  $address1=$addr.$addr1;

 

 

 

 

  define('API_USERNAME', 'paypal_pro_user name');

  define('API_PASSWORD', 'paypal_pro_user password');

  define('API_SIGNATURE', 'paypal given id');

  define('API_ENDPOINT', 'https://api-3t.sandbox.paypal.com/nvp');

  define('USE_PROXY',FALSE);

  define('PROXY_HOST', '127.0.0.1');

  define('PROXY_PORT', '808');

  define('PAYPAL_URL', 'https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=');

  define('VERSION', '53.0');




session_start();


/**

  * hash_call: Function to perform the API call to PayPal using API signature

  * @methodName is name of API  method.

  * @nvpStr is nvp string.

  * returns an associtive array containing the response from the server.

  */




function hash_call($methodName,$nvpStr)

  {

  ini_set('max_execution_time', 300);

  //declaring of global variables

 

  global $API_Endpoint,$version,$API_UserName,$API_Password,$API_Signature,$nvp_Header;

  $API_UserName=API_USERNAME;




$API_Password=API_PASSWORD;




$API_Signature=API_SIGNATURE;




$API_Endpoint =API_ENDPOINT;




$version=VERSION;

  

  //setting the curl parameters.

  $ch = curl_init();

 

  curl_setopt($ch, CURLOPT_URL,$API_Endpoint);

  curl_setopt($ch, CURLOPT_VERBOSE, 1);

 

  //turning off the server and peer verification(TrustManager Concept).

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

 

  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

 

  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

  curl_setopt($ch, CURLOPT_POST, 1);

  //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.

  //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php

 

  if(USE_PROXY)

  //echo CURLOPT_PROXY;

  curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);

 

 

  //NVPRequest for submitting to server

  //echo $version;

  $nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr;

 

  //setting the nvpreq as POST FIELD to curl

  //CURLOPT_POSTFIELDS;

  curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);

 

  //getting response from server

  $response = curl_exec($ch);

  // echo gettype($response);

  //echo "lkj"; die;

  //convrting NVPResponse to an Associative Array

  $nvpResArray=deformatNVP($response);

 

  $nvpReqArray=deformatNVP($nvpreq);

  //print_r($nvpReqArray);

  $_SESSION['nvpReqArray']=$nvpReqArray;

 

  if (curl_errno($ch)) {

 

  // moving to display page to display curl errors

  echo $_SESSION['curl_error_no']=curl_errno($ch) ;

  echo $_SESSION['curl_error_msg']=curl_error($ch); die;

 

  $location = "APIError.php";

  header("Location: $location");

  } else {

  //closing the curl

  curl_close($ch);

  }

 

  return $nvpResArray;

  }


/** This function will take NVPString and convert it to an Associative Array and it will decode the response.

  * It is usefull to search for a particular key and displaying arrays.

  * @nvpstr is NVPString.

  * @nvpArray is Associative Array.

  */


function deformatNVP($nvpstr)

  {

 

  $intial=0;

  $nvpArray = array();

 

 

  while(strlen($nvpstr)){

  //postion of Key

  $keypos= strpos($nvpstr,'=');

  //position of value

  $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

 

  /*getting the Key and Value values and storing in a Associative Array*/

  $keyval=substr($nvpstr,$intial,$keypos);

  $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);

  //decoding the respose

  $nvpArray[urldecode($keyval)] =urldecode( $valval);

  $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));

  }

  return $nvpArray;

  }

 

  $paymentType =urlencode( $this->input->post('paymentType'));

  $firstname =urlencode($firstname);

  $lastName =urlencode($lastname);

  $creditCardType =urlencode($creditCardType);

  $creditCardNumber = urlencode($creditCardNumber);

  $expDateMonth =urlencode( $this->input->post('expDateMonth'));

 

  // Month must be padded with leading zero

  $padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);

 

  $expDateYear =urlencode( $this->input->post('expDateYear'));

  $cvv2Number = urlencode($this->input->post('cvv2Number'));

  $address1 = urlencode($address1);

  //$address2 = urlencode($this->input->post('address2'));

  $city = urlencode($city);

  $state =urlencode($state);

  $zipcode = urlencode($zipcode);

  $amount = urlencode($amount);

  //$currencyCode=urlencode($_POST['currency']);

  $currencyCode="USD";

  $paymentType=urlencode($this->input->post('paymentType'));

  $nvpstr="&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstname&LASTNAME=$lastname&STREET=$address1&CITY=$city&STATE=$state".

  "&ZIP=$zipcode&COUNTRYCODE=US&CURRENCYCODE=$currencyCode";

  //print_r($nvpstr);

  /* Make the API call to PayPal, using API signature.

  The API response is stored in an associative array called $resArray */

  $resArray=hash_call("doDirectPayment",$nvpstr);

  ///print_r($resArray);

  /* Display the API response back to the browser.

  If the response from PayPal was a success, display the response parameters'

  If the response was an error, display the errors received using APIError.php.

  */

  $this->view->data12=$resArray;

 

  /*$uid= $this->session->userdata('user_login_id');

  $q=$this->db->query("select email from user_account where uid=$uid");

  $row=$q->result_array();

  $date1=date('d/m/y');


//$data=array('id'=>$id,'user_name'=>$firstName,'Payment'=>$amount,'date'=>$date1);

  mysql_query("insert into balboa_transaction('uid','user_name','Payment','date','email')values($uid,'$firstName','$amount','$date1','$row[0]['email']')");

  //$this->db->insert('balboa_transaction',$data);

  //   $this->db->query("insert into balboa_transaction ('id','user_name','Payment','date')values('$id','".$firstName."','".$amount."','$date1')"); die;*/

  $ack = strtoupper($resArray["ACK"]);

  //echo $ack;

  if($ack=='FAILURE'){

  ///$this->load->view('home/thanks');

  $this->load->view('errorpage');

  }

  else{

  $this->load->view('success page');

  }

?>

Friday, November 27, 2009

Dynamics Video Rss Feed in php

To generate dynamics video RSS Feed we require 4 File

  1. Database connection file(db.php)
  2. Linking Html file(rss.html)
  3. rssVideo.php file for generate rss feed xml file
  4. htaccess file for url rewriting

first file:-db.php

DEFINE('HOSTNAME','localhost');

DEFINE('USERNAME','root');
DEFINE('PASSWORD','');
DEFINE('DATABASE','tbc_main');

//End of Constraint Declaration.

/*

Function for DataBase Connection

$dbc variable for database connection

*/


$dbc=mysql_connect(HOSTNAME,USERNAME,PASSWORD) or die('There is error to connect to server:-'.mysqli_connect_error());
$db_selected = mysql_select_db(DATABASE,$dbc);


function getUserName($id,$dbc){
$getUserName="select user_name,user_id from users where user_id=$id";
$userNameResult=mysql_query($getUserName,$dbc)or die('Error in get User Name'.mysql_error());
$name=mysql_fetch_array($userNameResult);
return($name[0]);

}

function getVideoName($id){
return(substr(md5($id),0,15));
}




second file : rss.html

<html>

<ul>

<li><a href="http://www.sitename.com/rss/newadded.html">

<div style="float:left; width:100px; height:20px;">New Video </div>
</a></li>

<li><a href="http://www.sitename.com/rss/mostview.html">

<div style="float:left; width:100px; height:20px;">Most view </div>
</a></li>

<?php

include_once(db.php);

$selVideoCat="select video_category_id,video_category_name from video_category where video_category_status='Yes'";

$catRs=mysql_query($selVideoCat,$dbc);
while($row=mysql_fetch_array($catRs)){
echo '<li">
'.$row["video_category_name"].'</a>
<a href="http://sitename.com/rss/guru/'.$row["video_category_id"].'.html"></a></li>';

?>

</ul>

</html>



third file:rssvideo.php

<?php

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=iso-8859-1");



include_once('db.php');


$cat=$_REQUEST['cate']; //get which type of video require
$value=$_REQUEST['value'];//value to match for fetching video


switch($cat){
case 'newadded':
$where="where video_status='Ok' order by video_id DESC limit 0,50";
break;
case 'mostview':
$where="where video_status='Ok' order by total_views DESC limit 0,50";
break;
case'cate':
$where="where video_status='Ok' and video_category_id=$value order by video_id DESC limit 0,500";
break;
}



if(isset($cat)){
$rss="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
$rss .= '<!-- Generated on ' . date('r') . ' -->' . "\n";
$rss .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' . "\n";
$rss .= ' <channel>' . "\n";
$rss .= ' <atom:link href="http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'" rel="self" type="application/rss+xml" />' . "\n";
$rss .= ' <title>sitename Videos </title>' . "\n";
$rss .= ' <link>http://www.sitename.com/videoCategory.php</link>' . "\n";
$rss .= ' <description>sitename is the best place to one with great guru pravchan and their bhajan</description>' . "\n";
$rss .= ' <language>en-us </language>' . "\n";

$sql="select * from video ".$where;

$result=mysql_query($sql,$dbc) or die('Feed Error:-'.mysql_error());
while($row=mysql_fetch_array($result)){
$rss.="<item>\n";


$rss.="<title>".$row['video_title']."</title>\n";
$rss.="<link>http://www.sitename.com/viewVideo.php?video_id=".$row['video_id']."</link>\n";//page path (link) to view that perticular video on website
$rss.="<description><![CDATA[
<img src=\"http://www.sitename.com/files/videos/thumbnails/".getVideoName($row['video_id']).'S.jpg'."\" align=\"right\" border=\"0\" width=\"120\" height=\"90\" vspace=\"4\" hspace=\"4\" />// video thum location on server
<p>".$row['video_title']."</p>
<p>

".$row['video_tags']."<br/>
Added:".$row['date_added']."<br/>
</p>
]]></description>\n";

$rss.="<guid isPermaLink=\"true\">http://www.sitename.com/viewVideo.php?video_id=".$row['video_id']."</guid>\n";
$rss.="<pubDate>".gmdate('D, d M Y H:i:s \G\M\T',$row['date_added'])."</pubDate>\n"; //video add date according to rss rules

$rss.="</item>\r";
}


$rss.="</channel>\r";
$rss.="</rss>";

echo $rss;

}



?>




forth file : .htaccess

Options +FollowSymLinks

RewriteEngine on

RewriteRule ^(.*)/([0-9]+)\.html$ rssvideo.php?cate=$1&value=$2 [NC,L]

RewriteRule ^(.*)\.html$ rssvideo.php?cate=$1 [NC,L]



Tuesday, November 24, 2009

Download File in php

code for help to download any file using php script.
just pass complete path or pass as variable to code it will download that file to user desktop.

// $_REQUEST ['getfile'] get file name with path which want to download


if ($_REQUEST ['getfile']){
$file = $_REQUEST ['getfile'];

//$file is a variable that hold file path and name value.
}

$save_as_name = basename($file); //$save_as_name is the name by which wile will save to desktop here we take original file name


ini_set('session.cache_limiter', '');
header('Expires: Thu, 19 Nov 1981 08:52:00 GMT');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header("Content-Type: application/octet-stream"); //defile that we work with file
header("Content-Disposition: disposition-type=attachment; filename=\"$save_as_name\"");

readfile($file);

?>

Fetch record export to excel in csv fromat in php

this example will help to fetch record from database and export it to excel file in csv format in php.


<?php

class database

{
private $db_handle;
private $user_name;
private $password;
private $data_base;
private $host_name;
private $sql;
private $results;

function __construct($host="localhost",$user,$passwd)

{
$this->db_handle = mysql_connect($host,$user,$passwd);
}

function dbSelect($db)

{
$this->data_base = $db;
if(!mysql_select_db($this->data_base, $this->db_handle))
{
error_log(mysql_error(), 3, "/phplog.err");
die("Error connecting to Database");
}
}

function executeSql($sql_stmt)
{
$this->sql = $sql_stmt;
$this->result = mysql_query($this->sql);
}
function returnResults()
{
return $this->result;
}
}


$dbc=mysql_connect('localhost','username','password');
$db_selected =mysql_select_db('databasename',$dbc);

$user = "username";

$passwd = "password";
$db = "database name";

$videoCount="select * from users ";



$dbObject = new database($host,$user,$passwd);

$dbObject->dbSelect($db);
$dbObject->executeSql($videoCount);

$res = $dbObject->returnResults();

$file = "excel.csv";

$nameStr = "";

function getUserName($id,$dbc){


$getUserName="select user_id,user_name,dept from users where user_id=$id";
$userNameResult=mysql_query($getUserName,$dbc)or ('Error in get User Name'.mysql_error());
$name=mysql_fetch_row($userNameResult);

return($name);

}


$Title.=$Title."User Name".","."Department"."\n";

while($record = mysql_fetch_object($res))

{

$vTitle = $record->video_title;
$usrName=getUserName($record->user_id,$dbc);



$nameStr = $nameStr.$vTitle.",".$usrName[0].",".$usrName[1]."\n";

}

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=$file");
header("Cache-Control: public");
header("Content-length: ".strlen($nameStr)); // tells file size
header("Pragma: no-cache");
header("Expires: 0");
echo $Title;
echo $nameStr;

?>

Monday, November 23, 2009

Text Slide show in php using javascript function

To show text/field value comes database as slide show in php.
this will happen by using javascript function embed with php code.
this example will help in fetching record and display as slide show


<style type="text/css">

#featureBlog{

color:#006699; font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; width:345px;padding-top:5px;
}
#featureBlogDesc{
color:#000000; font-size:10px; font-family:Verdana, Arial, Helvetica, sans-serif; width:345px;padding-top:5px;
}

</style>




<?php


echo'


<SCRIPT type="text/javascript">

var quotations = new Array();';





$i=0;

$sql="select title,link,desc from table";

$rs=mysql_query($sql,$dbc)or die('Error in fetching title:-'.mysql_error());

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



echo 'quotations['.$i.']="<a href=\".$row["link"].'\"><span id=featureBlog>'.ucfirst($row["title"]).'<br><span id=featureBlogDesc>'.ucfirst($row["desc"]).'</span></a>";';

$i++;



}



echo'

function display()

{

a=Math.floor(Math.random()*quotations.length)

document.getElementById(\'quotation\').innerHTML=quotations[a]

setTimeout("display()",5000)

}

</SCRIPT>

';



?>

<div id="quotation" style="position:absolute; width:200; height:102; left:150; top:150; border-style:solid; border-width:1px; border-color:#000000;">

<SCRIPT type="text/javascript">display()</SCRIPT>

</div>

Friday, November 20, 2009

Date Validation in php

To check that enter date is in valid format in php by using validCurrentDate() function


function validCurrentDate($date){
//replace / with - in the date
$date = strtr($date,'/','-');
//explode the date into date,month and year

$datearr = explode('-', $date);

//count that there are 3 elements in the array

if(count($datearr) == 3){
list($d, $m, $y) = $datearr;

/*checkdate - check whether the date is valid. strtotime - Parse about any English textual
datetime description into a Unix timestamp. Thus, it restricts any input before 1901 and after 2038, i.e., it invalidate outrange dates like 01-01-2500. preg_match - match the pattern*/

if(checkdate($m, $d, $y) && strtotime("$y-$m-$d") && preg_match('#\b\d{2}[/-]\d{2}[/-]\d{4}\b#', "$d-$m-$y"))
{
/*echo "valid date";*/
return TRUE;
}
else {
/*echo "invalid date";*/
return FALSE;
}
}
else {
/*echo "invalid date";*/
return FALSE;
}
/*echo "invalid date";*/
return FALSE;
}

?>

Wednesday, November 18, 2009

Share Image (Email) to your friend using Bcc email address in php

Send Image as news letter or share image to all ur friend of the site in php though email using BCC address.

This image form and take user email id and verify that email id using java script code. u can send mail to more then one friend. u can save reciver id in your database

Image Form File

<style type="text/css">

#emailtext{
font-family:Verdana;
font-size:14px;
color:#282828;

}

.txtBox {
border:#333333 solid 1px;
}
.imgBox {
border:#FF9900 solid 1px;
}
</style>

<script language="javascript">


function checkFieldEmpty(textField,mess){

var textFieldValue=textField.value;

if(textField=="" || textFieldValue.length==0){// && textField=" "){

alert(mess)

return false;

}else{

//return true;

return "";
}

}


// Javascript Email Verification function

function chkEmail(elem, errorshow){

var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){

return "";
}else{
alert(errorshow);

return false;
}
}

function FormSubmit(theForm){

//alert("in submit");

var reason="";



reason += checkFieldEmpty(document.getElementById('senderName'),'Enter Your Name');
reason += checkFieldEmpty(document.getElementById('senderEmail'),'Enter Your Email');
reason += checkFieldEmpty(document.getElementById('recEmail'),'Enter Email To send');
reason += chkEmail(document.getElementById('senderEmail'),'Enter Your Email correct');
//reason += chkEmail(document.getElementById('recEmail'),'Enter Send To Email correct');


if(reason!=""){
alert("Some Field Need To Fill");
}else{
theForm.submit();
}
}



</script>

<table width="700" border="0" align="center" cellpadding="0" cellspacing="0">

<tr>
<td align="center" class="imgBox"><img src="<?php echo getPath($Id,$dbc); ?> " height="600" width="700"></td>
</tr>
<tr>
<td>
<form action="sendShareImage.php" method="post" name="shareForm">
<table width="400" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td><span id="emailtext">Your Name</span></td>
</tr>
<tr>
<td><input type="text" name="senderName" id="senderName" size="50" class="txtBox"><input type="hidden" name="id" value="<?php echo $Id;?>"></td>
</tr>
<tr>
<td><span id="emailtext">Your E-mail address</span></td>
</tr>
<tr>

<td><input type="text" name="senderEmail" id="senderEmail" size="50" class="txtBox"></td>
</tr>
<tr>
<td><span id="emailtext">Your Message:-</span></td>
</tr>
<tr>

<td><textarea name="sendermsg" id="sendermsg" cols="50" rows="5" ></textarea></td>
</tr>

<tr>
<td><span id="emailtext">Recipient E-mail address</span></td>
</tr>
<tr>

<td>
<input type="text" name="recEmail" id="recEmail" size="50" class="txtBox"><br />

(use , for multiple emailId)</td>
</tr>
<tr>

<td><strong>Bcc.</strong><br /><input type="text" name="bccsenderEmail" id="bccsenderEmail" size="50" class="txtBox"></td>
</tr>
<tr>
<tr>
<td>&nbsp;</td>
<td align="right" valign="bottom"><img src="images/send.gif" onClick="FormSubmit(shareForm)" />&nbsp;&nbsp;&nbsp;</td>
</tr>
</table>
</form>

</td>
</tr>
</table>

//End of file of image form

File of mail send start

<style type="text/css">

#send{
display:block;
background-color:#00CC66;
color:#FFFFFF;
text-align:center;
}
#fail{
display:block;
background-color:#FF3300;
color:#FFFFFF;
text-align:center;
}
#tbc{
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
font-weight:bold;
color:#000060;
}
</style>

<?php

$dbc=mysql_connect('localhost','root','');
mysql_select_db(db_name,$dbc);

set_time_limit(0);

$Id=$_REQUEST['id'];

$senderName=$_REQUEST['senderName'];
$sender=$_REQUEST['senderEmail'];
$receiver=$_REQUEST['recEmail'];
$senderMsg=$_REQUEST['sendermsg'];
$bccid=$_REQUEST['bccsenderEmail'];

//**********************Function to get Image Path*******************

function getPath($imgId,$dbc){

$selPath="select path,id from wallpaper where id=$imgId";
$Result=mysql_query($selPath,$dbc) or die('Error in fetch Thum Image:-'.mysql_error());
$row=mysql_fetch_array($Result);
return($row[0]);

}

//**********************End of Image Path Function********************

$sub="Image Sharing";

$headers = "From: $sender\r\n";

$headers .= "Content-type: text/html\r\n";
$headers .= "Bcc:$bccid"; //Send any bcc address

$imgPath = getPath($Id,$dbc);

$imgPath = str_replace( ' ', '%20', $imgPath );
//echo $imgPath;

$bodyTxt;

$bodyTxt='

<html>

<body>

<p>Dear friend of '.$senderName.',</p>

<img src="http://www.servername.com/wallpaper/'.$imgPath.'" height="800" width="1000"><br>

<p>
'.$senderMsg.'
</p>


<p>Thank you!</p>

</body>

</html>';

if(mail($receiver,$sub,$bodyTxt,$headers)){



$maxId="select max(id) from shareimg";
$res=mysql_query($maxId,$dbc);
$rs=mysql_fetch_row($res);
$shreId=$rs[0];
$newId=$shreId+1;
//echo $newId;
$saveId="insert into shareimg values($newId,'$senderName','$sender','$receiver','y')";
if(mysql_query($saveId,$dbc)){
echo'<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" height="81"><img src="images/successfulHeader.png" width="100%"></td>

</tr>
<tr>
<td colspan="2" valign="top"><span id="success">&nbsp;&nbsp;Successful !</span><br>
<span id="invitetbc">&nbsp;&nbsp;&nbsp;&nbsp;Your Wallpaper has been Sent</span></td>

</tr>
<tr>
<td width="158" height="185" align="left">&nbsp;&nbsp;&nbsp;&nbsp;<img src="'.getPath($Id,$dbc).'" width="140" /></td>
<td width="342" align="left" valign="middle"><span id="senderName">'.$senderName.'</span><br />
<span id="invitetbc">Your Desktop Wallpaper has been Sent to</span><br /><span id="tbc">'. $receiver.'</span></td>
</tr>
<tr>
<td colspan="2"><i><span id="invitetbc">&nbsp;&nbsp;&nbsp;&nbsp;We Invite you to:</span></i></td>

</tr>
<tr>
<td valign="middle" align="center">&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/sideimage.jpg" /></td>
<td>
<span id="tbc">

</span>


</td>
</tr>
</table>';

}

}else{
echo '<span id="send">Sending Fail</div>';
}

?>