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]



Wednesday, November 25, 2009

Upload video and convert it to flv in php and cut their thumnail

<?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, 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;
}

?>