RSS | Archive | Random | E-mail

About

Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.

Links

Codepuzzling main site
Development site
ByteStrike italian blog
Follow me on Twitter

My Life Style

while(passion) {
  try {
    myLife.run();
  }catch(LifeExceptions) {  
    stronger++;
    continue;
   }
}

Following

7 January 10

[PHP] Email validation considering PHP version

function isValidEmail($email)
{
	if(version_compare(PHP_VERSION, '5.2.0', '>=')
		return filter_var($email, FILTER_VALIDATE_EMAIL);
	else
		return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
}

Comments (View)
21 October 09

[PHP] Resources for programming with PDO

I’ve asked Twitter user what kind of PHP class would have used for a project and I was (and I am) in doubt between MDB2 (a PEAR Abstraction layer class) and mysqli extension. Someone has pointed out PDO, so I’m collecting some links to see what does this extension do:

Comments (View)
6 August 09

[PHP] How to retrive urls in Google sitemap into an array

This code makes use of SimpleXMLElement class.


function sitemap2array($http_url) {
   $sitemap = simplexml_load_file($http_url);
   if($sitemap !== FALSE) 
   {
	$arr = array();
        foreach($sitemap->children() as $b)
	if($b->getName() == "url") 	 
	    $arr[]= (string)$b->{'loc'};

        return $arr;
   }
}

Comments (View)
8 July 09

[PHP] How to catch warnings inside a script

Put the case you’re doing a FTP upload of a file. If the transmission fails for whatever problem, you’ll receive a warning but your app won’t stop, you’ll only be able to see that an error occurred. So you can define an error handler to catch those warnings:

// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    switch ($errno) {
	case E__ERROR:   echo "FATAL ERROR ".
                "[line: $errline] $errstr in $errfile\n"; 
                 break;
	case E_WARNING:  echo "WARNING [line: $errline]". 
                $errstr." in $errfile\n"; 
                break;
	case E__NOTICE:  echo "NOTICE [line: $errline] $errstr ".
                in $errfile\n";  
                break;
	default: echo "UNKNOWN ERROR: [line: $errline] $errstr in $errfile\n"; 
    }

    /* Don't execute PHP internal error handler */
    return true;
}

set_error_handler("myErrorHandler");

$a = 0;    $b = 2;
$c = $b/$a;
echo $c;   // not outputted
This will raise a warning:
WARNING [line: 21] Division by zero in /var/www/temp/warning.php

Tags: php debugging
Comments (View)
7 July 09

[PHP] How much memory does your app consume?

Here it is a simple function to display how much memory your PHP script is consuming.

// debug function with time, memory consumption (MB) and optional custom message
public function getMemoryUsage($message="", $echo=1) 
{
 $mem_used = memory_get_usage(true)/ 1024 / 1024;
 $mem_peak = memory_get_peak_usage(true) / 1024 / 1024;
 preg_match("/(\d)+/",ini_get('memory_limit'),$matches);  // regexp, takes only digits
 $mem_limit = $matches[0];
 $percentual = round(($mem_used * 100) / $mem_limit,2);

 $res = date("H:i:s",time())." ".$message." ";		
 $res .= "[MEM_USED: $mem_used MB ($percentual%) - Peak: $mem_peak MB]\n";
 if($echo) echo $res;
 else return $res;
}

Tags: php debugging
Comments (View)
Posted: 3:20 PM

[PHP] How to beautify XML code

If you manually write XML code without using a class like DOMDocument or SimpleXML, you’ll probably obtain a “one line file”, unless you intentionally insert break lines. As it’s a tedious work, there’s a useful PEAR class, XML_Beautifier, to do such a job. Here it is how to use it: first of all install it with pear by command line:

sudo pear install --alldeps --force XML_Beautifier
Then by considering that you have all XML content in a string variable named $xml, you can use this class in this way:
if (!$handle = fopen($file, 'w')) 
	die("Non si riesce creare il file ($file)");
else
{
	$fmt = new XML_Beautifier();
        $result = $fmt->formatString($xml);
	$bytes = fwrite($handle, $result);
	unset($fmt);
	
        if($bytes !== false) echo ("FileOK")
	else die("File KO");
}

Tags: php xml pear
Comments (View)
21 June 09

How to export to an array a MySQL query with 3 lines of code

By reading a good contribution on PHP site, I discovered this method for exporting to an array a query submitted to MySQL:
$result = mysql_query("SELECT * FROM table");
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;
array_pop($array); // removes last empty array
It produces:
Array
(
    [0] => Array
        (
            [id] => 1
            [user] => myuser
            [pass] => mypass
            ... other fields
        )
    ... and so on
That’s to say you’ll have count($array) records, of which every row has count($array[0]) fields.

Tags: mysql php SQL
Comments (View)
10 June 09

[PHP-MySQL] MySQL transaction with PHP

// require MySQL Version 4.0.12 using InnoDB type tables.
@mysql_connect("localhost","username", "password") or die(mysql_error());
@mysql_select_db("test") or die(mysql_error());
$query = "INSERT INTO trans (id,item,quantity)
		 values (null,'Baseball',4)";
begin(); // transaction begins
$result = @mysql_query($query);
if(!$result) {
	rollback(); // transaction rolls back
	echo "you rolled back";
	exit;
} else {
	commit(); // transaction is committed
	echo "Aggiornamento completato";
}

via DevArticles

See also:
Comments (View)
5 June 09

[PHP] How to retrive HTTP headers


$var = "REQUEST";

foreach (apache_request_headers() as $name => $value) {
    $var.= "$name: $value
"; } $var.= "RESPONSE"; foreach (apache_response_headers() as $name => $value) { $var.= "$name: $value
"; } echo $var;
Anyway response header returned by apache_response_headers() consists only of server signature in my case, but in firebug I can see a lot more of them.

Tags: php
Comments (View)
Posted: 4:22 PM

[PHP] How to test if a string is a number (with localization issues)

If you use is_numeric function, you could note that 45,362.00 or 45.362,00 are not numbers for this function (only one dot is permitted). So here it is a function (taken from this comment) that uses regular expression to extend is_numeric functionality:

function my_is_numeric($value)  {
    $american = preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
    $world = preg_match ("/^(-){0,1}([0-9]+)(.[0-9][0-9][0-9])*([,][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
   return ($american or $world);
}

$numbers = array("72", "15.3", "45,362.00", "45.362,00", "62.3692,00", "15:15:00", "15,3");
foreach($numbers as $val) 
	echo "$val is numeric? D: ".is_numeric($val)." M:".my_is_numeric($val)."
";
…and the result is:
72 is numeric? D: 1 M:1
15.3 is numeric? D: 1 M:1
45,362.00 is numeric? D: M:1
45.362,00 is numeric? D: M:1
62.3692,00 is numeric? D: M:
15:15:00 is numeric? D: M:
15,3 is numeric? D: M:1

Tags: php regexp
Comments (View)
Themed by Hunson. Originally by Josh