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


Sunday, November 8, 2009

Image Upload and Cut their Thumbnail of DIff Size and Store it diff location and Insert recrod in Database

This is a image upload Program in which we upload image and dynamic cute their 4 diff size Thumbnail and store it diff location and enter these entry in image table of mysql data base

structure of Project

wallpaper->image->thum_170x120
->thum_1280x124
->thum_800x600
->connection.php
->imageUpload.php

File:-connection.php


*
Define all the constant variable
for Database Connection
*/



DEFINE('HOSTNAME','localhost');


DEFINE('USERNAME','root');



DEFINE('PASSWORD','');

DEFINE('DATABASE','image');


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

?>

//End of File connection.php


File:-imageUpload.php

require_once('connection.php'); //****include Database DAO*******************
set_time_limit(0); // Set Upload Processing Timer Infinite
//********************Variable Declare*******************
$title=$_POST['title']; //Fetch Image Title from form
/*
*Remove space with - from file name
*@param txt $name
*/
function getImageName($name){
$type=$name;
//$occur=strrpos($type,'.');
//echo $occur;
//$type=substr($type,0,$occur);
$type = str_replace( ' ', '-', $type );
return($type);
}
/*
*get File extension
*@param txt $filename
*
*/
function getFileExtension($fileName){
$fileNameParts = explode( ".", $fileName );

$fileExtension = end( $fileNameParts );

$fileExtension = strtolower( $fileExtension );
return($fileExtension);
}
if(isset($_FILES['upload'])){// Check File in Url or not
$current_date = date('Y-m-d'); //Store Current(Today) Date
$dirname='image/';
$newFileName=getImageName($title);
$fileExtension=getFileExtension($_FILES['upload']['name']);
$filesave=$newFileName.'-'.$newId.'.'.$fileExtension;
$destination=$dirname.$filesave;
$dirname='image/thum/';
$destinationthum=$dirname.$filesave;
$dirname1='image/thum_1280x1024//';
$destinationthum1=$dirname.$filesave;
$dirname3='image/thum_800x600/';
$destinationthum3=$dirname.$filesave;

if($_FILES['upload']['type'] != "image/gif"&&$_FILES['upload']['type'] != "image/jpg"&&$_FILES['upload']['type'] != "image/jpeg"&&$_FILES['upload']['type'] !="image/png" ) {
echo 'You may only upload Image files.

';
}else{
#echo 'in array';
if(move_uploaded_file($_FILES['upload']['tmp_name'],$destination)){
echo '
Image Upload


';
create_thumbnail($destination,$destinationthum,'170','130');
create_thumbnail($destination,$destinationthum1,'1280','1024');
create_thumbnail($destination,$destinationthum3,'800','600');
$insertPhoto="insert into image(title,image_name,status) values('$title','$destination','y')";
mysql_query($insertPhoto,$dbc);
}
}
}
if ($_FILES['upload']['error'] > 0) {
echo '

The file could not be uploaded because: ';


// echo a message based upon the error.
switch ($_FILES['upload']['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.';
break;
}
echo '

';
}
function create_thumbnail($source,$destination,$thum_width,$thum_height){
//echo $source.'
';
$size=getimagesize($source);
//echo $size[0];
$width=$size[0];
$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 '
'.$width.'--'.$height;
$new_image=imagecreatetruecolor($thum_width,$thum_height)or die('Cannot Initialize new GD image stream');
$extension=getExtension($source);
//echo '
Exten:-'.$extension.'
';
if($extension=='jpg'||$extension=='jpeg'){
$image=imagecreatefromjpeg($source);
}
if($extension=='gif'){
$image=imagecreatefromgif($source);
}
if($extension=='png'){
$image=imagecreatefrompng($source);
}
if($extension=='bmp'){
$image=@imagecreatefromwbmp($source);
}
imagecopyresampled($new_image,$image,0,0,$x,$y,$thum_width,$thum_height,$width,$height);
if($extension=='jpg'||$extension=='jpeg'){
imagejpeg($new_image,$destination);
}
if($extension=='gif'){
imagegif($new_image,$destination);
}
if($extension=='png'){
imagepng($new_image,$destination);
}
if($extension=='bmp'){
image2wbmp($new_image,$destination);
}
}
function getExtension($name){
$type=$_FILES['upload']['type'];
$type = str_replace( 'image/', '', $type );
return($type);
}

?>

//Php COde Ended

HTML code Begin


Upload Image


*Select Image To Upload:- (.jpg,.gif,.png only)
Enter Title*




//End of File image upload


mysql command:-
CREATE TABLE IF NOT EXISTS `wallpaper` ( `id` bigint(10) NOT NULL AUTO_INCREMENT, `title` varchar(100) NOT NULL, `image_name` varchar(200) NOT NULL,
'staus' enum('y','n'));