How to fix ‘Function ereg() is deprecated’ in PHP 5.3.x?

If you upgraded your PHP version to PHP 5.3.x, you will get few warnings or deprecated function messages like function ereg() is deprecated in php 5.3.x. You can find the full list of functions that are deprecated by following URL Deprecated features in PHP 5.3.x

ereg family functions are deprecated in PHP 5.3.0 or later,as these were slower and felt less familiar than the alternative Perl-compatible preg family.

To migrate ereg()

[php]ereg(‘\.([^\.]*$)’, $file_name, $extension);[/php]

becomes

[php]preg_match(‘/\.([^\.]*$)/’, $file_name, $extension);[/php]

Notice that wrapped the pattern (\.([^\.]*$)) around / /, which are RegExp delimiters.
If you find yourself escaping / too much (for an URL for example), you might want to use the # delimiter instead.

To migrate ereg_replace()

[php]$file_name = ereg_replace(‘[^A-Za-z0-9_]’, ”, $file_name);[/php]

becomes

[php]
// preg_replace($pattern, $replacement, $string);
$file_name = preg_replace(‘/[^A-Za-z0-9_]/’, ”, $file_name);
[/php]

 

If you are using eregi functions (which are the case-insensitive version of ereg), you’ll notice there’re no equivalent pregi functions.
This is because this functionality is handled by RegExp modifiers.

To make the pattern match characters in a case-insensitive way, append i after the delimiter.

[php]eregi(‘\.([^\.]*$)’, $file_name, $extension);[/php]

becomes

[php]preg_match(‘/\.([^\.]*$)/i’, $file_name, $extension);[/php]

Deprecated features in PHP 5.3.x or later

PHP 5.3.0 introduces two new error levels named as E_DEPRECATED and E_USER_DEPRECATED.

 

The E_DEPRECATED error level is used to indicate that a function or feature has been deprecated.

 

The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.

 

The following is a list of deprecated INI directives.
Use of any of these INI directives will cause an E_DEPRECATED.

define_syslog_variables
register_globals
register_long_arrays
safe_mode
magic_quotes_gpc
magic_quotes_runtime
magic_quotes_sybase
Comments starting with ‘#’ are now deprecated in .INI files.

 

Deprecated functions:

[php]
1.call_user_method()
Can be used call_user_func() instead

2.call_user_method_array()
Can be used call_user_func_array() instead

3.define_syslog_variables()
dl()

4.ereg()
Can be used preg_match() instead

5.ereg_replace()
Can be used preg_replace() instead

6.eregi()
Can be used preg_match() with the ‘i’ modifier instead

7.eregi_replace()
Can be used preg_replace() with the ‘i’ modifier instead

8.set_magic_quotes_runtime() and its alias, magic_quotes_runtime()

9.session_register()
Can be used the $_SESSION superglobal instead

10.session_unregister()
Can be used the $_SESSION superglobal instead

11.session_is_registered()
Can be used the $_SESSION superglobal instead

12.set_socket_blocking()
Can be used stream_set_blocking() instead

13.split()
Can be used preg_split() instead

14.spliti()
Can be used preg_split() with the ‘i’ modifier instead

15.sql_regcase()

16.mysql_db_query()
Can be used mysql_select_db() and mysql_query() instead

17.mysql_escape_string()
Can be used mysql_real_escape_string() instead

18.Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
The is_dst parameter to mktime(). Use the new timezone handling functions instead.
[/php]

 

Deprecated features:

       * Assigning the return value of new by reference is now deprecated.

       * Call-time pass-by-reference is now deprecated.

 

Deprecated variables:

HTTP_ENV_VARS  use $_ENV instead
HTTP_GET_VARS  use $_GET instead
HTTP_POST_VARS  use $_POST instead
HTTP_POST_FILES  use $_FILE instead
HTTP_COOKIE_VARS  use $_COOKIE instead
HTTP_SESSION_VARS  use $_SESSION instead

 

You should take care the above in the coding, so that the code will run new in versions of PHP also.

If you have some more in this list, Please share with scriptarticle.com with comments.

 

Useful PHP validation functions

String Validation
Validate name, surname by the below function to restrict only letters and spaces.

[php]
function validateString($str)
{
//accept letters and space only
return preg_match(‘/^[A-Za-zs ]+$/’, $str);
}
[/php]

Validate numeric value by the below function to restrict only numbers,you can uncomment any line according to your need.

[php]
function validateNumber($value)
{
//is_double($value);
//is_float($value);
//is_int($value);
//is_integer($value);
return is_numeric($value);
}
[/php]

Alphanumeric Characters Validation
Below function validates alphanumeric characters.ctype is complete function library in PHP.

[php]
function validateAlphanumeric($string)
{
return ctype_alnum ($string);
}
[/php]

Validation for URL Exist or not
This function will check whether a given URL exist and not only validate it.

[php]
function urlExist($url)
{
$url = @parse_url($url);
if (!$url){
return false;
}
$url = array_map(‘trim’, $url);
$url[‘port’] = (!isset($url[‘port’])) ? 80 : (int)$url[‘port’];
$path = (isset($url[‘path’])) ? $url[‘path’] : ”;

if ($path == ”){
$path = ‘/’;
}
$path .= (isset($url[‘query’])) ? ‘?$url[query]’ : ”;
if (isset($url[‘host’]) AND $url[‘host’] != @gethostbyname($url[‘host’]))
{
if (PHP_VERSION >= 5){
$headers = @get_headers(‘$url[scheme]://$url[host]:$url[port]$path’);
}else{
$fp = fsockopen($url[‘host’], $url[‘port’], $errno, $errstr, 30);
if (!$fp){
return false;
}
fputs($fp, ‘HEAD $path HTTP/1.1rnHost: $url[host]rnrn’);
$headers = fread($fp, 4096);
fclose($fp);
}
$headers = (is_array($headers)) ? implode(‘n’, $headers) : $headers;
return (bool)preg_match(‘#^HTTP/.*s+[(200|301|302)]+s#i’, $headers);
}
return false;
}
[/php]

Validation for check Image Exist
Below function will check whether a given image link exist and not.

[php]
function imageExist($url) {
if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
}
[/php]

IP Address Validation
function will validate an IP address.

[php]
function validateIP($IP){
return preg_match(‘/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/’,$IP)
}
[/php]

Validation for Proxy
This function will detect proxy visitors even those that are behind anonymous proxy 🙂

[php]
function validateProxy(){
if ($_SERVER[‘HTTP_X_FORWARDED_FOR’]
|| $_SERVER[‘HTTP_X_FORWARDED’]
|| $_SERVER[‘HTTP_FORWARDED_FOR’]
|| $_SERVER[‘HTTP_VIA’]
|| in_array($_SERVER[‘REMOTE_PORT’], array(8080,80,6588,8000,3128,553,554))
|| @fsockopen($_SERVER[‘REMOTE_ADDR’], 80, $errno, $errstr, 30))
{
exit(‘Proxy detected’);
}
}
[/php]

Strong Password Validation
Check whether a particular password filled by the user is strong enough or not.

[php]
function validatePassword($password){
//must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
return preg_match(‘/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/’, $password);
}
[/php]

Credit Card Validation
Below function validate credit card number format.

[php]
function validateCreditCard($cc){
//eg. 746486033718121
return preg_match(‘/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/’, $cc);
}
[/php]

Automatically set permission to various file types using .htaccess

Set file permissions with .htaccess, this is a great method for ensuring the CHMOD settings for various file types.

 

Apply the following rules in the root .htaccess file to affect all specified file types, or place in a specific directory to affect only those files (add/update file types according to your needs)

[sourcecode language=”plain”]
# ensure CHMOD settings for specified file types
# never set CHMOD 777 unless you know what you are doing?
# files requiring write access should use CHMOD 766 rather than 777
# keep specific file types private by setting their CHMOD to 400

chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600
[/sourcecode]

 

Require SSL (Secure Sockets Layer)

Here is an easy way you can go using .htaccess file

[sourcecode language=”plain”]
# require SSL without mod_ssl
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
[/sourcecode]

 

Guys, If you still face any issue regarding this, leave a comment in the comment box.

 

Get live currency rates in PHP and currency conversion using APIs

Get live currency rates in PHP & conversion using APIs

In the below method, we get live currency rates from Google.
This function uses CURL so make sure you have enabled curl extension in php.

 

Google has an inbuilt calculator which can also be used for converting a currency into another.Doing so is really simple, you just type “AMOUNT”, “CURRENCY_CONVERTING_FROM” in “CURRENCY_CONVERTING_TO” and search, the inbuilt calculator will give you the result.

Try this
http://www.google.com/finance/converter?a=1&from=USD&to=INR

 

Google also has a secret calculator API (http://www.google.com/ig/calculator) that is usually used for iGoogle gadgets, but its free and open, anyone can use it.
So if you want to convert a currency into another using the API, you can grab the below code.

[php]

<?php

function get_currency($from_Currency, $to_Currency, $amount) {

$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);

$url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";

$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode(‘bld>’, $rawdata);
$data = explode($to_Currency, $data[1]);
return round($data[0], 2);
}

// Call the function to get the currency converted
echo get_currency(‘USD’, ‘INR’, 1);

?>

[/php]

 

You can also do same by using live currency Value from yahoo finance (http://finance.yahoo.com/)

Here is an example to get the value of US Dollar in Indian Rupees.

[php]

<?php

$from   = ‘USD’; /*change it to your required currencies */
$to     = ‘INR’;
$url    = ‘http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=’. $from . $to .’=X’;

$handle = @fopen($url, ‘r’);
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(‘, ‘, $result); /* Get all the contents to an array */
$dollarValue = $allData[1];
echo ‘Value of $1 in Indian Rupees is &#8377; ‘.$dollarValue;

?>

[/php]

Integrate Twitter Widget to add to your website

The twitter updates are always short – under 140 characters each. Plus, one can post updates and follow her friends using the Twitter website, software on his browser, a mobile phone or instant messages. People aren’t tied to one device. This makes the twitter so popular.

 

It has grown far beyond its microblogging roots to become a fabulous tool for social messaging.

Many people use Twitter clients to update their status and read tweets, but there are also a host of useful Twitter widgets that allow you to check your tweets from your blog/website or even let people re-tweet your blog entries.

 

Display your Twitter updates on your website like this.

twitter-widget

This is one of Twitter widgets that will let you take your status updates and put them up anywhere that allows custom widgets. The great thing about the Twitter Profile Widget is that you can put your tweets on a loop.

 

Twitter provide very rich widgets, where you can easily manage it’s width, height, background colour, text colour, links, number of tweets, loop scroll etc.

 

You can produce the code by follow the below link
https://twitter.com/about/resources/widgets/widget_profile