Month: April 2016

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

}

How to override javascript file in wordpress

Some time we required to override plugin and theme jQuery file to used below script.
if override plugin file add in your theme functions.php file and override theme file to add on child theme functions.php file.

function checkout_script(){
	wp_dequeue_script('wc-checkout');	
	wp_enqueue_script( 'wc-checkout', get_bloginfo( 'stylesheet_directory' ). '/woocommerce/assets/checkout.js' , array( 'jquery' ), false, true );	
}

add_action( 'wp_enqueue_scripts', 'checkout_script',1 ); 

How to get browser name and version using PHP

Get browser name and version using PHP function. This script main used detect browser internet explorer version.

/*******/
/* Get Browser Information
/*******/

function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
   
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet_Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla_Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google_Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }
   
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
   
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
   
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
   
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
} 


/*******/
/* Browser Information using PHP
/*******/
$ua = getBrowser();
$yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);


/*******/
/* Add Browser Information in WordPress body class
/*******/
add_filter( 'body_class', 'add_browser_class' );
function add_browser_class($classes){
	$ua=getBrowser();	
	$browser_class = "browser_" . $ua['name'] . " browser_version" . $ua['version'];
	
	if($ua['name'] == "Internet_Explorer" && $ua['version'] < 10){
		$classes[] = $browser_class;	
	}	
	// return the $classes array
	return $classes;
	
}