Thursday 17 November 2011

Common Javascript for validation


// JavaScript Document


// get element by id
function getObject(val){
return document.getElementById(val);
}


function trim(b)
{
var i=0;
while(b.charAt(i)==" ")
{
i++;
}
b=b.substring(i,b.length);
len=b.length-1;
while(b.charAt(len)==" ")
{
len--;
}
b=b.substring(0,len+1);
return b;
}

function checkAtLeastOneBox(name) {

count = 0;
elements = document.getElementsByName(name);
len = elements.length;

for (var i = 0; i < len; i++) {
var e = elements[i];
if (e.checked) {
count=count+1;
}
}

if (count == 0){
return false;
}
else {
return true;
}
}


function isCharsInBag (s, bag)
  {
    var i;
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) return false;
    }
    return true;
 }

//function to check valid zip code
function isZIP(s)
  {
    return isAlphaNumeric(s);
 }


function isValidUrlAddress(strUrl) {// not working
 
   var v = new RegExp();
    v.compile("[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
}



function checkURL(value) {

var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
if(urlregex.test(value))
{
return(true);
}
return(false);
}

function isValidUrl(strUrl) {
   var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
}

function isValidUrl2(strUrl) {
   var v = new RegExp();
    v.compile("^[A-Za-z0-9-_:\/]+\\.[A-Za-z0-9-_%&\?\/.=]+\\.[A-Za-z]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
 }
function isChar(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ");
}


function isName(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ");
}
function isPassword(s)
{

s=trim(s);
return isCharsInBag (s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_");
}

//function to check valid Telephone,. Fax no. etc
function isPhone(s)
  {

return isCharsInBag (s, "0123456789-+(). ");//simple test

var PNum = new String(s);

// 555-555-5555
// (555)555-5555
// (555) 555-5555
// 555-5555

    // NOTE: COMBINE THE FOLLOWING FOUR LINES ONTO ONE LINE.

var regex = /^[0-9]{3,3}\-[0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\) [0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\)[0-9]{3,3}\-[0-9]{4,4}$|^[0-9]{3,3}\-[0-9]{4,4}$/;

// var regex = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/; //(999) 999-9999 or (999)999-9999
if( regex.test(PNum))
return true;
else
return false;

  }

function isAlphaNumeric(s){
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ");
}

function isUserName(s){
s=trim(s);
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.");
}

function isEmpty(s)
{
s=trim(s);
 return ((s == null) || (s.length == 0));
}

//function to check valid email id
function isEmail(s)
{

var regex = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(s);

}


function isInteger (s)
   {
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
}

function isDigit (c)
{
  return ((c >= "0") && (c <= "9"))
}



  //set focus on el or global variable gl_el;
  function setFocus(el){
if(el != "undefined"){
document.getElementById(el).focus();
setAlertStyle(el);
// addEvent(document.getElementById(el),'onblur',function(){ alert('hello!'); })
}else if(typeof gl_el != "undefined"){
gl_el.focus();
}
return true;

  }
 

  function setAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '000';
  }
 
  function unsetAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '#f0f0f1';
  }

function SetAllCheckBoxes(FormName,FieldName)
{
var isChecked=document.getElementById('checkAll').checked;

if(isChecked==true){
var CheckValue='true';

}
else
{
var CheckValue='';
}

if(!FormName)
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];

if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;

if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
{
objCheckBoxes[i].checked = CheckValue;


}
}

function isAllcheckBoxSelected(formObj,checkBoxName){
var status = false;
var countCheckBoxes = 0;
var objCheckBoxes = formObj.elements[checkBoxName];
countCheckBoxes = objCheckBoxes.length;
if(countCheckBoxes!=0){
for(var i = 0; i <countCheckBoxes; i++){
if(objCheckBoxes[i].checked==true){
status = true;
}else{
status = false;
break;
}
}
}if(!countCheckBoxes) {
if(objCheckBoxes.checked==true){
status = true;
}else {
status = false;
}
}
return status;
}


function checkMasterCheckBox(checkBoxObj,formName,checkBoxName,masterCheckBoxName){
allCheckBoxCheckedStatus = false;
formObj = getObject(formName);
masterCheckBoxObj = getObject(masterCheckBoxName);
allCheckBoxCheckedStatus = isAllcheckBoxSelected(formObj,checkBoxName);
//alert(allCheckBoxCheckedStatus);
if(checkBoxObj.checked==true){
if(allCheckBoxCheckedStatus==true){
masterCheckBoxObj.checked = true;
}
}else{
masterCheckBoxObj.checked = false;
}

}


function showchkbox(){
$(document).ready(function(){
$('#chkTab').toggle('slow');
$('#downarrow').toggle('slow');
});
}

/**
 * shows a popup<br />
 * depends on jquery<br />
 * there should be empty div named winhidelayer on page.<br />
 * @param id of popup div
 */
function showPopup(id){
    var height = $(window).height();
    var winwidth = $(window).width();

try{

$('#winhidelayer').show();
 $('#winhidelayer').css({
'left' : 0,
'top' :0,
'height' : height,
'width' : winwidth

});
}catch(error){
}
$('#'+id).show();
var snpopup = $('#'+id);
    var width = $(document).width();

    snpopup.css({
        'left' : width/2 - (snpopup.width() / 2),
        'top' : height/2 - (snpopup.height() / 2),
        'z-index' : 1000000                      
    });
}

/**
 * hide a popup<br />
 * depends on jquery<br />
 * there should be empty div named winhidelayer on page.<br />
 * @param id of popup div
 */
function hidePopup(id){
try{
$('#winhidelayer').hide();
}catch(error){
}
$('#'+id).hide();
}

/*
function isleap(yr)
{
 //var yr=document.getElementById("year").value;
 if ((parseInt(yr)%4) == 0)
 {
  if (parseInt(yr)%100 == 0)
  {
    if (parseInt(yr)%400 != 0)
    {
    //alert("Not Leap");
    return false;
    }
    if (parseInt(yr)%400 == 0)
    {
   // alert("Leap");
    return true;
    }
  }
  if (parseInt(yr)%100 != 0)
  {
   // alert("Leap");
    return true;
  }
 }
 if ((parseInt(yr)%4) != 0)
 {
    //alert("Not Leap");
    return false;
 }
}
*/


function daysInMonth(iMonth,iYear)
{


var days=32 - new Date(iYear, iMonth, 32).getDate();

return days;

}


 /*function CompDate(adate,bdate,msg)
{
start = document.getElementById('day').value+'-'+document.getElementById('month').value+'-'+document.getElementById('year').value+'-'+document.getElementById('hour').value+'-'+document.getElementById('min').value;
end = document.getElementById('day2').value+'-'+document.getElementById('month2').value+'-'+document.getElementById('year2').value+'-'+document.getElementById('hour2').value+'-'+document.getElementById('min2').value;
//alert(start); alert(end);
a = start.split('-');
b = end.split('-');
var sDate = new Date(a[2],a[0]-1,a[1],a[3],a[4]);
var eDate = new Date(b[2],b[0]-1,b[1],b[3],b[4]);

if (sDate <= eDate)
{
alert('right');
return true;
}
else
{
   alert('wrong');
return false;
}
}




var startDate=new Date();
startDate.setFullYear(2010,0,14);
var endDate  =new Date();
endDate.setFullYear(2010,0,14);


if (startDate>endDate)
  {
  alert("Today is before 14th January 2010");
  }
else if(startDate<endDate)
  {
  alert("Today is after 14th January 2010");
  }
   else if(startDate=endDate){
   
alert('Equal');
 }
 */



function validateZipCode(elementValue){
      var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
      return zipCodePattern.test(elementValue);
 }

function allValid(s){
s=trim(s);
return isCharsInBag (s, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. ");
}

function priceValid(s){
s=trim(s);
return isCharsInBag (s, "0123456789. ");
}
function validateHtml(str){
 if(str.match(/([\<])([^\>]{1,})*([\>])/i)==null)
return false;
 else
return true;
}
function isFloatNumeric(s){
   return isCharsInBag (s, "0123456789. ");
}

js


function validateUser(){
var name=userName=userType=email=email=alternateEmail1=alternateEmail2=alternateEmail3=phoneNo=barNo='';
name=$('#name').val();
userName=$('#userName').val();
userType=$('#userType').val();
email=$('#email').val();
alternateEmail1=$('#alternateEmail1').val();
alternateEmail2=$('#alternateEmail2').val();
alternateEmail3=$('#alternateEmail3').val();
phoneNo=$('#phoneNo').val();
barNo=$('#barNo').val();

if(name==''){
$('#errName').show();
$('#errName').html('Please enter your name.');
$('#name').focus()
return false;
}
if(name!=''){
$('#errName').hide();
}

if(userName==''){
$('#errUserName').show();
$('#errUserName').html('Please enter username.');
$('#userName').focus()
return false;
}
if(userName!=''){
$('#errUserName').hide();
}

if(userType==''){
$('#errUserType').show();
$('#errUserType').html('Please enter user type.');
$('#userType').focus()
return false;
}
if(userType!=''){
$('#errUserType').hide();
}

if(email==''){
$('#errEmail').show();
$('#errEmail').html('Please enter your e-mail.');
$('#email').focus()
return false;}

if(!isEmail(email)){
$('#errEmail').show();
$('#errEmail').html('Please enter valid e-mail, Like(yourname@example.com)');
$('#email').focus()
return false;}

if(email!=''){
$('#errEmail').hide();
}

if(!isEmpty($('#alternateEmail1').val())){
if(!isEmail($('#alternateEmail1').val())){
$('#errEmail1').show();
$('#errEmail1').html('Please enter valid e-mail, Like(yourname@example.com)');
$('#alternateEmail1').focus();
return false;
}
}

if(!isEmpty($('#alternateEmail2').val())){
if(!isEmail($('#alternateEmail2').val())){
$('#errEmail2').show();
$('#errEmail2').html('Please enter valid e-mail, Like(yourname@example.com)');
$('#alternateEmail2').focus();
return false;
}
}

if(!isEmpty($('#alternateEmail3').val())){
if(!isEmail($('#alternateEmail3').val())){
$('#errEmail3').show();
$('#errEmail3').html('Please enter valid e-mail, Like(yourname@example.com)');
$('#alternateEmail3').focus();
return false;
}
}

if(phoneNo==''){
$('#errPhone').show();
$('#errPhone').html('Please enter phone number.');
$('#phoneNo').focus()
return false;
}

if(isNaN(phoneNo)){
$('#errPhone').show();
$('#errPhone').html('Please enter phone no in numeric.');
$('#phoneNo').focus()
return false;}

if(phoneNo!=''){
$('#errPhone').hide();
}

if(barNo==''){
$('#errBar').show();
$('#errBar').html('Please enter bar number.');
$('#barNo').focus()
return false;
}
if(barNo!=''){
$('#errBar').hide();
}

}

/*if(alternateEmail1!=''){
if(!isEmail(alternateEmail1)){
$('#errEmail').show();
$('#errEmail').html('Please enter your e-mail.');
$('#alternateEmail1').focus()
return false;
}
}*/

function deleteUser(id){
str= 'deleteUser.php?action=delUser&uId=';
val = confirm('Are you sure you want to delete this User?');
if(val){
document.location.href=str+id;
}
}

function changeUserStatus(status,id){
document.location.href="changeUserStatus.php?id="+id+"&status="+status;
}

mang


<?php
class userManager
{
function addUser($arr,$files){

   require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();

if(self::userExist($arr)){
echo '<script>document.location.href="manageUser.php?msg=4";</script>';
return $result=0;
}

require_once(COMM_PATH."Helper.php");
$helper = new Helper();

if(isset($_REQUEST['uId']) && $_REQUEST['uId']!=''){
$query='UPDATE users SET name="'.$arr['name'].'",address="'.$arr['address'].'",userType="'.$arr['userType'].'",phoneNo="'.$arr['phoneNo'].'",cellPhone="'.$arr['cellPhone'].'",businessPhone="'.$arr['businessPhone'].'",barNo="'.$arr['barNo'].'",email="'.$arr['email'].'",alternateEmail1="'.$arr['alternateEmail1'].'",alternateEmail2="'.$arr['alternateEmail2'].'",alternateEmail3="'.$arr['alternateEmail3'].'",billingInformation="'.$arr['billingInformation'].'",billingPlan="'.$arr['billingPlan'].'",isActive="'.$arr['isActive'].'",dateUpdated=now() WHERE  userId="'.$_REQUEST['uId'].'"';
$result=$db->executeUpdate($query);
} else {
$query='INSERT INTO users(name,userName,address,userType,phoneNo,cellPhone,businessPhone,barNo,email,alternateEmail1,alternateEmail2,alternateEmail3,billingInformation,billingPlan,isActive,dateCreated,dateUpdated) VALUES("'.$arr['name'].'","'.$arr['userName'].'","'.$arr['address'].'","'.$arr['userType'].'","'.$arr['phoneNo'].'","'.$arr['cellPhone'].'","'.$arr['businessPhone'].'","'.$arr['barNo'].'","'.$arr['email'].'","'.$arr['alternateEmail1'].'","'.$arr['alternateEmail2'].'","'.$arr['alternateEmail3'].'","'.$arr['billingInformation'].'","'.$arr['billingPlan'].'","'.$arr['isActive'].'",now(),now())';
$result=$db->executeUpdate($query);
$rowId = $db->lastInsertId();

if(count($result) >0){
$rand_number=$this->random_string();
$subject = "Your Cortq temporary password";
$from = ADMIN_MAIL;
$to = $arr['email'];
$mailContent = "Hello ".ucfirst($arr['name']).",<br /><br />";
$mailContent .= "Welcome to CortQ!<br />";
$mailContent .= "Just login using folllowing detail:<br /><br />";
$mailContent .= "User name:  ".$arr['userName']."<br />";
$mailContent .= "User e-mail:  ".$arr['email']."<br />";
$mailContent .= "Session ID:  ".$rand_number."<br /><br />";
$mailContent .= "Thanks,<br />";
$mailContent .= "The CortQ Team ";
$headers ="From:".ADMIN_MAIL."\nReply-To:".ADMIN_MAIL."\nContent-Type:text/html";
//echo $mailContent; die();
@mail($to,$subject,$mailContent,$headers);
$sql="UPDATE users SET password ='".md5($rand_number)."' WHERE userId=".$rowId;
$result = $db->executeUpdate($sql);
}
}
}

    function random_string(){
$character_set_array = array( );
$character_set_array[ ] = array( 'count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz' );
$character_set_array[ ] = array( 'count' => 1, 'characters' => '0123456789' );
$temp_array = array( );
foreach ( $character_set_array as $character_set )
 {
for ($i=0;$i<$character_set[ 'count' ];$i++)
  {
$temp_array[ ]=$character_set[ 'characters' ][ rand( 0, strlen( $character_set[ 'characters' ] ) - 1 ) ];
  }
 }
 shuffle( $temp_array );
 return implode( '', $temp_array );
}



   function getUserList($arr,$limitUp, $limitDown)
{
if(isset($_REQUEST['sortBy']) && $_REQUEST['sortBy']!=''){
$sortBy = $_REQUEST['sortBy'];
} else {
$sortBy = "userId";
}

if(isset($arr['ordBy']) && $arr['ordBy']!=''){
$ordBy = $arr['ordBy'];
} else {
$ordBy = "DESC";
}
require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();
$query='SELECT * FROM users ORDER BY '.$sortBy.' '.$ordBy.' LIMIT '.$limitUp.', '.$limitDown;  
$result=$db->executeQuery($query);
return $result;
}

  function getCountOfPages(){
require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();
$query='SELECT COUNT(*) as cnt FROM users';
$result=$db->executeQuery($query);
return $result[0]['cnt'];
}

  function getUserForEdit($uId){
require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();
$query='SELECT * FROM users WHERE userId="'.$uId.'"';
$result=$db->executeQuery($query);
return $result;
}

  function userExist($arr){
require_once(COMM_PATH."DatabaseManager.php");
$db = new DatabaseManager();
if(isset($arr['uId']) && $arr['uId']!='')
$sql = "SELECT * FROM users where userName = '".$arr['userName']."' and userId!= '".$arr['uId']."'";
else
$sql = "SELECT * FROM users where userName = '".$arr['userName']."'";
$resList = $db->executeQuery($sql);
if(count($resList)>0){
return true;
} else {
return false;
}
}

  function deleteUser($uId){
require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();
//self::deleteUploadedImages($uId);
$query='DELETE FROM users WHERE userId="'.$uId.'"';
$result=$db->executeUpdate($query);
return $result;
}
}
?>

init


<?php
require_once(ADMIN_LIB_PATH."user/userManager.php");
require_once(COMM_PATH."Paging.php");
$userDetail = new userManager();

$paging = new Paging();
$defNum = 10; // records per page
$page = 1;


if(isset($_REQUEST['page']) && $_REQUEST['page']!=''){
$page = $_REQUEST['page'];
} else {
$page = 1;
}
$limitDown = MG_RECORDS_PER_PAGE;
$limitUp = ($page-1)*$limitDown;


if(isset($_GET['msg']) && $_GET['msg']!=''){
if($_GET['msg']=='1'){
$message = 'User has been added successfully';
}
if($_GET['msg']=='2'){
$message = 'User has been updated successfully';
}

if($_GET['msg']=='3'){
$message = 'User has been deleted successfully';
}

if($_GET['msg']=='4'){
$errorUser = 'User Name already in use';
}
}

if(isset($_REQUEST['act']) && $_REQUEST['act']=='addUser')
{
$insertUser= $userDetail->addUser($_REQUEST,$_FILES);
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!=''){
echo '<script>document.location.href="manageUser.php?msg=2";</script>';
exit();
} else {
echo '<script>document.location.href="manageUser.php?msg=1";</script>';
exit();
}
}

if(isset($pg_Name) && $pg_Name=='User List'){
$userList= $userDetail->getUserList($_REQUEST,$limitUp, $limitDown);
$pageCount= $userDetail->getCountOfPages();
$paging->setpagingparameters($pageCount);
}


$name=$userType=$userName=$email=$alternateEmail1=$alternateEmail2=$alternateEmail3=$address=$phoneNo=$cellPhone=$businessPhone=$barNo=$billingInformation=$billingPlan=$password=$isActive='';
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!=''){
$editList= $userDetail->getUserForEdit($_REQUEST['uId']);

if(count($editList)>0){
$name=$editList[0]['name'];
$userType=$editList[0]['userType'];
$userName=$editList[0]['userName'];
$email=$editList[0]['email'];
$alternateEmail1=$editList[0]['alternateEmail1'];
$alternateEmail2=$editList[0]['alternateEmail2'];
$alternateEmail3=$editList[0]['alternateEmail3'];
$address=$editList[0]['address'];
$phoneNo=$editList[0]['phoneNo'];
$cellPhone=$editList[0]['cellPhone'];
$businessPhone=$editList[0]['businessPhone'];
$barNo=$editList[0]['barNo'];
$billingInformation=$editList[0]['billingInformation'];
$billingPlan=$editList[0]['billingPlan'];
$password=$editList[0]['password'];
$isActive=$editList[0]['isActive'];
}
}

?>

Tuesday 15 November 2011

GET ID FROM URL IN ZEND

JUST USE THE FOLLOWING LINE FOR GET THE REQUEST

If your url like as following and want to get id from url then use this following code

Your url http://business/bic/property/editpicture/id/2

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

$request = $this->getRequest();
$id = $request->id;
echo $id;
/***********************************************/

from this you want to delete any item then use following code

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

public function deleteAction(){
$request = $this->getRequest();
$id = $request->id;
$db = Zend_Db_Table::getDefaultAdapter();
$db->delete('table_name', array('id = ?' => $id ));
$this->_redirect($url."property");
}
/************************************************/

Item will be deleted if you want to activate and deactivate your field then use the following code

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


public function editAction()
{
$request = $this->getRequest();
$id = $request->id;
$userList = new Users();//object
$userList->deleteUser($id);
$this->_helper->redirector('index');
}


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


Now your data edit..............

Edit Image

Edit image from below


<?php
$upload_data_pic = $arr]['pathofthepicture'];
if($upload_data_pic && $upload_data_pic != '' ) {
$thumbimguser = $this->baseUrl()."/property_images/".$upload_data_pic;  //image path
  ?>
<span style="vertical-align:top" id="thumbimage2"> <img src="<?php echo $thumbimguser;?>" />
<a href="javascript:;" onClick="editImage();" class="comment" style="text-decoration:none;">Edit</a>&nbsp;&nbsp;
// <?php echo formError('upload_file', $this->errors); ?>
               // optional for error shows
</span>

    <span style="vertical-align:top; display:none;" id="editbanner2"><input type="file" name="upload_file" id="upload_file" value="" />&nbsp;&nbsp;<a href="javascript:;" onClick="canceleditImage();" class="comment" style="text-decoration:none;">Cancel</a></span>
<?php } else {?>
              <input type="file" name="upload_file" id="upload_file" />
//<?php echo formError('upload_file', $this->errors); ?>
                               // optional for error
<?php }?>


ALSO PLACE A SCRIPT IN YOUR FILE BELOW/TOP  OF THE PAGE OR IN JS FILE


<SCRIPT type="text/javascript">
function editImage()
{
document.getElementById('thumbimage2').style.display='none';
document.getElementById('editbanner2').style.display='block';
}

function canceleditImage()
{
document.getElementById('upload_file').value='';
document.getElementById('thumbimage2').style.display='block';
document.getElementById('editbanner2').style.display='none';

}
</SCRIPT>








Thumbnail Genrator Function


/**This function used for the purpose of image resize just copy and paste
    *$imgType = $arr['upload_file']['type']; there need to change upload_file name with your given name
**/
public function resizeImage($originalImagepath&name,$toWidth,$toHeight,$smallimagepath&name,$arr)
{
ini_set("memory_limit", "50M");
$imgType = $arr['upload_file']['type'];

list($width, $height) = getimagesize($originalImage);

if($width < $toWidth){
$toWidth = $width;
}

if($height < $toHeight){
$toHeight = $height;
}

if($toWidth != 0){
$xscale=$width/$toWidth;
}

if($toHeight != 0){
$yscale=$height/$toHeight;
}

if ($yscale>$xscale){
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
} else {
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}

$imageResized = imagecreatetruecolor($new_width, $new_height);

if ($imgType =="image/gif"){
$imageTmp = imagecreatefromgif($originalImage);
$background = imagecolorallocate($imageResized, 0, 0, 0);
            ImageColorTransparent($imageResized, $background);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagegif($imageResized, $path);
} elseif($imgType =="image/png" || $imgType =="image/x-png") {
$imageTmp = imagecreatefrompng($originalImage);
imagealphablending($imageResized, false);
imagesavealpha($imageResized, true);
$background = imagecolorallocatealpha($imageResized, 255, 255, 255, 127);
imagecolortransparent($imageResized, $background);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagepng( $imageResized,$path);
}
else {
$imageTmp  = imagecreatefromjpeg($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($imageResized,$path);
}

return $imageResized;
}//End resizeImage Function there.....


How to use this function................................................
1. Use this function after move _uploaded_file(); 

2. Used as following.

                                $upload_path = "property_images/"; //My image folder where save
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'].'/projectName/');
define("USER_IMAGE_PATH", ROOT_PATH."property_images/");// proper image folder where your image save.
$imageName = basename($_FILES['upload_file']['name']); // Get image name
$originalImg = USER_IMAGE_PATH.$imageName; //Get orignal image path and image name 
$upload_path = $upload_path . basename( $_FILES['upload_file']['name']);
$unique = rand();// for unique image name 
$smallImg = USER_IMAGE_PATH."small_".$unique."_".$imageName; //first image small size
$bigImg = USER_IMAGE_PATH."big_".$unique."_".$imageName;  // you want big if
$insertedName = "small_".$unique."_".$imageName;
move_uploaded_file($_FILES['upload_file']['tmp_name'], $upload_path);
$this->resizeImage($originalImg, 170, 130,$smallImg,$_FILES);
$this->resizeImage($originalImg, 376, 304,$bigImg,$_FILES);

It's Working if any problem image thumb is black then check resize()  function there is not get file type just print this $imgType = $arr['upload_file']['type']; and check value. 

How to read special character in php

Some time you store data in different language like French, Spanish etc.When you fetch this data on your page then the special character are not shown as they save in data base.They shows on page as question mark etc,this is problem is utf encode. If you are using xampp version of 1.7.3 and above then there is no problem because when you are fetching data from database then it's return encoded data then data shows in right way.But when your special character are not shown. So don't worry and no need to install latest xampp/wampp.Following are the special characters and method how to show this in our page.


Umlauts and accents:-Â Ã Ä Æ Ç È É Ñ  Õ Ö Ø Ù Ú Û Ü ß  ã  ñ ò ó ô œ õû ü ÿ<br/>
<b>b) <u>Punctuation:-</u></b>  ¿ ¡ « » § ¶ † ‡ • - – —<br/>
<b>c) <u>Commercial symbols:-</u></b>  ™ © ® ¢ € ¥ £ ¤<br/>
<b>d) <u>Greek characters:-</u></b>  α β γ δ ε ζ η κ λ μ ο π ρ σ τ υ φ χ ωΓ Δ Θ Λ Ξ Π Σ Φ Ψ Ω<br/>
<b>e) <u>Math characters:-</u></b>  ∫ ∑ ∏ √ − ± ∞ ≈ ∝ ≡ ≠ ≤ ≥ × · ÷ ∂ ∈ ⇒ ⇔ → ↔ ↑ ℵ ∉<br/>
</div>
<p>For that there is following ways for showing special characters.</p>
<div class="maiwwn">
1. utf8_encode() <br/>
2. header('Content-Type: text/html; charset=utf-8');<br/>
</div><br/><br/>

1. <b style="color:#66019C;font-size:14px;"><u>utf8_encode():-</u></b> This is used with variable, for example if there is a variable</br>
<div class="vattttttt">$userPassword = "#ÛÜõû!";</div>
if these special character not print in your page then you need to used this function as following.<br/>
<div class="vattttttt">echo utf8_encode($userPassword); </div>
Now it's print #ÛÜõû! on your page.<br/><br/><br/>

2. <b style="color:#66019C;font-size:14px;"><u>charset=utf-8:-</u></b> Another way is just place this code on your page at the top once time header('Content-Type: text/html; charset=utf-8'); , then your special character shows on your page.<br/>
<div class="vattttttt">header('Content-Type: text/html; charset=utf-8'); </div>
But you can use utf8_encode() it's more predictable and accurate.
<br/><br/>
you can use both of this but I suggest you you can use <b style="color:red">utf8_encode()</b> and it's solve your problem. Use this with variable where you wants to echo.