Category Archives: PHP

Energy Saver in Web Page

Have you imagine if your web page can do some kind energy saver like screen saver in your computer desktop? Do you want to make it happen? Then lets do it togather.

First download required file jquery.js and jquery.idle-timer.js.

Second, Copy the bellow script into your head tag in html file.
<script type="text/javascript" src="[url]/jquery.js"></script>
<script type="text/javascript" src="[url]/jquery.idle-timer.js"></script>

<script type="text/javascript">
(function($){
    var timeout = 10000;//ten second idle. change this var. 1000 means 1 sec.
    $(document).bind("idle.idleTimer", function(){
		position_popup(150,30);
		document.getElementById('popup_area_bg').style.display = 'block';document.getElementById('popup_area').style.display = 'block';
    });
    $(document).bind("active.idleTimer", function(){
		document.getElementById('popup_area_bg').style.display = 'none';document.getElementById('popup_area').style.display = 'none';
    });
    $.idleTimer(timeout);
    $('#timeout').text(timeout/1000);
})(jQuery);

function position_popup(width,height){
height = parseInt(height);
	if(!window.innerWidth){
		if(!document.documentElement.offsetWidth){
			if(!document.body.offsetWidth){
				win_width = 1000;
			}else{
				win_width = document.body.offsetWidth;
			}
		}else{
			win_width = document.documentElement.offsetWidth;
		}
		document.getElementById('popup_area').style.position ='absolute';//need only once
		document.getElementById('popup_area_bg').style.display ='none';//need only once
	}else{
		win_width = window.innerWidth;
	}
	if(!window.innerHeight){
		if(!document.documentElement.offsetHeight){
			if(!document.body.offsetHeight){
				win_height = 1000;
			}else{
				win_height = document.body.offsetHeight;
			}
		}else{
			win_height = document.documentElement.offsetHeight;
		}
		document.getElementById('popup_area').style.top ='100px';
	}else{
		win_height = window.innerHeight;
		inner_top = (win_height - height-25)/2;if(inner_top < 0)inner_top=0;
		document.getElementById('popup_area').style.top = inner_top+'px';
	}
	inner_left = (win_width - width-25)/2;if(inner_left < 0)inner_left=0;
	document.getElementById('popup_area').style.left = inner_left+'px';
	document.getElementById('popup_area').style.width = width;
	document.getElementById('popup_area').style.height = height;
}
</script>

<style type="text/css">
.inner_popup{
	display: none;
	position:fixed;
	text-align:center;
	z-index:1002;
	padding:10px;
	width: 150px;
	height: 30px;
	border: 2px solid;
	border-color:#CCCCCC;
	background-color: white;
	vertical-align:middle;
}
.outer_popup{
	display: none;
	position:fixed ;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: black;
	z-index:1001;
	-moz-opacity: 0.8;
	opacity:.70;
	filter: alpha(opacity=80);
	text-align:center;
}
</style>

Third, copy bellow script into body tag in your html file.

<div class="outer_popup" id="popup_area_bg">
</div>
<div class="inner_popup" id="popup_area">
<div style="float:left; width:100%;" align="center">
	Idle Time
</div>
</div>

By implementing energy saver in your web page, I hope, your page can save energy even only in a small amount. The more your page visited by other people, the more you help them to save energy.

Thanks to Paul Irish for jQuery idleTimer plugin so that we can make our Energy Saver in Web Page.

Refference: http://paulirish.com/2009/jquery-idletimer-plugin/

http://septiadi.com/2011/07/11/energy-saver-in-web-page/

 

 


Handle Old Open PHP Tag

Continuing my previous post PHP Auto Replace Multiple Files Content, you can esily make the old php open tag <? to be handled by new php.

You have to change your php.ini file. In php.ini file, found a row with “short_open_tag = Off” then change it with “short_open_tag = On“. After that restart your apache server.

http://septiadi.com/2011/06/24/handle-old-open-php-tag/


PHP Auto Replace Multiple Files Content

Previously my best friend told me about his problems in php. He has a bunch of php file that already outdated.These files use php 4 format. He requested me if there is a way to change the format <? used in those files into <?php that used in current php format. Therefore, I made a php script to do such thing.

This script has feature:

  • List all files in current folder except the script it self
  • Read each file one by one
  • Replace requested string
  • Save it
This is the script:
<?php
//if file is too many, there is a possibility that the script exceed the max exection time
$this_file = 'index.php';//this is the script file for exception
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";

			if($file != $this_file){

				$handle2 = fopen("$file", "rb");
				$contents = '';
				while (!feof($handle2)) {
				  $contents .= fread($handle2, 8192);
				}
				$contents = str_replace("<?", "<?php", $contents);// for replacing <? into <?php
				//for replacing deprecated function, you need regex
				echo htmlspecialchars($contents).'<hr><br>';
				fclose($handle2);

				$fp = fopen("$file", 'w');
				fwrite($fp, $contents);
				fclose($fp);
			}
        }
    }
    closedir($handle);
}
?>

Just copy the script into a folder where resides the files that you want to replace the content.

 http://septiadi.com/2011/06/22/php-auto-replace-multiple-files-content/

Import MySql From CSV

Continuing from my previous article about Export MySql Into CSV, I will explain about how to Import MySql From CSV. In this case, you will need to load the CSV file by using a php file that placed in the destination server. The php file will read the CSV file and then make a MySql query related to the content of the CSV file.

Here the php file:

$host = 'localhost';//host name, in this case we use localhost
$user = 'root';//user name, in this case we use root
$pass = 'password';//password, in this case we use password
$db = 'member';//declare the database that will be used

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$handle = @fopen("csv.csv", "r");
$content = '';
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        $content .= $buffer;
    }
}
$arr1 = explode("\n",$content);
$table = '';
foreach($arr1 as $val){
	preg_match_all('/(?<!\\\)"(.*?)(?<!\\\)"|(?<!\\\)"(.*\n.*?)(?<!\\\)"/i',$val, $matches);
	$q = "INSERT INTO `member` (`member_id`, `name`, `phone`, `address`, `status`) VALUES ('".$matches[1][0]."', '".$matches[1][1]."', '".$matches[1][2]."', '".$matches[1][3]."');";//you can change this based on the table that will you insert.
	mysql_query($q);
}
fclose($handle) or die("can't close file");

You can change the $q based on the table that you want to inser. In this case, the code above will only export-import one table. However, with little bit modification you can make your own code for export-import multiple table. Good luck.

http://septiadi.com/2011/05/30/import-mysql-from-csv/


Export MySql Into CSV

After examine the different between XML and CSV file, I found out that when you export a database to XML and CSV files, the CSV file should be smaller than the XML file. Therefore, in this article I will explain about how to Export MySql Into CSV.

This article is a little bit simillar with my previous post about Export MySql Into XML. The different is we will use CSV this time.

$host = 'localhost';//host name, in this case we use localhost
$user = 'root';//user name, in this case we use root
$pass = 'password';//password, in this case we use password
$db = 'member';//declare the database that will be used
$table = 'tos';//table that will be exported
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_array($values)) {
	foreach($rowr as $key => $val){
		if (!preg_match('#^\d+$#', $key, $match)){
			$csv_output .= '"'.$val.'";';
		}
	}
	$csv_output = rtrim($csv_output, ";");
	$csv_output .= "\n";
}

$filename = $file."-".$db."-".$table."_".date("Y-m-d_H:i:s",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
echo $csv_output;
exit;

When the file is executed, the file will generate an CSV file. I will post how to import database from an CSV file next time. Hope this simple article can help you alot.

http://septiadi.com/2011/05/30/export-mysql-into-csv/


Export MySql Into XML

Previously I just want to export several tables of my database from one server to another server. Let say, I want to send tables from server A to server B. In this case, I just make a php file that will generate xml file when executed. In this case, the php file to Export MySql Into XML will be placed in server A.

Here the codes:

//connecting to DB
$host = 'localhost';//host name, in this case we use localhost
$user = 'root';//user name, in this case we use root
$pass = 'password';//password, in this case we use password
$conn = mysql_connect($host, $user, $pass)
or die('Connection Failed');//will show "Connection Failed" if the connection failed
$db_name = 'member';//declare the database that will be used
mysql_select_db($db_name);//selecting the data base

//tables that will be exported
$tables = array("client","ib");

header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="'.$table.'.xml"');

$text ='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<'.$db_name.'>';

foreach($tables as $table){
	$result = mysql_query("SELECT * FROM  `$table`");
	$text .='
	<table_'.$table.'>';

	while($row=mysql_fetch_array($result)) {
		$text .=  "
		<$table>";
			foreach($row as $key => $val){
				if (!preg_match('#^\d+$#', $key, $match)){
					$text .=  "
					<$key>$val</$key>";
				}
			}
		$text .=  "
		</$table>";
	}

	$text .= "
	</table_$table>";
}
	$text .= "
</$db_name>";
echo $text;
mysql_close($connection);

When the file is executed, the file will generate an xml file. I will post how to import database from an xml file next time. Hope this simple post can help you alot.

http://septiadi.com/2011/05/20/export-mysql-into-xml/


PHP Session Expire

PHP Session Expire

Previously, I just search through the internet to find PHP Session Expire. However, I couldn’t find what I need.

In this case, I just want to make my system will expire the session if the user dont have activity on the page. But, I havent found php function to check the status of user, because PHP is server side. Despite of checking the user activity on the page, I rather choose to expire the session if the user not refreshing the page for some time.

Here is some code to expire the session if the user dont refresh the page.

session_start();
$timeout = 300;//in second
if(isset($_SESSION['time_stamp']) ) {
	$idle_time = time() - $_SESSION['time_stamp'];
	if($idle_time > $timeout){
		session_destroy();
		echo "Session Destroyed";
		//header('Location:logout.php');
		//some code when session is expired
	}
	else{
		$_SESSION['time_stamp'] = time();
		//refreshing time stamp
	}
}
else{
	$_SESSION['time_stamp'] = time();
	//make time stamp
}

Just to keep in mind PHP Session Expire script have to be placed on the top of every page. Hope this PHP Session Expire can help you alot.

 

http://septiadi.com/2011/05/19/php-session-expire/