Absolutely Tech

[SOLVED] ‘Error at offset’ error in unserialize()

I came across this weird error in unserialize() where it refused to unserialize the serialized data. After hours of trying different things to solve it, finally converting the encoding worked.

The solution to the problem is to use the following function instead of unserialize():

function safe_unserialize($str){
       return unserialize( trim( mb_convert_encoding( $str,'auto','UTF-8' ) ) );
}

Cheers!

[HOWTO] Fix Twitter clients (or PHP scripts) which use basic authentication.

As you probably know, Twitter completely ditched basic authentication method on August 31st, 2010. It now supports only OAuth method of authentication which complicates the coding process multiple folds. Scripts which were previously 20 lines long now span several files.

While there are numerous advantage of Oauth like client doesn’t need to know your password, increased security etc, lots of twitter clients which used basic authentication stopped working right away after Aug 31st.

However, there had to be someone to the rescue. This time it’s http://www.supertweet.net/. They act like a proxy between twitter and your app, converting all basic authentication requests to oauth requests. So practically, twitter will be getting oath requests and your app would still be making basic authentication requests. This would help the twitter clients or php scripts to still use the same code and function just like before.

Documentation:
http://www.supertweet.net/about/documentation
The process is pretty simple and you should get through everything without a hitch.

You just have to change the API url from http://api.twitter.com/ from the application settings or PHP code to http://api.supertweet.net/.

If you still have problems, post it in comments.

Cheers!

[HowTo] Check your php and server information using phpinfo()

We can check the php configuration, apache’s loaded modules and all other kinds of PHP configuration using a simple function called phpinfo(). Create a file called infophp.php in your web’s root directory and put the following code in it:

<?
phpinfo();
?>

This would output all the php configuration info and apache information. You can pass on an argument to phpinfo() to limit what information is displayed. You can checkout the phpinfo documentation here.

PS: This is a beginner tutorial for absolute beginners.

[HOWTO] Send emails(using mail function) from localhost in PHP through msmtp (using gmail account) on Linux

There’ve been lots of times when I wanted to use the mail() function on my local server. I am sure lots of you would’ve been wanting it too but most of you would’ve settled for PHPMailer or just used a web host to test the code instead. I myself had been doing the same until recently when I finally decided to do some research and get it to work.

Here are the steps in short for the geeks who like to do things on their own:
All I did was used smtp client called msmtp, configured it to work with my gmail account and configured PHP to use msmtp to send emails.

This tutorial is only applicable for linux users. I’ll write another article for windows users soon when I get my hands on a windows box.
All the commands used in the instructions are for Ubuntu, however you may use corresponding commands for your distro (for eg; you can use yum install instead of apt-get install on fedora, redhat, centos.

Step by step instructions:

Read the rest of this entry »

[HOWTO] Validate Email-address in PHP using Regular expressions (the correct way)

Here’s a function which thoroughly checks email-address and returns true for a valid email address and returns false for invalid one. I thought it was worth sharing so I posted it on my blog. You will find the source link at the bottom.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email 
address format and the domain exists.
*/
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

Usage Example:

if(validEmail($_POST['email']))
echo 'Valid Email';
else
echo 'Invalid Email';

Source/Reference

Cheers!

[SOLVED]‘Error establishing a database connection’ in wordpress

One of my clients got this error in his wordpress:

Error establishing a database connection

It is one of those vague errors which give very little information about what caused it. On going to /wp-admin, it gave error:

One or more database tables are unavailable. The database may need to be repaired.

I added “define(‘WP_ALLOW_REPAIR’, true);” in wp-config.php and clicked on ‘repair’, it showed that all tables have been repaired but I was still getting the error about wordpress not being able to connect with database. It was actually able to connect but there was some other problem. I checked if any table was missing from the database, but it was not.

Finally after 2 hours of searching for a solution, I found it. In wp-options table, just make sure the option_value for the option_name ‘siteurl’ is your site’s url. You can also do this by executing the following sql statement (you can use phpmyadmin):
Read the rest of this entry »

Passing variable number of arguments to a function in PHP

We all know about functions and how we can pass arguments to it. But did you know that we can pass variable number of arguments in a function?

Consider a function sum() which adds numbers passed into its arguments. Now we want it to add all the numbers passed onto the arguments. Eg; if we call sum (21, 45) or sum (45, 23, 78, 56, 90) it should add all of them. Even if we pass a 100 arguments, it should execute successfully.

Below is the code for making the function sum() :
Read the rest of this entry »

[SOLVED] Flush(), ob_flush() not working in PHP (Disabling gzip through htaccess)

Flushing the output buffer doesn’t works in PHP sometimes no matter what you do. I had this code which would never work on my server but would perfectly fine on localhost. This was the code.

<?php
include('common.php');
ini_set('output_buffering','on');
ini_set('zlib.output_compression', 0);
//ini_set('implicit_flush',1);
ob_implicit_flush();
for($i=0;$i<10;$i++) {
      echo $i;
      echo str_repeat(" ", 500);
      ob_flush();
      flush();
      sleep(1);
}
?>

Read the rest of this entry »

Missing alphabet check (is_alpha) in PHP

Well, you might have seen a huge number of variable checks ranging from is_file(), is_array() to is_numeric() and is_int(). While developing a script today I wanted to check for alphabets. I directly used is_alpha() but to my surprise it wasn’t defined.

Read the rest of this entry »

Using CodeIgniter’s Email library separately

I’ve developed my own libraries for rapid development of PHP applications. Email library is one area which I didn’t feel like developing a library for. Just then, I remembered how simple and robust CodeIgniter’s Email class was. I decided to try it on my own script. It was not at all difficult to get it working. It just commented out few lines of codes and voila! I was able to send my first email.

Those who are in need of a email library could use this simple library separately. I’ll guide you through the whole process step by step.

First thing you need to do is copy the Email.php from system/libraries folder and place it inside your script. Then use your favorite IDE to edit these lines:
Read the rest of this entry »