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

?>

Thursday, November 19, 2009

Form or Field Validation in Java script


//Function for remove white spaces from string both side starting and ending
function trim(str) {
return str.replace(/^\s+|\s+$/g,'');
};

//function end


//Function to check that pass value is empty or not
function checkFieldEmpty(textField,errorField){
var textFieldValue=trim(textField.value);
if(textField=="" || textFieldValue.length==0){
errorField.innerHTML="Field Can't Leave Empty";
errorField.style.visibility='visible';
errorField.style.border='#FF3333 solid 1px';
errorField.style.background='#FBE3E4';
errorField.style.color='#8a1f11';
textField.style.border='#FF3333 solid 1px';
//textField.focus();
return false;
}else{
errorField.style.visibility='hidden';
errorField.innerHTML="";
textField.style.border='#339900 solid 1px';
//return true; return "";
}
}

//end of funciton


//Function to check max length of string

// textField is a text box name
//max is the length value for check
//errorField is div show if error occur

function checkLength(textField,max,errorField){

var textFieldValue=trim(textField.value);


if(textFieldValue.length>max){

errorField.innerHTML="Field Lenght is More Then Size";
errorField.style.visibility='visible';
errorField.style.border='#FF3333 solid 1px';
errorField.style.background='#FBE3E4';
errorField.style.color='#8a1f11';
textField.style.border='#FF3333 solid 1px';
textField.focus();
return false;

}else{

errorField.style.visibility='hidden';
errorField.innerHTML="";
textField.style.border='#339900 solid 1px';
return "";
//return true;
}


}

//End of Function


//Function to check min length of string
// textField is a text box name
//min is the length value for check
//errorField is div show if error occur

function checkminLength(textField,min,errorField){

var textFieldValue=trim(textField.value);


if(textFieldValue.length
errorField.innerHTML="Field Lenght is Less Then Size";
errorField.style.visibility='visible';
errorField.style.border='#FF3333 solid 1px';
errorField.style.background='#FBE3E4';
errorField.style.color='#8a1f11';
textField.style.border='#FF3333 solid 1px';
textField.focus();
return false;
}else{

errorField.style.visibility='hidden';
errorField.innerHTML="";
textField.style.border='#339900 solid 1px';
return "";
//return true;
}
}

//Function End


//Function to check length of textarea of html or check is text area empty

// textareaField is a text area name

//errorField is div show if error occur

function checktextareaEmpty(textareaField,errorField){

var areaValue=trim(textareaField.value);

if(textareaField=="" && areaValue.length==0){

errorField.innerHTML="Text Area Can't Empty ";
errorField.style.visibility='visible';

//textareaField.focus();
return false;

}else{

errorField.style.visibility='hidden';
errorField.innerHTML='';
return "";
//return true;
}

}

// Function End

// Function for show any error or div box on select any option in select box
//selectionId is select box
//option is the value for which selection pass value is check
//showItem is div which will show the option check is true

function selectionShow(selectionId,option,showItem){

var selectionValue=trim(selectionId.value);
var opt=trim(option);
if(selectionValue==opt){

showItem.style.visibility='visible';

}else{

showItem.style.visibility='hidden';
}

}

// End Function

// Function for show div on radio button select
//buttonID is radio button id
//ShowItem is div to show

function selectRadioButton(buttonID,ShowItem){

var buttonValue=trim(buttonID.value);
alert(buttonValue);

if(buttonValue=="all"){

showItem.style.visibility='visible';

}else{

showItem.style.visibility='hidden';

}

}

// End of function


// Function for form submit ion validation that every require field not empty

function onSubmited(theForm){

var reason = "";


reason += checkFieldEmpty(document.getElementById('title'),document.getElementById('errorshow'));

reason += checkFieldEmpty(document.getElementById('user'),document.getElementById('errorshowid'));

if(document.getElementById('hide_singer').style.visibility == "visible"){

reason += checkFieldEmpty(document.getElementById('other_singer'),document.getElementById('errorsinger'));
}
if(document.getElementById('hide_lord').style.visibility == "visible"){

reason += checkFieldEmpty(document.getElementById('other_lord'),document.getElementById('errorlord'));
}
if(document.getElementById('hide_lang').style.visibility == "visible"){

reason += checkFieldEmpty(document.getElementById('other_language'),document.getElementById('errorlang'));
}
if(document.getElementById('hide_genure').style.visibility == "visible"){

reason += checkFieldEmpty(document.getElementById('other_genure_txt'),document.getElementById('errorgenure'));
}

//reason += checktextareaEmpty(theForm.other_tag,document.getElementById('errortag'));

if(reason !="") {
alert("Some fields need correction:\n" + reason);

}else{
theForm.submit();
}




}

//End of funciton

//Function for email validation

function chkEmail(elem, errorField){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
errorField.innerHTML="";
//errorshow.style.height='0px';
errorField.style.border='';

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

errorField.innerHTML="Please Enter Valid Email Address e.g. abc@abc.com";
errorField.style.visibility='visible';
errorField.style.border='#FF3333 solid 1px';
errorField.style.background='#FBE3E4';
errorField.style.color='#8a1f11';
textField.style.border='#FF3333 solid 1px';
textField.focus();

return false;
}
}

//End of function


http://opensourceprogrammer.blogspot.com/feeds/posts/default

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

?>

Create Auto Generated Table according to no of record in table

If we want to create table automatic according to no of record come from database;
first we declare how much no of col in table want to display.

<table width="810" border="0" cellspacing="0" cellpadding="0">

<?php

$colNo;

$i=0;

$slectQuery="select title from table";

$Result=mysql_query($selectQuery,$dbc)or die('error in fetch record:-'.mysql_error());


while($row=mysql_fetch_row($Result)){

if($i==0){

echo '<tr>';
}

echo '<td>

$i++;

if($i==$colNo){


echo '</tr>';
$i=0;
}

?>

</table>


Saturday, November 14, 2009

How to Use a CAPTCHA in php

To put it simply a captcha works by generating a random string, writing it to an image, then storing the string inside of a session or cookie or by some other method. This is then checked when the form or operation is performed.
Their are 7 basic Step
  1. Random text generated
  2. Text written to image
  3. Text stored in session/cookie/database
  4. Image displayed to user
  5. User enters the code
  6. User entered code is checked against the stored key
  7. If they match then something is done
Random text

I will use the php functions, microtime() and mktime() to generate a number. This number will then be encrypted using md5(). With this 32 character long encrypted string we will then use substr() to cut it down to a 5 letter long string. This is our random text.


//Start the session so we can store what the code actually is.
session_start();

//Now lets use md5 to generate a totally random string
$md5 = md5(microtime() * mktime());

/*
We dont need a 32 character long string so we trim it down to 5

*/

$string = substr($md5,0,5);
?>


Text to the image


/*
Now for the GD stuff, for ease of use lets create

the image from a background image.

*/


$captcha = imagecreatefrompng("./captcha.png");

/*
Lets set the colours, the colour $line is used to generate lines.

Using a blue misty colours. The colour codes are in RGB

*/


$black = imagecolorallocate($captcha, 0, 0, 0);
$line = imagecolorallocate($captcha,233,239,239);

/*
Now to make it a little bit harder for any bots to break,

assuming they can break it so far. Lets add some lines

in (static lines) to attempt to make the bots life a little harder

*/

imageline($captcha,0,0,39,29,$line);
imageline($captcha,40,0,64,29,$line);
?>


Text stored in session/cookie


/*
Now for the all important writing of the randomly generated string to the image.

*/

imagestring($captcha, 5, 20, 10, $string, $black);


/*
Encrypt and store the key inside of a session

*/


$_SESSION['key'] = md5($string);

/*
Output the image

*/

header("Content-type: image/png");
imagepng($captcha);

?>

Image displayed to user/User Enter COde

User simple img tag and input box


Check Enter Code is correct or not


session_start
();

//Encrypt the posted code field and then compare with the stored key

if(md5($_POST['code']) != $_SESSION['key'])
{

die(
"Error: You must enter the code correctly");
}else{

echo
'You entered the code correctly';
}
?>