Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jul 232011
 

Check the amount of memory used by PHP

Answer:

To check the amount of memory used by PHP process, use the function - memory_get_usage

E.g.

// Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.
echo memory_get_usage(); 
Jul 092011
 

Turn off magic_quotes_gpc in PHP

Answer:

magic_quotes_gpc is a legacy PHP function that no longer be supported in PHP 6.0. So you should disable them to make sure your application not break in the future version of PHP.

To disable it, edit the php.ini

vi /etc/php.ini

Locate and set

magic_quotes_gpc = off;

Remember to restart web server such as Apache if needed.

Apr 142011
 

Validate email address using PHP

Answer:

To validate an email address using PHP, you can use the code below. (It is from www.ilovejackdaniels.com/php/email-address-validation , it is not perfect, but better than most of the average solutions found in the Internet)

<?php

function check_email_address($email) {
  // First, we check that there's one @ symbol, 
  // and that the lengths are right.
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters 
    // in one section or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
    if
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
      return false;
    }
  }
  // Check if domain is IP. If not, 
  // it should be valid domain name
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if
(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}
Mar 222011
 

Sending a UTF8 encoded CSV from PHP

Answer:

It is easy to generate a CSV file using the fputcsv function. One of a very common problems is even the file is UTF-8 encoded, Microsoft Excel is still unable to identiy the file as UTF-8.

To solve this, you need to add the UTF-8 BOM to the beginning of the file.

E.g.

<?php 

echo "\xEF\xBB\xBF" . $csvdata; // Assume $csvdata contains the CSV string you want to output
Mar 182011
 

Error control operator in PHP

Answer:

The error control operator (the @) is useful to ignore any error messages that might be generated by PHP.

E.g.

<?php

$my_value = @$my_array[$key];

The above statement will not generate any warning even if the index $key doesn't exist.