Archive for the ‘PHP’ Category.

phpMyDB – Data base class for MySql

phpMyDB is not only a class handler for MySql written in PHP, it’s also has a query cache built in, a great debugger and is damn easy to use!

I’ve wrote this class just few weeks a go since I need it for the new version of Open Classifieds (coming soon I promise, many changes).

This class uses fileCache class to be able (if you want to) to cache the query result in a really simple way (transparent to the programmer).

First Download

Usage with examples:

Constructor:
DB Constructor – connects to the server and selects a database

$ocdb = new phpMyDB(DB_USER, DB_PASS, DB_NAME,DB_HOST,DB_CHARSET);

In case of error will print using the private function print_error

Debugger:
Logs all the connection or action inside the class, you can set it on whenever you want.

$ocdb->setDebug(true);
$ocdb->returnDebug();

We set it on, and at the end of our script(or whenever you want) we should returnDebug, by default in “HTML”, but can return as an “array”.
Also you can add new “logs” with $ocdb->addLog(“any string”);

Activate cache:
Uses fileCache class. As parameter we have:
1: true or false to activate or deactivate the cache, by default false
2: Time in seconds by default 3600 (10 seconds expires in the example)
3: Path for the cache, by default cache/

$ocdb->setCache(true,10);

Normal query:
Just performs a normal query, but keeps the query counter and logs the action if debugger it’s on

$result =$ocdb->query($query);
if (mysql_num_rows($result)){
     while ($row=mysql_fetch_assoc($result)){
          echo 	$row['title'];
     }
}

getRows
Returns in rows the target query. If cache is activated automatically cache the result as an array.
Parameters:
1: Query to return values
2: Returning as “assoc” (default), “row” , “object” ,”value” (returns first field form the query)
3: Cache type “cache” or “APP” by default “cache”
Example: Cached query, returning the row as an object (cache must be activated):

$result=$ocdb->getRows($query,"object");
if ($result){//more than 1 result
	foreach ( $result as $row ){
           echo $row->title;
       }
}

Continue reading ‘phpMyDB – Data base class for MySql’ »

PHP Class for better cache – fileCache

Last days I’m working making many changes in Open Classifieds and one of them is this new class to handle the cache.

Few days a go I wrote about a cache class and longer a go about application variables for php. This is a mix of both in just one powerful class.

Explanation:

In this class we have 2 different kinds of cache.

First the normal file cache, where we store values in a single file. This is good for example to cahe an entire page.

Second we have an APPLICATION kind integrated in the cache. This means that whatever you store in the APP cache it would be kept in the same file as all the other APP. Really useful to store small amount of data, for example menus, counters etc… Remember that this file is loaded everytime yo create a new object fileCache, you need to be careful to not store many things on it.

Usage:

$cache= new fileCache();
//$cache= new fileCache(180);//second
//$cache= new fileCache(180,'cache/');//seconds and path
 
////cahe application in the same file!!!
$test= $cache->APP("test");
if (!$test){
	$cache->APP("test","value test application cache<br />");
} else echo $test;
$cache->APP("test2","value test 2 application cache<br />"); //same file as variable test
 
//end cache app
 
//normal cache in different files
$test = $cache->cache("test");//getting values from cache
if (!$test) {	//not value from cache found
	$cache->cache("test", "value test normal cache<br />");	//save cache			
}else echo $test;	
//end normal cache
 
$cache->deleteCache(60);//deletes any cache older than X seconds xD

The Class: (Download)
Continue reading ‘PHP Class for better cache – fileCache’ »

Add PDF files inside other PDF in PHP

Scenario:

We have some data sotred in a data base that must be returned as PDF.

Sounds easy but what if I tell you that between that data you need to attach other PDF files?

It makes everything more complicated. We already saw how to convert from Word to PDF in PHP and Concatenate PDF in PHP but that’s not enough…

First download in your work space TCPDF and FPDI.

Then you can use this class I did for this.
Continue reading ‘Add PDF files inside other PDF in PHP’ »

Cache Class for PHP

Just another php cache class that you can find in Internet..

The difference? super easy to use ;)

Usage:
Initialize:

$cache = new Cache();

Set expire time (by default 3600 seconds)

$cache = new Cache(15);

Set the path (by default “cache/”)

$cache = new Cache(120,"/any_other_path/");

Read a “Key”:

$value = $cache->get("some_data");

Write a “Key”:

$cache->put("some_data", "some_value");

Full example to cache a query:

$cache = new Cache();
$values = $cache->get($query);//setting values from cache
 
if ($values==false) {	//not value from cache found
	$result=mysql_query($query);
	if (mysql_num_rows($result)>0){//checking if there's more than one result
		while($row = mysql_fetch_assoc($result))  array_push($values, $row);  //feed array
		$cache->put($query, $values);	//save cache			
	}
}		
print_r($values);

The Class:
Continue reading ‘Cache Class for PHP’ »

Free SMS Notification for high server load

I’ve found in foros.ovh this interesting script that notifies high server load to you using an SMS.

All of this works thanks Google Calendar and his API.

Steps:

  • First of all you need a google account and then sign in google calendar.
  • Then go to your google calendar -> settings (right top bar) -> mobile setup
  • Follow the instructions to add you phone number.
  • After this Settings->Calendar Settings and in any of them click on Notifications.
  • Create an Event reminders, SMS 0 Minutes.

With this, now every time we create a new event in google calendar just on the time (because of that 0 minutes) we will receive an SMS to our phone.

Try it, come on!

The Script:

To make this script work you need to have Zend Gdata (http://framework.zend.com/download/gdata/) downloaded or you can download the script + Zend Gdata here.

// Config
define('EMAIL','xxxx@gmail.com');//gmail account used in google calendar
define('PASS','xxx');//your gmail password
define('SERVER_NAME','your_servername');//just as reference server name
//level of avg load http://php.net/manual/en/function.sys-getloadavg.php
define('LEVEL_EMAIL',3);//load average to notify by email
define('LEVEL_SMS',5);//load average to notify by sms
// End Config
 
//Loading Zend_Gdata libraries
ini_set('include_path', 'ZendGdata/library');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
//End Loading Zend_Gdata libraries
 
// Function to create a new Google Calendar event
function createQuickAddEvent ($client, $quickAddText) {
  $gdataCal = new Zend_Gdata_Calendar($client);
  $event = $gdataCal->newEventEntry();
  $event->content = $gdataCal->newContent($quickAddText);
  $event->quickAdd = $gdataCal->newQuickAdd('true');
  $newEvent = $gdataCal->insertEvent($event);
}
// End Function to create a new Google Calendar event
 
 
//load average
if (function_exists(sys_getloadavg)){
	$load=sys_getloadavg();
	$load=$load[0];
}
else{
	$content = file_get_contents("/proc/loadavg");
	$loadavg = explode(" ", $content);
	$load = $loadavg[0] + 0;
}
//end load average
 
 
//NOTIFICATIONS
 
// Email - Send email notification
if($load >= LEVEL_EMAIL){
    mail(EMAIL, "Alarm high server load (".$load.") ".SERVER_NAME, "");
}
 
//SMS - Add Event in Google Calendar
if($load >= LEVEL_SMS){
    $text = "Alarm high server load (".$load.") ".SERVER_NAME;
    $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // service name Google Calendar
    $client = Zend_Gdata_ClientLogin::getHttpClient(EMAIL,PASS,$service);
 
    // Hour and minute with 2 minutes delayment
    $hour= date("H");
    $minute= date("i")+2;
 
    // Creates the event in Google Calendar
    createQuickAddEvent($client, $text." ".$hour.":".$minute);
}    
//END NOTIFICATIONS

Now just put the script in you cron for example every 15 minutes,

*/15 * * * * /root/scripts/SMS_High_Server_Load/sms-load.php >/dev/null 2>&1

Other ideas, using this system is to send SMS when your site is down with this script.

Follow me