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:-





Wednesday, December 23, 2009

Send Mail With Attachment in php

 If u want to send a email using php mail function with attachment a zip or any file following code will help u to send it.

$fileatt = ""; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = ""; // Filename that will be used for the file as the attachment



$to = 'youraddress@example.com';                          //define the receiver of the email 

$subject = 'Test email with attachment';                   //define the subject of the email 

$random_hash = md5(date('r', time()));                 //create a boundary string. It must be unique use md5 function for it.


$random_hash = md5(date('r', time()));                 //create a boundary string. It must be unique use md5 function for it.
$mime_boundary = "==Multipart_Boundary_x{$random_hash}x";
$headers = "From: support@campus100.com\r\nReply-To: support@campus100.com";   //define the headers we want passed. Note that they are separated with \r\n

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";   //add boundary string and mime type specification
//$headers .= "Content-type: text/html\r\n";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks

$file = fopen($destination,'rb');
$data = fread($file,filesize($destination));
fclose($file);
$data = chunk_split(base64_encode($data));
//define the body of the message.

//ob_start();         //Turn on output buffering
$fileatt_type=$_FILES['attachFile']['type'];

$textTosend='.nl2br($body).';

$textTosend .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$textTosend . "\n\n";



$textTosend .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data. "\n\n" .
"--{$mime_boundary}\n";
unset($data);
unset($file);
unset($destination);
unset($fileatt_type);
unset($fileatt_name);

if(mail( $to, $subject, $message, $headers ) ){

echo "Mail sent" ;

}else{
   echo "Mail send Fail";
}

?>




Monday, December 21, 2009

change picture each time web page loads

Image can change on web page, you know...like showing different christmas pictures when web page loads on a users computer. I want them to see a different picture each time in php page.


$file=array();

$file[0]="file1.gif";
$file[1]="file2.gif";
$file[2]="file3.gif";
$file[3]="file4.gif";
$file[4]="file5.gif";
$file[5]="file6.gif";
$file[6]="file7.gif";
$file[7]="file8.gif";

$fileno=rand(0,7);

$filename=$file[$fileno];

echo '<img src="$filename" >';

?>

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>

Thursday, December 17, 2009

Fetch Record form search string in php

fetch unique  row set passing query sting as parameter and search by its all word of string one by one merge all record and find unique row set and display them.

$dbc=mysql_query('host','username','pass');
mysql_select_db('databasename',$dbc);

$getTag=$_REQUEST['tags'];  //searching string

$arrFirst=array();
$arrSecond=array();


$queryExecute="select * from music where name like('%".$getTag."%') and status='y' or singer like('%".$getTag."%') and status='y' or language like('%".$getTag."%') and status='y' or main_cate like('%".$getTag."%') and status='y' or genure like('%".$getTag."%') and status='y' or placename like('%".$getTag."%') and status='y' or other_tag like ('%".$getTag."%') and status='y'";


$queryResult=mysql_query($queryExecute,$dbc);

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

$arrFirst=array_merge($arrFirst,array($row[0]));

}

$findKeyTag=explode(" ",$getTag);

for($i=0;$i
$executequery="select * from music where name like('%".$findKeyTag[$i]."%') and status='y' or language='$findKeyTag[$i]' and status='y' or main_cate='$findKeyTag[$i]' and status='y' or guru='$findKeyTag[$i]' and status='y' or genure='$findKeyTag[$i]' and status='y' or lordname='$findKeyTag[$i]' and status='y' or other_tag like('%".$findKeyTag[$i]."%') and status='y'";

$result=mysql_query($executequery,$dbc);
while($row=mysql_fetch_array($result)){

$arrSecond=array_merge($arrSecond,array($row[0]));

}


}

$arrFinal1=array();
$arrFinal=array_unique(array_merge($arrFirst,$arrSecond));

$rsCount=count($arrFinal);
for($i=0;$i<$rsCount;$i++){

$arrFinal1=array_unique(array_merge($arrFinal1,$arrFinal));

}

if($rsCount>$display){

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

}else{
$pages=1;
}



showRecord1($arrFinal1,$getTag,$dbc,$startNo);




function showRecord1($arr,$tag,$dbc,$start,$userId,$url){


$totalRecord=count($arr);
for($i=$start;$i<$start+10;$i++){


if($arr[$i]==""||!$arr[$i]){

     break;
}


$q="select * from music where id=$arr[$i]";
$result=mysql_query($q,$dbc);

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

echo $row["id"];
}

   }

}

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***************************************************


Saturday, December 12, 2009

Edit record using ajax

If u need ajax for edit your display record. it display all record in table row column format that will save (edit) by sending data using ajax javascript function to server php file and get response from server of fail and success and intimate user about the server response.




  //****************************************   Edit ajax file ****************************************

<?php

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

  mysql_select_db('databasename',$dbc);

  $do = $_REQUEST['do'];

  $cateId = $_REQUEST['cateId'];

  switch($do) {

  case 'edit':

  $newTitle=$_REQUEST['ptitle'];

  $newDesc=$_REQUEST['pDesc'];

  $photoId=$_REQUEST['Id'];

 

  if(get_magic_quotes_gpc()) {

  $photoId = $photoId;

  $newTitle=$newTitle;

  $newDesc=$newDesc;

 

  }else{

  $photoId = addslashes($photoId);

  $newTitle = addslashes($newTitle);

  $newDesc = addslashes($newDesc);

  }

  $updatPhoto="update photo_gallery set title='$newTitle',description='$newDesc' where id=$photoId";

  if(mysql_query($updatPhoto,$dbc)or die('Error in update : '.mysql_error())){

  header('Content-Type: text/xml');

  header('Pragma: no-cache');

  echo '<?xml version="1.0" encoding="UTF-8"?>';

  echo '<result>';

  echo 'true';

  echo '</result>';

  }else{

  header('Content-Type: text/xml');

  header('Pragma: no-cache');

  echo '<?xml version="1.0" encoding="UTF-8"?>';

  echo '<result>';

  echo 'false';

  echo '</result>';

  }

 

  break;

  default:

  echo 'Error, invalid action';

  break;

  }

  ?>

//***************************************AJax file end*************************************************


//*********************** Edit html File Start ***********************************************



<script type="text/javascript">

// *************************Ajax call function start***************************************

function editPhotoDetail(Id){

  if (window.XMLHttpRequest) {

  http = new XMLHttpRequest();

  }else if (window.ActiveXObject) {

  http = new ActiveXObject("Microsoft.XMLHTTP");

  }

 

  var handle = Id;

 

  var url = 'ajax.php?';

  //alert(handle);

  var newtitle=document.getElementById('title'+handle).value;

  var newDesc=document.getElementById('desc'+handle).value;

  //alert('title : ' + newtitle+'   '+photoId  );

  // alert('Desc : ' + newDesc);

  if(handle > 0) {

  //alert('call statechange');

  var fullurl = url + 'do=edit&Id=' + encodeURIComponent(handle)+'&ptitle=' + encodeURIComponent(newtitle) + '&pDesc=' + encodeURIComponent(newDesc);

  http.open("POST", fullurl, true);

  http.send(null);

  http.onreadystatechange = statechange_detailchange(handle);

 

  }

 

 

  }


function statechange_detailchange(handle) {

  //alert('in statechange');

  if (http.readyState == 4) {

  var xmlObj = http.responseXML;

  var rs = xmlObj.getElementsByTagName('result').item(0).firstChild.data;

  //    alert('RS '+rs);

  if(rs=="true"){

 

  errorField = document.getElementById('msgbox'+handle);

  errorField.innerHTML = "Photo Record Successfully Update";

  errorField.style.visibility='visible';

  errorField.style.border='#339900  solid 1px';

  errorField.style.background='#FBE3E4';

  errorField.style.color='#339900';

  errorField.style.fontSize='12px';

 

  }else{

  errorField = document.getElementById('msgbox'+handle);

  errorField.innerHTML = "Photo Record Update Fail.";

  errorField.style.visibility='visible';

  errorField.style.border='#FF3333 solid 1px';

  errorField.style.background='#C9FFCA';

  errorField.style.color='#8a1f11';

  errorField.style.fontSize='12px';

 

  }

  }

}

//*********************************Ajax call function end*********************************

  </script>


//********************************Record fetch from database and display for edit

  <table>

  <?php



  $selRec="select * from table";

  $rsRec=mysql_query($selRec,$dbc);

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

  ?>

  <tr>

  <td><input type="radio" name="coverId" value="<?php echo $newId;?>" onclick="setId(<?php echo $newId;?>)"/></td>

  <td height="170px" width="190px" valign="middle" align="center">

 

 

 

  <span id="msgbox<?php echo $row["id"];?>"></span>

  </td>

  <td valign="top"><input type="text" size="30" name="title<?php echo $row["id"];?>" id="title<?php echo $row["id"];?>" value="<?php echo $row["title"];?>"></td>

  <td valign="top"><textarea name="desc<?php echo $newId;?>" id="desc<?php echo $row["id"];?>" rows=7><?php echo $row["descs"];?></textarea>    </td>

  <td align="center"><a onclick="editDetail(<?php echo $row["id"];?>)"><span style="color:#003300; background-color:#C4FFE1; font-family:Arial, Helvetica, sans-serif; font-size:14px;">Edit</span></a></td>

  </tr>

  <?php

  }?>

  </table>

//*****************************Html file end***************************************

Friday, December 11, 2009

Create Contact Us form for website

Create Contact us form where any request fill by any site visitor and all information will send to a site admin Email Id automatically by mail function.



<?php
  $mailto = 'destination email id' ;
  $formurl = "from email id" ;


// -------------------- END OF CONFIGURABLE SECTION ---------------
  $subject = $_POST['thesubject'] ;
  $message = $_POST['themessage'] ;
  $name = $_POST['name'] ;


$address = $_POST['address'] ;
  $city = $_POST['city'] ;


$state = $_POST['state'] ;


$postalcode = $_POST['postalcode'] ;


$country = $_POST['country'] ;


$email = $_POST['email'] ;


$phone = $_POST['phone'] ;


$phone1 = $_POST['phone1'] ;


$http_referrer = getenv( "HTTP_REFERER" );



if (!isset($_POST['email'])) {
  header( "Location: $formurl" );
  exit ;
  }
  $thankyouurl='thanx.php';//page where redirect after mail contact form successfully
  $messageproper =


"This message was sent from:\n" .
  "$http_referrer\n" .
  "------------------------- COMMENTS -------------------------\n\n" .
  " Subjet : $thesubject\n\n Message : $themessage\n\n Name : $name\n Address : $address\n City :$city\n State : $state\n Postal Code: $postalcode\n\n Phone : $phone, $phone1\n Country : $country\n\n Email : $email\n";
  "\n\n------------------------------------------------------------\n" ;


mail($mailto, $subject, $messageproper, "From: \"$Name\" <$email>\nReply-To: \"$name\" <$email>\nX-Mailer: chfeedback.php 2.01" );
  header( "Location: $thankyouurl" );
  exit ;
  ?>








<form id="form1" method="post" action="mailSend.php">
  <table border="0" cellspacing="5" style="width: 397px">
  <tr>
  <td colspan="2">
  <h3>
  Send a Enquiry</h3>
  </td>
  <tr>
  <td style="padding-top: 10px" width="95">
  </td>
  <td style="padding-top: 10px" width="283">
  <input type="hidden" id="ToEMail" name="ToEMail" value="contact@victoriamortgagebrokers.com.au" />
  <input type="hidden" id="thanksPage" name="thanksPage" value="http://victoriamortgagebrokers.com.au/Thanks.html" />
  </td>
  <tr>
  <td width="95">
  Name
  </td>
  <td width="283">
  <input type="text" id="txtName" name="txtName" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Contact No.
  </td>
  <td width="283">
  <input type="text" id="txtPhone" name="txtPhone" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  e-mail ID
  </td>
  <td width="283">
  <input type="text" id="txtEmail" name="txtEmail" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Suburb.
  </td>
  <td width="283">
  <input type="text" id="txtsuburb" name="txtSuburb" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Post Code
  </td>
  <td width="283">
  <input type="text" id="txtpostCode" name="txtPostCode" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Home Telephone</td>
  <td width="283">
  <input type="text" id="txtHomePhone" name="txtHomePhone" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Office Telephone</td>
  <td width="283">
  <input type="text" id="txtofficePhone" name="txtOfficePhone" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Mobile
  </td>
  <td width="283">
  <input type="text" id="txtmobile" name="txtmobile" style="width: 283px" />
  </td>
  </tr>
  <tr>
  <td width="95">
  Looking For</td>
  <td width="283">
  <input type="text" id="txtlookingfor" name="txtlookingfor" style="width: 283px" />
  </td>
  </tr>


<tr>
  <td valign="top" width="95">
  Comments
  </td>
  <td width="283">
  <textarea id="txtComments" name="txtComments" style="width: 283px; height: 91px"></textarea>
  </td>
  </tr>
  <tr>
  <td width="95">&nbsp;
 
  </td>
  <td align="right" style="padding-right: 25px" width="259">
  <input id="Button1" type="submit" value="Send" />
  </td>
  </tr>
  </table>
  </form>


Thursday, December 10, 2009

Get video duration without ffmpeg function

If we need to get video duration in php if server not support ffmepg function than use following code to get duration.

    ob_start();

    passthru("ffmpeg -i ".$videoName." 2>&1");
    $duration = ob_get_contents();
   ob_end_clean();

    $search='/Duration: (.*?)[.]/';
    $duration=preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE);
    $duration = $matches[1][0];

    list($hours, $mins, $secs) = split('[:]', $duration);

    echo "Hours: ".$hours." Minutes: ".$mins." Seconds: ".$secs;
    $duration=$mins.':'.$secs;


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>

Tuesday, December 8, 2009

Upload Email Refine it and save it to database

*


This post will help in copy all email id and pase it to textarea and click on upload button. Programme will automatically filter all invalid id and organize them and create group or add to exit group as u want.




<?php



$dbc=mysql_connect('localhost','userName','password');
mysql_select_db('database name',$dbc);





function gethtmlformat($txt){ //Function for RIght syntex for html format

$txt=str_replace('%0D%0A','',$txt);

$txt=str_replace('+','',$txt);

$txt=str_replace(',%20',',',$txt);

return($txt);



}



$action=$_REQUEST['act'];

$newGroup=$_REQUEST['newGroup'];

//echo $newGroup;

$oldGroup=$_REQUEST['group'];

$emailId=urlencode($_REQUEST['emailId']); //replace space with +

$emailId=urldecode(gethtmlformat($emailId));

//echo $emailId;

$EmailArray=explode(",",$emailId); //Create array of uploaded email string 

$totemail=count($EmailArray); //Count total email in arrary

//echo $totemail;

$count=0;

$Id;

$wrongId;

$group;

if(isset($action)){



if($newGroup!="" ){

$group=$newGroup;

}else{

$group=$oldGroup;

}

//echo $group.'<br>';



function chkEmail($email){

//echo $email;

if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ // function will validate email id

return("Invalid");

}else{

return("Valid");

}



}

for($i=0;$i<$totemail;$i++){

//echo $i;

if(isset($EmailArray[$i])){

//echo $EmailArray[$i].'<br>';

if(chkEmail($EmailArray[$i])=="Valid"){

$Id.=$EmailArray[$i].',';

$count+=1;

//echo $Id.'<br>';

}elseif(chkEmail($EmailArray[$i])=="Invalid"){



$wrongId.=$EmailArray[$i].'<br>';

//echo $wrongId.'<br>';

}

}

//echo chkEmail($EmailArray[$i]);

}

//echo $Id;

//****************************start Get New ID for News letter to send*****************



$selMaxId="select max(id) from emailgroup";

$result=mysql_query($selMaxId,$dbc)or die('Error in Fetch Id'.mysql_error());

$rs=mysql_fetch_row($result);

$groupId=$rs[0];

$newgroupId=$groupId+1;



//*******************************End get New ID for Greeting ********************



//******************************Check Group Exit or not************

function chkGroup($value,$dbc){

$chk="select group_name,emailid from emailgroup where group_name='$value'";

$chkRs=mysql_query($chk,$dbc) or die('error in group:-'.mysql_error());

$value1=mysql_fetch_row($chkRs);

//echo $value.$value1[1].'<br>';

return($value1[1]);



}





//*************************************************





if($Id!=""){

$insertEmail="insert into emailgroup values($newgroupId,'$group','$Id','y',$count)";
if(mysql_query($insertEmail,$dbc)){

echo '<div class="success">Email Uploaded</div>';

}else{

echo '<div class="error">Email Uploaded Fail</div>';



}

}

if($wrongId!=""){echo '<div class="error">Wrong Email Id:-'.$wrongId.'</div>';}



}



?>

<body>



<center>

<table width="80%" border="1">

<tr>

<td colspan="2" align="center" ><img src="http://www.totalbhakti.com/wallpaper/images/logo.png" border="0"></td>

</tr>

<tr>

<td width="20%" valign="middle">

<?php include('left.php');?>

</td>

<td>



<fieldset>

<legend>Email Id Upload Panel</legend>

<form name="emailform" action="emailUpload.php" method="post">

<table width="95%" cellpadding="0" cellspacing="0" border="1">

<tr>

<td width="30%"><strong>Select Email Group</strong></td>

<td >

<select name="group" id="group" onchange="selectionShow(document.getElementById('group'),'New',document.getElementById('newGroup1'))" >

<option>General</option>

<?php









$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>';



}



?>









<option>New</option>



</select>



</td>

</tr>

<tr id="newGroup1" style="visibility:hidden">

<td align="right">

<strong>Enter New Group</strong>

</td>

<td>

<input type="text" name="newGroup" id="newGroup" >

</td>



</tr>

<tr >



<td colspan="2" id="errorGroup" style="visibility:hidden">



</td>



</tr>

<tr>

<td align="left">

<strong>Enter Email Id's</strong>

</td>

<td>

<textarea name="emailId" id="emailId" cols="40" rows="10" ></textarea>

</td>



</tr>



<tr >



<td colspan="2" id="errorId" style="visibility:hidden">



</td>



</tr>



<tr >

<td align="right">

<input type="hidden" name="act" value="true" />

</td>

<td>

<input type="button" value="Upload" onclick="onSubmited(emailform)" >

</td>



</tr>

</table>

</form>

</fieldset>

</td>

</tr>

</table>

Friday, December 4, 2009

Add/Remove dynamic rows in HTML table

Add or remove row or item form html table dynamically.





 
<SCRIPT language="javascript">
     function addRow(tableID) {

     var table = document.getElementById(tableID);

     var rowCount = table.rows.length;
     var row = table.insertRow(rowCount);

     var cell1 = row.insertCell(0);
     cell1.innerHTML = "Select Photo : ";


     var cell2 = row.insertCell(1);
     cell2.innerHTML = rowCount + 1;

     var cell3 = row.insertCell(2);
     var element2 = document.createElement("input");
     element2.type = "file";
     cell3.appendChild(element2);

     }

     function deleteRow(tableID) {
     try {
     var table = document.getElementById(tableID);
     var rowCount = table.rows.length;

     for(var i=0; i<rowCount; i++) {
     var row = table.rows[i];
     var chkbox = row.cells[0].childNodes[0];
     if(null != chkbox && true == chkbox.checked) {
     table.deleteRow(i);
     rowCount--;
     i--;
     }

     }
     }catch(e) {
     alert(e);
     }
     }

  </SCRIPT>

 

  <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

  <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

  <TABLE id="dataTable" width="350px" border="1">
  <TR>
  <TD>Select File : </TD>
  <TD> 1 </TD>
  <TD> <INPUT type="file" name="file" /> </TD>
  </TR>
  </TABLE>


Wednesday, December 2, 2009

Url rewriting rule for .htaccess

Their are some rule that should be follow when we use url rewriting. Their are solution with example and definition of all parameter and tell how to use them in url rewriting.


Rewrite rules are broken down into 4 simple blocks.

  1. Call to action
  2. Pattern
  3. Rewrite
  4. Command Flag.
Example
    RewriteRule ^dir/([0-9]+)/?$ /index.php?id=$1 [L]


Call to action: RewriteRule
Pattern: ^dir/([0-9]+) /?$
Rewrite: /index.php?id=$1
Command Flag: [L]



Call to action Block


if you ever see a 500 error on your site it mostlikely due to a bad line of code in your .htaccess file. The only way to screw this up is to spell RewriteRule incorrectly or leave out the space between this and the starting of the pattern block.




Pattern Block


This one little piece of the mod rewrite is where the power is. In the pattern block of the rewrite rule we use regular expressions to detect the requested file name or uri and from this we can extract key parts to pass to the rewrite block.


Pattern Matching metacharacter Definitions


Char.
Definition
\
Use before any of the following characters to escape or null the meaning or it. \* \. \$ \+ \[ \]
^
Start matching at this point
$
End point of the match
.
Any character
[]
Starts a class
|
Starts alternative match this|that would mean match this or that
()
starts a back reference point
?
match 0 or 1 time Quantifier
+
match atleast 1 or more times Quantifier
*
match 0 to infinite times Quantifier
{}
match minimum to maximum Quantifier {0,3} match up to 3 times
Class Definitions []


Char.
Definition
^
Negates the class. [^A-Z]+ means don't match any uppercases
\
Use before any of the following characters to escape or null the meaning or it. [\+]+
-
Range for matching [0-9]+ [a-zA-Z]+


Example:-
     RewriteRule ^category/([0-9]+)\.htm$ /category.php?cat_id=$1 [L]


The best to use is the negated class since .+ will pick up a / since a / is defined as any given character. The [-a-zA-Z0-9]+ would just take up too much computing power over the long run. Remember the more you define the more strain there is on the system. Since a search for every thing but a / ([^/]+) requires less computing power it's not only fast it most optimal.




Rewrite Block
This part is a piece of cake. Now that we've used the pattern block to reference our matches ([0-9]+) we need to rewrite to the url and add the references as needed.
Remember a reference is anything that was picked up in the () in the rewrite.
To call a reference you just add a $ follow by the reference number. This all goes in order like so. Below we'll make 3 references.
RewriteRule ^dir/(.*)/(.*)\.(.htm|.html)$ /$1/$2.$3 [R=301,L]
Rewrites using a 301 redirect
dir/some/folder/file.htm to /some/folder/file.htm
You can mix up the references if you want like so:
RewriteRule ^dir/(.*)/(.*)\.(.htm|.html)$ /$2/$1.$3 [R=301,L]
you can also not call a reference like so:
RewriteRule ^dir/(.*)/(.*)\.(.htm|.html)$ /$2/$1.php [R=301,L]



Command Flag Block (Optional)
Ok I didn't tell you this is optional because half of you would skip this part. Learning the different Command Flags is a must.
The command flag definitions are as follows:

Char.
Definition
[R]
Redirect you can add an =301 or =302 to change the type.
[F]
Forces the url to be forbidden. 403 header
[G]
Forces the url to be gone 401 header
[L]
Last rule. (You should use this on all your rules that don't link together)
[N]
Next round. Rerun the rules again from the start
[C]
Chains a rewrite rule together with the next rule.
[T]
use T=MIME-type to force the file to be a mime type
[NS]
Use if no sub request is requested
[NC]
Makes the rule case INsensitive
[QSA]
Query String Append use to add to an existing query string
[NE]
Turns of normal escapes that are default in the rewriterule
[PT]
Pass through to the handler (together with mod alias)
[S]
Skip the next rule S=3 skips the next 3 rules
[E]
E=var sets an enviromental variable that can be called by other rules

EAJBJZSSMQEB

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');

  }

?>