PHP Function to return readable mysql timestamps

Something almost every PHP app needs is a way to take Mysql timestamps and convert them to a readable format. So, I went and wrote a few functions to handle this. I used PHP’s date function and strtotime to make this happen. You can edit what it returns by understanding how PHP’s date function works.

Here is the function:

function stampfixer($data) {if($data=='0000-00-00 00:00:00' or $data==''){return '';} else{ $cdate = strtotime($data);return date("m-d-Y h:i A",$cdate); }}

This function will take a timestamp you throw at it and turn it into something like this:

01-01-1980 12:00 AM

You can change it to not show the AM/PM, 24 hour format instead of 12, just about anything by editing:

return date("m-d-Y h:i A",$cdate)

See PHP date function for what variables to throw at it to get it to do what you want.

Questions, comments, feel free to say something.

Lowercase everything in string, upper case first letter in sentence

Another quick and easy one. Using ucfirst, strolower, and a few other functions. In this case my string is called $whyexp but you can change it to whatever you want just make sure you change of of them.

$whyexp = ucfirst(strtolower($whyexp));
$whyexp = preg_replace_callback('/[.!?].*?\w/', create_function('$matches', 'return strtoupper($matches[0]);'),$whyexp);
$whyexp = str_replace(" i "," I ", $whyexp);

The bottom line find’s all the letter I(‘s) and then converts them to upper case. Since the first line drops all the letters down to lower case, the second capitalizes all the first letters in the sentences, and the third cleans up all the lower case I(‘s) (if any…) to upper case.

Bare in mind if you have all abbrevaitions for something in the string that needs to be upper case add another line like the third one.

$whyexp = str_replace(" abs "," ABS ", $whyexp);

In this case I used ABS as an example. By adding that line, all the abbrevaitions for ABS are converted back to uppercase ABS. You can add as many lines as you need. You may also want to consider doing it in an array.

PHP Function to return readable mysql timestamps

Something almost every PHP app needs is a way to take Mysql timestamps and convert them to a readable format. So, I went and wrote a few functions to handle this. I used PHP’s date function and strtotime to make this happen. You can edit what it returns by understanding how PHP’s date function works.

Here is the function:

function stampfixer($data) {if($data=='0000-00-00 00:00:00' or $data==''){return '';} else{ $cdate = strtotime($data);return date("m-d-Y h:i A",$cdate); }}

This function will take a timestamp you throw at it and turn it into something like this:

01-01-1980 12:00 AM

You can change it to not show the AM/PM, 24 hour format instead of 12, just about anything by editing:

return date("m-d-Y h:i A",$cdate)

See PHP date function for what variables to throw at it to get it to do what you want.

Questions, comments, feel free to say something.

Lim_Registry – PHP Lazy Registry Class

Lim_Registry is a PHP Registry class met ondersteuning voor “lazy loading”. In dat geval wordt er pas een instantie van een class aangemaakt, wanneer deze uit het register wordt opgehaald. Hetzelfde geldt eventueel voor een callback functie.

Hoe werkt het?

// set
Registry::set('site_title', 'My Site Title');
Registry::setLazyClass('db', 'DBConnection');
Registry::setLazyCallback('avg', 'getAverage');

// get
$value = Registry::get('site_title');

// is loaded (and not in lazy state)
$loaded = Registry::isLoaded('db');

// exists?
$exists = Registry::has('site_title');

// remove
Registry::remove('site_title');

Voorbeeld “by reference”

// set by ref
$arr = array('One', 'Two', 'Three');
Registry::setByRef('numbers', $arr);

// get by ref
$ref = & Registry::getByRef('numbers');

arr[0] = 'Ten'; // -> $ref[0] === 'Ten'

API

Static methods

  • Registry::getInstance()
  • Registry::defaultOverwrite( $overwrite = null )
  • Registry::throwExceptions( $throwExceptions = null )
  • Registry::set( $key, $value, $overwrite = null )
  • Registry::setByRef( $key, & $value )
  • Registry::setLazyClass( $key, $class, $args = array(), $overwrite = null )
  • Registry::setLazyCallback( $key, $callback, $args = array(), $overwrite = null )
  • Registry::get( $key, $reload = false )
  • Registry::getByRef( $key )
  • Registry::has( $key )
  • Registry::isLoaded( $key )
  • Registry::remove( $key )
  • Registry::clear()

Downloaden

Je kan de laatste versie downloaden van Github.

How to combine two arrays into one and three arrays into one in PHP

I found a nice snippet for combining two arrays into one. I’d love to credit the original source, but unfortunately I can’t remember it and I can’t seem to find it in Google anymore. If you are the original author or know who they are, please let me know so I can credit accordingly.

Here is the code for combining two arrays into one:

<?php

function array_combine($arr1, $arr2) {
$out = array();

$arr1 = array_values($arr1);
$arr2 = array_values($arr2);

foreach($arr1 as $key1 => $value1) {
$out[(string)$value1] = $arr2[$key1];
}

return $out;
}

?>

That’s all well and good, but I had three arrays that I needed to combine into one. So I modified the above code to come up with this, it combines three arrays into one multidimensional array:

<?php

function double_array_combine($arr1, $arr2, $arr3) {
$out = array();

$arr1 = array_values($arr1);
$arr2 = array_values($arr2);
$arr3 = array_values($arr3);

foreach($arr1 as $key1 => $value1) {
$out[(string)$value1][0] = $arr2[$key1];
$out[(string)$value1][1] = $arr3[$key1];
}

return $out;
}?>

So that’s pretty simple. If you want to combine four arrays into one and so on, just add more arrays to the code according to the above example. So how do you use these functions? Well, let’s say you have these three arrays: $name, $address, $phone. You want to combine the three into one array. Just include the above code in your script, and then use this script to call the function:

<?php

$new_array=double_array_combine($name, $address, $phone);

print_r($new_array); // this will print out the contents of your new array

?>

Keyword parsing: separating words by capital letters in PHP

I was trying to create a simple routine for separating the keywords within a domain name based on user input of capitalized words. For example, the user might input:

https://ucw18.com/vn/keonhacai

This should be parsed into the term “my domain name” based on the capital letters signifying the first letters of each word.

As usual, I Googled to see if someone had already done this, no use reinventing the wheel. However, I did not really find anything good, so I decided to tackle the problem myself. Here’s the code I came up with:

<?php

$ctype_test = preg_replace(’/[^a-zA-Z]/’, ”, $domain_name);

// the above line gets rid of everything except letters
if (!ctype_lower($ctype_test) and !ctype_upper($ctype_test)) {

// check whether there are BOTH upper and lowercase letters in the domain name

// otherwise there is no sense in continuing with the routine
for ($i=0;$i<strlen($domain_name); $i++){     // loop as many times as the string is long
$string_split[$i]=$domain_name[$i];
if (ctype_upper($string_split[$i]) AND $i>0){  // if there is an uppercase letter
$string_split[$i]=” “.$string_split[$i];         // then add a space in front of the letter
}
}

foreach($string_split as $value){     // loop through all the letters
$term=$term.$value;                // add each letter to the TERM to make up the parsed term
}

$term=strtolower($term); // finally, make the term all lowercase

?>

Maybe there’s a better way to do it, but I though this was nice & simple.

Mac OS X How to Clean Desktop – Clear Desktop Icons

OK, this post is unrelated to php, but I figured I’d blog it anyway for the possible benefit of other Mac OS X users.

If you’re like me, your desktop will accumulate clutter very fast. At the end of a workday, it looks messy, uses up memory and things become difficult to find.

An easy way to clean your Mac desktop – I do this every day – is to use the Terminal application (shell), and type these commands:

(everything between ~ and $ represents the prompt so don’t type this. Type only the text I’ve written in italic. The ~ sign means you’re in your home folder)

~$ cd desktop

~/desktop$ mkdir desktop090709

~$desktop$ mv * desktop090709

That’s it. Your desktop becomes magically clean in a split second, and all files are stored in a folder named ‘desktopDDMMYY’. This way you’ll only ever have two icons on your desktop: The main hard drive and the latest desktop backup folder.

Since Mac OS X has the incredibly efficient Spotlight search feature, you don’t need to worry about where your files are stored. This leads me to another tip: Always name your files descriptively, so you can easily find them with the Spotlight ‘in file name’ search. For instance, if you write a travel diary entry about your day at the beach, name the file ‘travel-diary-june-2009-Santa-Monica-beach-with-kids-surfing-and-ice-cream.rtf’. It doesn’t matter that the file name is long. What matters is that it’s intuitive to find.

Anyway, next time, back to PHP.

ServerHub Launches High Availability Web Hosting Plans

ServerHub, has announced today that it has successfully launched it’s new line of High Availability Web Hosting products.

Beginning today ServerHub has entered into the market of Shared Web Hosting by launching three new high availability, RAID protected Web Hosting offerings.

Starting at just $14.99 for an Essentials Plan customers receive 7GB of RAID10 protected storage, 150GB of premium multi-homed bandwidth and one Free Domain for the first year with every new hosting plan purchased. All Web Hosting plans are placed on High Availability Intel Xeon Powered Servers with a minimum of 32GB of memory and Solid State Drives (SSD) that utilize Hardware RAID cards with SSD Caching.

ServerHub.com Launches High Availability Web Hosting Plans

“We are very excited about the launch of our new High Availability Web Hosting Service. We have tested our configurations for quite some time with a small number of our current customers with great success. There is a lot of “Web Hosting” offerings in our industry, but not everybody can offer an outstanding product that has rock-solid reliability and truly stand by the product.” says John Brancela, Chief Executive Officer of ServerHub

In the announcement, the company says that it will also be providing other value added services with the offering such as Softaculous Auto Installer as well as hundreds of Do It Yourself Website Templates to enable Web Hosting customers to get up and running within minutes.

Offers Low Cost Web Hosting Plus Free SEO

gophpbb.com, provider of low-cost web hosting, domain registration and maintenance services, announced today the launch of its brand new website. Cheap domains start at £3.49 per year.

The new site features a fully integrated client area with 24-hour support, where customers can log in and manage all the Raid Host products and services to which they subscribe, including domain registration, website hosting, reseller hosting, VPS hosting and Dedicated Servers.

“We provide an incredibly high level of service at an affordable price,” said Raid Host managing director Calvin Robbins. “Unlike the vast majority of web hosting providers, our customers don’t have to worry about restrictive limits and over capacity servers. We absolutely guarantee 99.9 percent uptime.”

Customers can choose one of four web hosting plans from the company’s low-cost pricing structure:

£1.99/mo, Lite Package with 500Mb disk space, 50Gb bandwidth and 1 e-mail account
£4.99/mo, Elite Package with 10Gb disk space, 100Gb bandwidth and 10 e-mail accounts
£9.99/mo, Deluxe Package with 25Gb disk space, 250Gb bandwidth and 50 e-mail accounts
£14.99/mo, Ultimate Package with 45Gb disk space and unlimited bandwidth

No contract is required, don’t need a lot of money and customers can easily upgrade or purchase bolt-ons at any time. All domain names include free Domain Privacy Protection, as well as managed DNS and e-mail/domain forwarding.

As a “grand opening” special of sorts, Raid Host is offering two months free web hosting to new clients who pay yearly for hosting services, as well as three months’ free SEO from partner provider Click Submit.

How to choose a CPU for your dedicated server

If you want to purchase a new dedicated server for your web site, you need to know how to choose a CPU for your dedicated server upfront. There are many alternatives of CPU, RAM and Operating System for dedicated servers. In this article We are going to help you choosing a CPU for your dedicated server.

Processors

Mostly there are two brands in the market, Intel and AMD. Generally speaking there aren’t many alternatives of AMD CPUs and most likely you will choose an Intel CPU. The most important thing is choosing the right CPU for your needs. Intel has various CPUs for different users. These are Intel I3, Intel I5, Intel I7 and Intel Xeon processors. All of these processors satisfies certain criterias for your needs. For example if you are using your server just for visitors and if you don’t have many visitors picking an Intel I3 processor is enough, but if you are using the server for your development purposes such as producing videos or images you need a high processing power thus Intel Xeon processor is going to be your best pick.

Intel CPU Details

 

There are many sites that can help you to inspect a processor. http://ark.intel.com is the official web site for Intel processors. You can see the number of cores, number of threads, base frequency, max frequency and cache memory of a particular CPU. These details will help you compare various CPUs and decide which one to choose.

CPU Benchmarking Scores

One other thing you can compare is benchmarking scores of processors. Benchmarking shows processor scores and you can directly compare these scores when choosing your processor. http://www.cpubenchmark.net is a web site that shows benchmarking scores of many CPUs. The site benchmarked more than 600,000 CPUs. There are High End, High to Mid Range, Low to Mid Range and Low End CPU charts available so that you can see the place of your CPU in its class.

As a conclusion, choosing the right CPU for a dedicated server is very important, but please consider a certain visitor increase and processing power needs before and choose accordingly. In our opinion choose minimum an Intel I7 processor since the price differences are not that much.

WHMCS (Web Host Manager Complete Solution)

What is WHMCS?

WHMCS (Web Host Manager Complete Solution) is a PHP script which offers all-in-one solution to web hosting companies. Client management, billing and support tasks are fully automated with this script. So if you want to start a web hosting business from scratch or if you want to fully automate all crucial tasks, WHMCS seems to be the mostly used and proven solution for your needs.

What does WHMCS exactly do for you?

It offers a pleasant web hosting experience for both the clients and the company. Lets have a brief look at some main WHMCS features:

Billing, Payment and Ordering

  1. Create custom products, bundles, plans and promotions
  2. Manage product stocks if there is any limit
  3. Create fully customisable, professional looking invoices
  4. Use multiple currencies at the same time
  5. Enable and manage taxation
  6. Create one off and recurring plans
  7. Integration with over 75 payment gateways (PayPal, Skrill, WorldPay etc.)
  8. Allow clients to deposit funds
  9. Setup automated unpaid invoice reminders for clients
  10. Allow support ticket billing
  11. Setup late fees for overdue invoices
  12. Automated payment, credit card and billing processing

Client Management

  1. Automated creation, suspension and termination of clients and services (Integration with popular admin panels such as cPanel and Plesk Panel and more)
  2. Easy password management
  3. Integrated fraud checking
  4. Send “Welcome emails”

Support Automation

  1. Support ticket system
  2. Social integration
  3. Manage announcements
  4. Build a knowledgebase
  5. Setup auto responders

There are many more features which you can check by visiting Offiical features list.

These awesome features come with a price of course. You can either pay once and own the license or you can start with a low monthly price to get a start. For $15.95 per month, you can serve up to 250 clients which makes $0.16 cost per client!

How to upload a video with dailymotion data api using php

Dailymotion is one of the popular video sharing web sites. Users can share and watch videos from this website. There is an opportunity for users to share and earn revenue from their videos like YouTube. Users can upload videos either using the website and with the dailymotion php api. Uploading videos from the website is fairly easy but you can not schedule an upload task with it. In this article we will show you how to upload a video with dailymotion data api using php.

Creating Dailymotion DATA API credentials
In order to use dailymotion data api you need to have an authorisation to the website. This authorization consist of an apikey, apisecret, username and password. You need to create an apikey and apisecret from dailymotion developer console (http://www.dailymotion.com/settings/developer).

create-dailymotion-api-keyWrite your channel name into application name box, write a description into application description, write a website address into Application Website box (generally this website address is used for embedding a video player into a website but you can enter your development servers website address into this box), write a purpose into Application Purpose box, if you need a dynamic callback url you can define it in the Callback URL box and lastly you can upload your custom application icon by using this form. After filling out this form in developer settings page you will have an api key and api secret. You will later use these credential in a php script file.

Dailymotion PHP SDK
There are PHP, JavaScript, Objective-C, Python and Android SDKs and their links to the related files in the dailymotion developer tools page (https://developer.dailymotion.com/tools/sdks). The latest version of Dailymotion PHP SDK can be downloaded from GitHub (https://github.com/dailymotion/dailymotion-sdk-php). You don’t need to edit this PHP file to use the API, just link this file into your video uploader php script file by php require once command.

<?php
require_once ‘Dailymotion.php’;
Dailymotion video uploader php script file
The last part of the process is creating a video uploader php script file. In this file you will write your Dailymotion DATA API Credentials and details of the video. You can use below php script example while creating your file.

<?php
require_once ‘sdk/Dailymotion.php’;

// Dailymotion DATA API credentials
$apikey = ‘Your API Key’;
$apisecret = ‘Your API Secret’;
$user = ‘Your user email address’;
$password = ‘Password’;

$api = new Dailymotion();
$videotitle = “Title of the video”;
$videofile = “Actual path of the video”;
$videocategory = “Category of the video”;
$videotags = “Tags of the video”;
$videodescription = “Description of the video”;

$api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apikey, $apisecret, array(‘write’,’delete’), array(‘username’ => $user, ‘password’ => $password));
$url = $api->uploadFile($videofile);
$result = $api->call(‘video.create’, array(‘url’ => $url, ‘title’ => $videotitle , ‘channel’ => $videocategory , ‘tags’ => $videotags, ‘description’ => $videodescription, ‘published’ => true));
$videourl = ‘http://www.dailymotion.com/video/’.$result[‘id’];

?>