PHP
PHP, source code, scripts, developing, tips & hints
Get visitor IP address – PHP
9Simple code of the day:
function getIp(){//obtain the ip // if getenv results in something, proxy detected if (getenv('HTTP_X_FORWARDED_FOR')) { $ip=getenv('HTTP_X_FORWARDED_FOR'); } else {// otherwise no proxy detected $ip=getenv('REMOTE_ADDR'); } return $ip; }
Anyway of doing this better?
PHP Set format date
6Just a function to change the format of a mysql date to the one you want to.
function setDate($L_date,$L_dateFormat="dd-mm-yyyy"){//sets a date in a format if(strlen($L_date)>0){ $L_arrTemp = split(" ",$L_date); $L_strDate = $L_arrTemp[0]; // 2007-07-21 year month day $L_arrDate = split("-",$L_strDate);// split date $L_strYear = $L_arrDate[0]; $L_strMonth = $L_arrDate[1]; $L_strDay = $L_arrDate[2]; if($L_dateFormat == 'yyyy-mm-dd'){//default return $L_arrTemp[0]; } elseif($L_dateFormat == "dd-mm-yyyy"){//day month year $returnDate = $L_strDay."-".$L_strMonth."-".$L_strYear; return $returnDate; } elseif($L_dateFormat == "mm-dd-yyyy"){//month day year $returnDate = $L_strMonth."-".$L_strDay."-".$L_strYear; return $returnDate; } } else return false; }
PHP sitemap.xml generator
2Any web page should use a sitemap.xml, it’s really important for the bots to crawl your site properly.
But how to make it work using PHP?
This is the way I do it for Open Classifieds:
First of all I use to defines, for the path of the file, and when it would expire:
define(SITEMAP_FILE,"sitemap.xml.gz"); define(SITEMAP_EXPIRE,3600); //seconds
At the beginning of any of your scripts we check if the sitempa it’s expired, if it’s expired we generate another time the sitemap :
(more…)
phpMyDB – Data base class for MySql
10phpMyDB 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; } }
PHP Class for better cache – fileCache
11Last 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 cache 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.
The latest version of the class chooses which is the best option of storage engine, based on the size of the variable. Then for example an entire page HTML will be in a single file, and a number or a person name would be in the APP cache.
Usage:
$cache = fileCache::GetInstance(30,'cache/');//creating new instance singleton $cache->setDebug(true);//this runs the debug and in destruct prints it //normal usage $cache->cache('test','test values for the var!!!!'); echo $cache->cache('test');//get //overloads $cache->anyvar='tes asd asd aasdasdasda sada ast';//overload of set and get methods echo $cache->anyvar;//get overload var_dump(isset($cache->anyvar));//isset and unset are overloaded unset($cache->anyvar); //clear $cache->deleteCache();//deletes all the cache $cache->deleteCache(60);//deletes any cache older than X seconds
Add PDF files inside other PDF in PHP
7Scenario:
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.
(more…)
Cache Class for PHP
4Just 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:
(more…)
Free SMS Notification for high server load
9I’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','[email protected]');//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.
Concatenate PDF in PHP
39As requirement for one project we need it to concatenate PDF files to have just one file as input.
First download in your work space TCPDF and FPDI
Class to concatenate pdf, pdfConcat.php:
require_once("tcpdf/tcpdf.php"); require_once("fpdi/fpdi.php"); class concat_pdf extends FPDI { var $files = array(); function setFiles($files) { $this->files = $files; } function concat() { foreach($this->files AS $file) { $pagecount = $this->setSourceFile($file); for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $this->ImportPage($i); $s = $this->getTemplatesize($tplidx); $this->AddPage(’P', array($s['w'], $s['h'])); $this->useTemplate($tplidx); } } } }
Usage:
include_once("pdfConcat.php"); $pdf =& new concat_pdf(); $pdf->setFiles(array("doc.pdf","pauta.pdf", "4bp.pdf", "5bp.pdf")); $pdf->concat(); $pdf->Output("newpdf.pdf", "I");
After this I recommend to you to keep the file already merged in the server, then you will not need to generate it another time. To do this you can use $pdf->Output(“newpdf.pdf”, “F”); instead.
TimeZone select for PHP
5Simple script that returns to us a list with possible TimeZones:
<select id="TIMEZONE" name="TIMEZONE"> <?php $timezone_identifiers = DateTimeZone::listIdentifiers(); foreach( $timezone_identifiers as $value ){ if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){ echo "<option>$value</option>"; } } ?> </select>
Improved version:
<select id="TIMEZONE" name="TIMEZONE"> <?php $timezone_identifiers = DateTimeZone::listIdentifiers(); foreach( $timezone_identifiers as $value ){ if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){ $ex=explode("/",$value);//obtain continent,city if ($continent!=$ex[0]){ if ($continent!="") echo '</optgroup>'; echo '<optgroup label="'.$ex[0].'">'; } $city=$ex[1]; $continent=$ex[0]; echo '<option value="'.$value.'">'.$city.'</option>'; } } ?> </optgroup> </select>
Be aware this will only work in PHP 5.2.0 or greater as they explain in the doc