Tuesday 25 December 2012

Hiding unnecessary menus in wordpress admin


In this post, I describe a technique for hiding unnecessary menus. 



Some time we need to hind unnecessary menus for other clients role just like (administrator, contributor, subscriber, author, editor, etc) then with the help of this function we can hide wordpress menu.
1.    
1   This code include your themes>>functions.php files.

// remove unnecessary menus
function remove_admin_menus () {
                global $menu;
                                $restrict = explode(',', 'contributor');// you can pass user role (administrator, contributor, subscriber, author, editor, etc)
                $restrict_user = explode(',', 'Posts,Comments,Media,Profile,Appearance,Plugins,Users, Tools,Settings');// you can pass menus name whose you want to hide.
               
                $f = create_function('$v,$i', 'return __($v);');
                array_walk($restrict, $f);
                if (!current_user_can('activate_plugins')) {
                                array_walk($restrict_user, $f);
                                $restrict = array_merge($restrict, $restrict_user);
                }
                // remove menus
                end($menu);
                while (prev($menu)) {
                                $k = key($menu);
                                $v = explode(' ', $menu[$k][0]);
                                if(in_array(is_null($v[0]) ? '' : $v[0] , $restrict)) unset($menu[$k]);
                }
}
add_action('admin_menu', 'remove_admin_menus');

Thursday 13 December 2012

How to remove last character of a string(mysql Query fields)?




SELECT Concat( mid( fieldname, 1, length(fieldname) -1 )
 , REPLACE( mid(fieldname, length(fieldname) ) , ',', "" ) )
 as fieldname FROM tablename
 
OR

Select id, REPLACE(fieldname,',','') from tablename 
where fieldname REGEXP '(.*),' limit 5;

update last character from string mysql

UPDATE tablename SET fieldname = Concat( mid(fieldname,
 1, length(fieldname) -1 ) , REPLACE( mid(fieldname, 
length(fieldname) ) , ',', "" ) ) 

Wednesday 21 November 2012

After logout browser back button shows all visited page in cake php

Some time we logout from application, then we got successfully massage you are logout , but we click back button then we see we reach also last page where we logout.

I solve this problem with given below function.


Add below code in your AppController.php

 
 

public function beforeRender() {
    $this->disableCache();
   
}

Monday 1 October 2012

Translate date into your language

 i got a requirment wherein i user add date in US(English) format but user want to display spanish language/or Other Language.

First Method :


/* Windows con apache
setlocale(LC_TIME, 'Spanish'); */

/* Apache con linux */
/* setlocale(LC_TIME, 'es_ES'); */

// setlocale(LC_TIME, 'de_DE'); 
// echo strftime('%A, %d. %B %Y');  

/* setlocale(LC_TIME, 'es_MX'); */

setlocale(LC_TIME, 'es_ES'); //pase language code 
echo $fecha=strftime('%B %d %Y',strtotime('01-09-2012'));// Output septiembre 01 2012

Second Method 

function converttospanish($paramdate)
{
$str=$paramdate;
$month = array("","enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiempre", "diciembre");// you can change different language 
if (($timestamp = strtotime($str)) !== false)
{
$php_date = getdate($timestamp);
$dm = date_parse_from_format("Y-m-d", $paramdate);
echo $php_date["mday"].' '.$month[$dm["month"]].' '.$php_date["year"];
}
else
{
echo 'invalid timestamp!';
}
}


Tuesday 25 September 2012

Add and remove textbox dynamically with jQuery.

Recently when working on my site i got a requirment wherein i user can add multiple input text on page in different textboxes, and these textboxes needs to be created dynamically as per user need. So i decided to do it in jQuery. it’s quite easy to add or remove a textbox dynamically. The idea is quite simple, just combine the use of ‘counter‘ variable, jQuery createElement(), html() and remove() method. See below example :


<html>
<head>
<title>Add dynamic text box</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>add dynamic text box</h1>
<script type="text/javascript">
 $(document).ready(function(){
     var counter = 2;
     $("#addButton").click(function () { //add dynamic text box
  if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
}   
  var newTextBoxDiv = $(document.createElement('div'))
    .attr("id", 'TextBoxDiv' + counter);
  newTextBoxDiv.after().html('<label>Textbox #'+counter+':</label>'+'<input type="text" name="textbox'+ counter+'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
     });

     $("#removeButton").click(function () { //remove dynamic text box
if(counter==1){
 alert("No more textbox to remove");
 return false;
   }   
counter--;
        $("#TextBoxDiv" + counter).remove();
     });

     $("#getButtonValue").click(function () {

var data = '';
for(i=1; i<counter; i++){
     data += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
     alert(data);
 //save dynamic data in database;
/* for(i=1; i<counter; i++) { 
        $.post(
            'process.php',// Data will be passed to this php file. 
           
                value: $('#textbox'+i).val() // get data values
            }
            );
  }*/
     });
  });
</script>
</head>


<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

</body>
</html>

Tuesday 18 September 2012

Cropping an Image with PHP and the GD Library

Learn how to use the PHP GD library in your PHP program to generate dynamic images. Learn how to create and manipulate the GIF, PNG and JPG images.



<?php
# Note: Install GD laibreries 
$filename = '194_card.jpg';//orignal file 
$filename1 = '1.png';//save file name whoes you save 

list($current_width, $current_height) = getimagesize($filename);
$left = 0; //crop left margin
$top = 0;//crop right margin
$crop_width = 1056; 
$crop_height = 400;
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename1, 100);
?>

Sunday 16 September 2012

Saving An Image Retrieved Via cURL


How can save images without use of browser with the help of Curl.
Some time we need save url image help of code without open browser
This function save image without open link.
$url="http://google.com/imagename.jpg";                                                                          
$ch = curl_init($url);
$fp = fopen(‘folderpath/card1.jpg', 'wb');// folder path where you save image
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Note : One of the main reasons to use cURL to save or display a remote image is that some servers/hosts have allow_url_fopen turned off. This means functions like fopen can’t open files held on external servers.
I hope you have enjoyed this tutorial

Saturday 18 August 2012

How can import excel file data in mysql with the help of php.


How can import excel file data in mysql with the help of php.

To import excel data into php-mysql records first create a table with required fields. Make database connection. Open excel file and read columns one by one and store in variables.

First Method******************* import excel data to php code****************/
$handle = fopen("Book1.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
echo "INSERT into importing(text,number)values('$data[0]','$data[1]')";
echo "<br>";
}
/************************************************************************/
 /***Second Method************ import excel data to php code and mysql***************/
$handle = fopen("Book1.csv", "r");
$fields=array('category','datatype','date','value');
$table='test';
$sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
while (($data = fgetcsv($handle)) !== FALSE) {
    foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
           $rows[] = implode(",",$data);
  }
$sql_query .= implode("),(", $rows);
 $sql_query .= ")";
  echo $sql_query;

/****************************************************************************/
 /***Third Method*********** import excel data to php code and mysql****************/
require_once 'Excel/reader.php'; // http://code.google.com/p/php-excel-reader/downloads/list
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('Book1.xls');
for ($x = 2; $x<=count($data->sheets[0]["cells"]); $x++) {
    $name = $data->sheets[0]["cells"][$x][1];
    $extension = $data->sheets[0]["cells"][$x][2];
    $email = $data->sheets[0]["cells"][$x][3];
    $sql = "INSERT INTO mytable (name,extension,email) VALUES ('$name',$extension,'$email')";
    echo $sql."\n";
    echo "<br>";
 }

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

Monday 30 July 2012

In cake php Upload file/image without refresh page with the help of ajax and validate extension.


Upload file without refreshing page in cakephp
1.controller/controlername_controller.php
class DoctorsController extends AppController {
var $name = 'Doctors';
public $uses = array('Doctor');
function changeprofilephoto() {
$doctor_id = “14”; //
$path = "../../app/webroot/profilepic/";//set path
$valid_formats = array(".jpg", ".png", ".gif", ".bmp", ".jpeg");//
if($this->data)
{
$this->Doctor->set( $this->data );
$name = $this->data["Doctor"]['profile_pic']['name'];
$size = $this->data["Doctor"]['profile_pic']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = strtotime(date('Y-m-d H:i:s')).$fileExt;
$tmp = $this->data["Doctor"]['profile_pic']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$this->Doctor->set($this->data);
$this->Doctor->id=$doctor_id;
$this->Doctor->saveField('uploadfoldername',$actual_image_name);
echo "<img src='/profilepic/".$actual_image_name."' class='preview'>";
$this->Session->write('suc','1');
$this->redirect($_SERVER['HTTP_REFERER']);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
} else
echo "Please select image..!";
exit;
}
}
} 



  1. views/changeprofilephoto.ctp


<?php
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>

<script type="text/javascript" >
$(document).ready(function() {
$('#profile_pic').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="../img/loader.gif" alt="Uploading...."/>');//download loding image
$("#Doctor").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<div class="layout-popup f-left">
<?php
echo $this->Form->create('Doctor',array('id'=>'Doctor', 'controller'=>'Doctors','action'=>'changeprofilephoto', 'type'=>'file'));
?>

<!-- <form id="Doctors" name='Doctors' method="post" enctype="multipart/form-data" action='/Doctors/changeprofilephoto'> -->

<!-- start id-form -->
<table class="frm-tbl" id="id-form" >
<tr>
<td colspan="2" class="align-t-r" >
<div class="f-left popup-title">Change doctor profile image</div>
</td>
</tr>
<tr>
<td>Upload your image</td>
<td align="left" >
<!-- <input type="file" name="[Doctors][photoimg]" id="profile_pic" /> -->
<?php echo $form->file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?>
</td>
</tr>
<tr>
<td colspan="2">
<div id='preview'>
</div>
</td>
</tr>
</table>
<?php
echo $this->Form->end();
?>
</div>

Sunday 29 July 2012

How to create paging and shorting in cake php


1. Controller/controllername.php
class ControllerNameController extends AppController {

var $name = 'ControllerName';
public $uses = array('TablesName');


function inbox() {
$this->paginate = array(
'conditions' => array('TablesName.receiver_delete'=>'0', 'AND'=>array('TablesName.user_to'=>$parameters ['id'])),'limit' => 10,'order' => array('TablesName.sent_date'=>'desc'
)
);
$data = $this->paginate('TablesName');
$this->set('messages', $data);
}


  1. views/elements/paging.ctp
    <?php
echo "<div align='left' class='l1'>".
$this->Paginator->counter(array('format' => 'Showing %page% to %pages% of %count% entries' )).
"</div><div align='right' class='r1'>".
$this->Paginator->first('First', null, null, array('class' => 'disabled'))."&nbsp;&nbsp;&nbsp;".
$this->Paginator->prev('« Prev', null, null, array('class' => 'disabled'))."&nbsp;&nbsp;".
$this->Paginator->numbers()."&nbsp;&nbsp;".
$this->Paginator->next('Next »', null, null, array('class' => 'disabled'))."&nbsp;&nbsp;".
$this->Paginator->last('Last', null, null, array('class' => 'disabled'))."".
"</div>";
?>

  1. views/paging vies file

<table width="100%" style="border: 1px solid #ccc;" border='0'>
<?php
if (!empty($messages)) {
echo "<tr>";
echo "<td colspan=\"5\" align=\"right\">". $this->element('paging')."</td>";
echo "</tr>";
echo "<tr style=\"background-color: #55699F;\">";
echo "<td><font color=white>S.No</font></td>";
echo "<td><font color=white>".$this->Paginator->sort('From', 'user_from')."</font></td>";
echo "<td><font color=white>".$this->Paginator->sort('Title', 'subject')."</font></td>";
echo "<td><font color=white>".$this->Paginator->sort('Date & Time', 'sent_date')."</font></td>";
echo "<td><font color=white>Action</font></td>";
echo "<tr>";
foreach ($messages as $message) {?>
<tr class="<?php echo ($message['Message']['status']=='Un-read')? 'unread':'read'?>">
<td><?php echo $message['Message']['id'] ?></td>
<td onclick="read('<?php echo base64_encode($message['Message']['id'])?>/inbox')" style="width: 200px"><?php echo $message['user_from']['email']?></td>
<td onclick="read('<?php echo base64_encode($message['Message']['id'])?>/inbox')" style="width: 500px"><?php echo $message['Message']['subject']?></td>
<td onclick="read('<?php echo base64_encode($message['Message']['id'])?>/inbox')" style="width: 130px"><?php echo $message['Message']['sent_date']?></td>
<td style="width: 40px"><a onclick="return confirm('Do you really want to delete this message?');" href="delete/<?php echo base64_encode($message['Message']['id']);?>/inbox">Delete</a></td>
</tr>
<?php
}
echo "<tr>";
echo "<td style=\"height:20px\"></td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"5\" align=\"right\">". $this->element('paging')."</td>";
echo "</tr>";
} else {?>
<tr >
<td colspan="5">Ther are no messages in inbox.</td>
</tr>
<?php
}
?>
</table>

Monday 23 July 2012

Upload file/image without refresh page with the help of ajax and validate extension.

file upload with progress bar
jquery upload file with progress bar


Step 1.
<html>
<head>
<title>Image upload without refresh page</title>
</head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>//search this file on google
<script type="text/javascript" src="scripts/jquery.form.js"></script> //search this file on google
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>'); //download load loading image 
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<body>
<div style="width:600px">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
<br>
<input type="text" id='tt' name='tt'>
</form>
<div id='preview'>
</div>
</div>
</body>
</html>

Step 2. 

<?php
$path = "img/"; // set image upload path

$valid_formats = array(".jpg", ".png", ".gif", ".bmp"); // set formate
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
//echo $name = $_POST['tt'];//use to image description. and you can do also save in database.
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext; // create image unique name
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
// you can fire query for insert image discription or more fields whoes you create in form.
echo "<img src='img/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>


Thursday 12 July 2012

A simple code to export data to excel using PHP and cake php

While generating a report in your project, you might have to download the data into excel file using PHP. In most scenario, you have to display the report in a page and create a link to download the report in the excel file. Well in that scenario, i think i can help you with a simplified code of PHP and cakephp.


Core Php

<?php
    $filename ="excelreport.xls";
    $contents = "Name\t Email \t Mobile \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
    header('Content-type: application/ms-excel'); /// you can set csv format
    header('Content-Disposition: attachment; filename='.$filename);
    echo $contents;
    ?>

Cake php Code 
Past this code on controller
controlpanel_controller.php

class ControlpanelController extends AppController {
var $name="Controlpanel";
var $layout=false;

function file_export()
{
              $this->autoRender=false;
ini_set('max_execution_time', 1600); //increase max_execution_time to 10 min if data set is very large
$results = $this->ModelName->find('all', array());// set the query function
 foreach($results as $result)
{
$header_row.= $result['Doctor']['fname']."\t". $result['Doctor']['lname'] ."\t ".$result['User']['email']." \t \n";

}
$filename = "export_".date("Y.m.d").".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo($header_row);
}

}