Category Archives: PHP

Detect mobile browser (smartphone)

Detecting mobile browsers is very easy when you know the right regular expression.

Here are two examples (for PHP and JSP)

PHP

<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
 
header('Location: http://mysite.com/mobile_version');
?>

JAVA (JSP)

<%
String ua=request.getHeader("User-Agent").toLowerCase();
 
if (ua.matches(".*(android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino).*")||ua.substring(0,4).matches("1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|e\\-|e\\/|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\\-|2|g)|yas\\-|your|zeto|zte\\-"))
 
response.sendRedirect("http://mysite.com/mobile_version");
%>

More info HERE.

Detect visitor IP address with PHP

Two post in 2 days… 🙂

Here is a small PHP function to detect remote IP address (visitor IP address). This should work even if the client/visitor is behind a proxy

function getIPAddress() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
 
$ip = getIPAddress();
echo $ip;

There is not much to talk about. As you can see, the $ip variable is detected IP address.

Upgrading PHP and MySQL on CentOS or RHEL

I already wrote about upgrading via Jason Litka repo on this PAGE but in case you have problems with this repo, you can add Remi Collet repo.

First, import Remi GPG key with

#rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
# cd /etc/yum.repos.d
# wget http://rpms.famillecollet.com/enterprise/remi.repo

This file provides configuration for remi and remi-test repositories. Keep in mind that Remi repo is disabled by default so you can add –enablerepo=remi to yum command or you can edit line enabled=0 to enabled=1 inside remo.repo. For production servers I don’t recommend enabled=1 to remi-test repo.

Current PHP is 5.3.3 and MySQL 5.1.50

PHP error reporting

Error reporting in PHP is a very usable option but sometimes you can be buried with “PHP Notice” lines which you don’t need (save space and bandwith).

PHP Notice:  Undefined index: 11 in /home/website/blabla.php on line 52

To turn on reporting on all errors add this line above all other php lines (before error happens)

// Report all PHP errors
error_reporting(E_ALL);

To turn on all errors except E_NOTICE

error_reporting(E_ALL ^ E_NOTICE);

To turn off reporting (not recommended)

error_reporting(0);

To be sure that this will work, place error_reporting right below opening php tag (< ? php) More about this options can be found HERE.

Using PHP as a shell scripting language

As most of us already know, PHP is one of the most popular scripting language for developing dynamic web pages. But you probably don’t know that PHP can be used as a shell scripting language. It isn’t robust as Bash or Perl but it has some advantages.

The only difference between a PHP shell script and a regular PHP file which serves web page is the first line:

#!/usr/bin/php -q

The ‘-q’ switch is here to suppress the HTTP headers. After the first line, you just add standard PHP tags:

<?php ?>

Here is the example so you can see what I’m talking about:

#!/usr/bin/php -q
<?php
 
    print("Hi there folks !\n");
 
?>

Save these lines as test.php and execute with:

# php test.php

Good idea is to add the next lines at the beginning:

if (!isset($_SERVER["argv"][0]) || isset($_SERVER['REQUEST_METHOD'])  || isset($_SERVER['REMOTE_ADDR'])) {
	die ("<br><strong>Shell access only</strong>");
}

In this case, this script can be accessible via browser but those lines will kill the script in case if it is issued via browser.

Upgrading to PHP 5.2.5 on RHEL and CentOS

As you probably know, the latest CentOS and RHEL distros are available only with PHP 5.1.6 and if you want to upgrade PHP, you need to install it manually (or to find someone to do it for you 🙂 ). The 5.2.5 release brings several security enhancements, more than 60 bug fixes, and improved performance for those of you that like arrays (and really, who doesn’t?). I wanted to install latest RoundCube webmail application and it won’t work if you don’t have PHP> 5.2. Also, latest Vivvo won’t work without 5.2.x

So, if you don’t want to build rpms or to go through ./configure, make, make install nightmare, you can enable Jason Litka yum repository to your RHEL or CentOS system. To do this please follow next few steps.

First you need to validate that the packages came from Jason Litka and you’ll do it with next command:

#rpm --import http://www.jasonlitka.com/media/RPM-GPG-KEY-jlitka

After you added his public GPG key, you’ll need to adjust yum so he can search at his repo. To do this, please follow next steps:

#nano -w /etc/yum.repos.d/utterramblings.repo

Now copy next lines inside this file and save those changes.

[utterramblings]
name=Jason's Utter Ramblings Repo
baseurl=http://www.jasonlitka.com/media/EL$releasever/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://www.jasonlitka.com/media/RPM-GPG-KEY-jlitka

Now you can upgrade your PHP installation with simple:

#yum update php

More information about this can be found HERE.

#php -v

should return

[root@ns1 ~]# php -v
PHP 5.2.6 (cli) (built: May  5 2008 10:32:59)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
[root@ns1 ~]#

I forget to say that you should restart httpd after upgrade.