Tag: PHP

Call jQuery function after all image are load

Some time we need to set equal height in our design. using below snippet we can easily call function or custom code.


// =============================================
// load portfolio list
// =============================================
function load_portfolio_list( post_length ) {

var category_id = jQuery(".portfolio-list").data('category_id');
jQuery( '.portfolio-ajax' ).addClass('loading');
jQuery.ajax({
type: "POST",
url: adminurl,
dataType: 'json',
data: { action : 'load_portfolio', post_length : post_length, category_id : category_id},
success: function (result){
jQuery('.portfolio-list .portfolio-ajax').remove();
jQuery('.portfolio-list .row').append(result.portfolio_list).imagesLoaded().then(function(){
equalheight('.portfilio-item');
});
},
error:function(){
alert("Error: There is some issue please try again.");
},
beforeSend:function(){
jQuery( '.portfolio-ajax' ).addClass('loading');
},
complete: function () {
jQuery( '.portfolio-ajax' ).removeClass('loading');
// Our code after load
}
});
}

below code are check image are loading after done function will return


// Fn to allow an event to fire after all images are loaded
jQuery.fn.imagesLoaded = function ($) {

// get all the images (excluding those with no src attribute)
var $imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return jQuery.Deferred().resolve().promise();}

// for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
var dfds = [];
$imgs.each(function(){

var dfd = jQuery.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.onerror = function(){dfd.resolve();}
img.src = this.src;

});

// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return jQuery.when.apply(jQuery,dfds);

}

WordPress file protected with user login

Some time we deed to give option to user download PDF, Doc file the protected with user login

On Download action code as like below


foreach($download_list as $list) {
$title = $list['title'];
$download = $list['download']['url'];

$path = get_home_url().'/';
$dir = '';
$resource_src = str_replace($path, $dir, $download);
$data = base64_encode($resource_src.'^'.get_current_user_id());

$url = get_site_url()."/download.php?file=$data";
?>
<li><a href="<?php echo $url; ?>" target="_blank"><?php echo $title; ?></a></li>
<?php
}

Create “download.php” file from root and add below code.


include('wp-load.php');

if( !get_current_user_id() )
{
wp_redirect(site_url('login/'));
exit;
}
$rew = explode('^',base64_decode($_GET['file']));
if($rew[1] != get_current_user_id())
{
wp_redirect(site_url('login/'));
exit;
}
$file = $rew[0];
$all = $_GET['all'];
if(isset($all)) {
if(json_decode($all)) {
$allFiles = json_decode($all);
} else {
$allFiles = explode(',',$all);

}

$zipname = 'images-'.date('YmdHis').'.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

foreach ($allFiles as $imgfile) {
$path_parts = pathinfo($imgfile);
$ext = strtolower($path_parts["extension"]);
if($ext != 'php') {
$zip->addFile($imgfile, basename($imgfile));
}
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$zipname");
header("Pragma: no-cache");
header("Expires: 0");

readfile($zipname);
unlink($zipname);
}
if(isset($file)) {
download_file($file);
}
function download_file( $fullPath ){

// Must be fresh start
if( headers_sent() )
die('Headers Sent');

// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

// File Exists?
if( file_exists($fullPath) ){

// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);

// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}

if($ext != 'php') {
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );
} else
die('Invalid File');

} else
die('File Not Found');

}

Export MySQL Database Using PHP Code

Using bellow snippet we have to download and store on server MySQL database easily. Just change database name and it’s credentials.


EXPORT_TABLES("localhost","username","password","database" ); //or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3")
function EXPORT_TABLES($host,$user,$pass,$name, $tables=false, $backup_name=false ){

$mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }
foreach($target_tables as $table){

$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount=$result->field_count; $rows_num=$mysqli->affected_rows;

$res = $mysqli->query('SHOW CREATE TABLE '.$table);

if(!$res) {
//echo $link->error;
} else {
$TableMLine=$res->fetch_row();
}
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) {
while($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 ) {$content .= "\nINSERT INTO ".$table." VALUES";}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++) { $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '"'.$row[$j].'"' ; }else {$content .= '""';} if ($j<($fields_amount-1)){$content.= ',';} }
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";} $st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}



$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";

/***********/
/* if you have to store on your server
/***********/

/*$rootPath = realpath('../auto-backup');
$rootPath = $rootPath.'/'.$backup_name;

$fp = fopen($rootPath,"wb");
fwrite($fp,$content);
fclose($fp);
/**************/


/***********/
/* if you have to download
/***********/
header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$backup_name."\""); echo $content; exit;
}

How To Create All Files And Folders Backup Using PHP

Hello Dear Friends using bellow snippet you can create your all files and folders backup.


# My Backup
$backupRootPath = realpath('../backup-folder-name/');

# Give full path to create backup for using mail or full URL.
$BackupFullPath = "http://".$_SERVER['SERVER_NAME']."/auto-backup/mybackup.zip";

# Give short path to create backup
$BackupPath = '../auto-backup/mybackup.zip';

# If you can skip folder or file type add here
$NotReqFile = array('zip','rar');

BackupZip($backupRootPath,$BackupPath,$NotReqFile,$BackupFullPath);

function BackupZip($rootPath,$backupPath,$NotReqFile,$backupFullPath){
ini_set('max_execution_time', 600); //600 seconds = 10 minutes <<open($backupPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);

# Create recursive directory iterator
# @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
# Skip directories (they would be added automatically)
if (!$file->isDir())
{

$info = new SplFileInfo($file);
$FileType = $info->getExtension();

# Change file extension in lowercase
$FileType = strtolower($FileType);

#$DirList = explode('\\',$file); #it's For Local
$DirList = explode('/',$file); #it's For Live

if(!array_intersect($DirList, $NotReqFile)) {
# If any file are not required live zip,rar Etc.
if(!in_array($FileType,$NotReqFile)){
# Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
# Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
}
}

# Zip archive will be created only after closing object
$zip->close();

}

PHP Ajax inline edit textbox

Inline Edit MySQL table field using jQuery Ajax and PHP.

Step => 1 HTML and PHP code

<td class="task"><a class="inline_edit" data-feedback_id="<?=$row['id'];?>" href="javascript:void(0);"><?=$row['task_name'];?></a>
        <input type="text" data-data_id="<?=$row['id'];?>" data-fieldname="laci_task" value="<?=$row['task_name'];?>" class="t_inline_edit textbox display0" /> 
</td>

Step => 2 jQuery and Ajax code in .js file.

jQuery(document).ready(function(e) {
    /*****/
    /* Inline Edit save field 
    /****/
    jQuery('.t_inline_edit').bind('blur keypress',function(e){
    
    var $this = jQuery(this);
        
    if(e.keyCode === 13 || e.keyCode === 9 || e.type === 'blur'){
        
        var field_id = jQuery(this).data('data_id');
        
        // field_name to fiend table name
        var field_name = jQuery(this).data('fieldname');        
        var field_value = jQuery(this).val();
        
        // send data 
        var price_data = {
            'function_name':'inline_edit',
            'field_name':field_name, // field_name to fiend table name
            'field_where':field_id,    // field_where to set set sql condition        
            'field_value':field_value
        };
        
        
        jQuery.ajax({
            url: 'ajax-file/ajax.php',
            type: 'POST',
            dataType: "json",
            data: price_data,
            success: function(data){
                //called when successful                
                if(data['message'] == 'success'){
                    $this.closest('td').find('a').text(data['values']['field_value']).show();
                    $this.closest('td').find('input').hide();                    
                    
                }else{
                    //location.reload();
                }
            },
            error: function(e){
                //called when there is an error
                console.log(e.message);
            }            
        });            
    }
    });
});
Step => 3 call Ajax in PHP file using condition in PHP file.
    /****/
    /* Edit inline
    /****/
    if(isset($_POST['function_name']) && $_POST['function_name'] == 'inline_edit' )
    {
        
        if($_POST['field_name'] == 'laci_feedback'){
            $table_name = 'laci_task';
            $field_name = 'feedback';
            $field_where = 'id';
        }
        elseif($_POST['field_name'] == 'laci_task'){
            $table_name = 'laci_task';
            $field_name = 'task_name';
            $field_where = 'id';
        }
        else{
            $return = array('result' => 'Opps !! Geting some Error.');
            echo json_encode($return);
            die;
        }
        
        $sql = "UPDATE $table_name SET
            $field_name = '".$_POST['field_value']."'
            WHERE $field_where = ".$_POST['field_where']."";
            
        //echo $sql;
        $res = mysql_query($sql);
        
        
        $return_data = array(
            'message' => 'success',
            'values' => array(
                'field_value' => $_POST['field_value']                
            ),
        );
        $return = $return_data;        
    }
    

    echo json_encode($return);
    die;

Popular post

Popular post using post view

This code using to display popular post. set those code functions.php file.

function setPostViews($postID) {
$count_key = ‘post_views_count’;
$count = get_post_meta($postID, $count_key, true);
if($count==”){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0’);
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}

After set code then next step call this function single.php file.

<?php
setPostViews(get_the_ID());
?>

And Last step is custom query for.

<?php $args = array(
‘posts_per_page’   => $post_page,
‘meta_key’            => ‘post_views_count’,
‘orderby’           => ‘meta_value_num’,
‘order’            => ‘DESC’,
‘post_type’        => ‘post’,
‘post_status’      => ‘publish’,
‘paged’            => $paged
);

$single_post = new WP_Query( $args );
while ( $single_post->have_posts() ) {
$single_post->the_post();
}
?>