Aditya Kothadiya's Blog

Entrepreneurship, programming, design, productivity, books, philosophy and more.

Archive for the ‘php’ tag

The PHP Benchmark

Comments

I just stumbled upon a website called PHP Benchmark. It’s a great resource to learn PHP tips for improving performance and speed. These are not advanced tips, but rather very simple tips that we generally don’t pay attention to in our day-to-day programming.

Here is one example -

Is it worth the effort to calculate the length of the loop in advance?

E.g. Should we use


for ($i = 0; $i < $size; $i++)

instead of


for ($i = 0; $i < sizeof($arr); $i++)

The performance result for a loop with 1000 keys with 1 byte values is as below -

With pre calc – count(): Total time: 229 µs
Without pre calc – count(): Total time: 99702 µs
With pre calc – sizeof(): Total time: 235 µs
Without pre calc – sizeof(): Total time: 99610 µs

So it’s very clear that calculating the length of array in advance is way faster than calculating it in the loop.

I hope you’ll find other tips from PHP Benchmark website very useful too.

Written by Aditya

April 18th, 2009 at 10:00 am

Posted in Programming

Tagged with , ,

Verifying Twitter account credentials using Symfony validator in PHP

Comments

If you’re using Symfony – a PHP’s MVC framework to develop your web application, and if your application interacts with Twitter, and if you need Twitter user’s credentials to access his or her data from Twitter, then this might be useful to you.

Here is a simple Twitter class -

<?php
class Twitter {
private $credentials;

function Twitter($username, $password) {
$this->credentials = sprintf("%s:%s", $username, $password);
}

function verifyCredentials($format = NULL) {
$api_call = sprintf("http://twitter.com/account/verify_credentials%s", ($format != NULL) ? sprintf(".%s", $format) : NULL);
return $this->APICall($api_call, true);
}

private function APICall($api_url, $require_credentials = false, $http_post = false) {
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $api_url);

if ($require_credentials) {
curl_setopt($curl_handle, CURLOPT_USERPWD, $this->credentials);

}
if ($http_post) {
curl_setopt($curl_handle, CURLOPT_POST, true);
}
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
$twitter_data = curl_exec($curl_handle);

curl_close($curl_handle);
return $twitter_data;
}
}
?>

Then here is the simple action to handle form –

public function executeTwitterLogin()
{
if ($this->getRequest()->getMethod() == sfRequest::POST)
{
$username = $this->getRequestParameter('username');
$password =  $this->getRequestParameter('password');

// Your business logic here...
}
}

Here is the action to handle error for TwitterLogin action –

public function handleTwitterLogin()
{
return sfView::SUCCESS;
}

Here is a simple template with the form asking for the Twitter login credentials -

<?php use_helper('Validation', 'Form') ?>

<?php echo form_tag('@twitter_login') ?>

<p>Please enter your Twitter account's login credentials below.</p>

<?php echo form_error('username') ?>
<label for="username">Twitter Username:</label>
<?php echo input_tag('username', $sf_params->get('username')) ?>

<?php echo form_error('password') ?>
<label for="password">Twitter Password:</label>
<?php echo input_password_tag('password') ?>

<?php echo submit_tag('Login') ?>
</form>

Here is the twitterLogin.yml validator file –

methods:
post: [username, password]

names:
username:
required:     true
required_msg: Your Twitter Username is required.
validators:   userValidator

password:
required:     true
required_msg: Your Twitter Password is required.

userValidator:
class:        twitterLoginValidator
param:
password:    password


And finally, here is the custom class which is extended from sfvalidator for authenticating Twitter login details.

<?php
class myTwitterLoginValidator extends sfValidator
{
public function initialize($context, $parameters = null)
{
// initialize parent
parent::initialize($context);

// set defaults
$this->setParameter('error', 'Your Twitter account credentials are incorrect.');
$this->getParameterHolder()->add($parameters);

return true;
}

public function execute(&amp;$value, &amp;$error)
{
$password_param = $this->getParameter('password');
$password = $this->getContext()->getRequest()->getParameter($password_param);

$username = $value;

// Verify Twitter Credentials
$twitter = new Twitter($username, $password);
$resp_xml = $twitter->verifyCredentials('xml');
$resp_xml = simplexml_load_string($resp_xml);

$resp_username = $resp_xml->screen_name;
$verified = strcasecmp($username, $resp_username); // returns 0 if they are equal

if ($verified === 0)
return true;

$error = $this->getParameter('error');
return false;
}
}
?>

I hope you’ll find this useful. Let me know in the comments section if you see any issue while using it.

Written by Aditya

April 1st, 2009 at 8:47 pm

Posted in Programming

Tagged with , , , ,

Generate sequential strings for URL addresses using PHP

Comments

I’m working on an interesting project right now, and for this project, I wanted to generate URLs with sequential alphabetic sequence as opposed to using numeric IDs. Using alphabetic string allows me to use short URL addresses with many URL combinations. E.g. If I use numeric indexes, then I can only have 10 possibilities to represent http://abc.com/N, where N= 0 to 9. But instead, if I use alphabetic character, I have 26 possibilities where N= a, b, c to z. I don’t want to add usability issues by using both upper and lower cases of alphabets, so I’ll stick to lower case addresses only.

So I needed a function which will generate sequential alphabetic strings for URL address based on incremental numbers. So I coded up following function:

function getAlphaString($num)
{
  $alpha = '';
  while($num >= 1) {
    $num = $num - 1;
    $alpha = chr(($num % 26)+97) . $alpha;
    $num = $num / 26;
  }
  return $alpha;
}

Use this in a for{} loop, and it will give you sequential strings. Or call with individual numbers as shown below, and it will return you appropriate alphabetic string.

echo getAlphaString(5) . "\n";
echo getAlphaString(500) . "\n";
echo getAlphaString(500000) . "\n";
echo getAlphaString(50000000) . "\n";

And it produced following output:

e
sf
abkpt
dejtlx

Hope you’ll find this function useful in one of your applications.

Written by Aditya

January 23rd, 2009 at 6:30 am

Posted in Programming

Tagged with , ,

Splitting strings in PHP using explode Vs split functions

Comments

Splitting strings into an array is nothing new and is pretty easy using the explode function if your input string pattern is consistent. But if your input string pattern is a little less consistent, then using the split function makes it a lot easier than doing some post-processing on array elements produced by the explode function.

Here is an example:

I have an input field where I ask user to enter her friends’ email addresses to invite them. I instruct user to use commas to separate multiple email addresses. But user will not necessarily enter all email addresses with consistent pattern. The input string may not contain any spaces, or may contain optional spaces before or after actual email addresses. For example:

$recipient_email_list = "abc@example.com, def@example.com,ghi@example.com , jkl@example.com , mno@example.com";
$recipient_emails = explode(',', $recipient_email_list);

//Echo with '|' delimiter to see the spaces before and after email address:

foreach ($recipient_emails as $recipient_email)
{
  echo $recipient_email.'|';
}

The output is as below:

abc@example.com| def@example.com|ghi@example.com | jkl@example.com | mno@example.com|

In above example, few exploded strings have additional spaces. So you need to do post-processing on the exploded array as below:

$i=0;
foreach ($recipient_emails as $recipient_email)
{
  $found = preg_match('/ /', $recipient_email);
  if($found)
  {
    $recipient_emails[$i]= trim($recipient_email);
  }
  $i++;
}

foreach ($recipient_emails as $recipient_email)
{
  echo $recipient_email.'|';
}

Then the output is as below:

abc@example.com|def@example.com|ghi@example.com|jkl@example.com|mno@example.com|

But there is another easy way to avoid this extra lines of post-processing code. Use split function as below:

$recipient_emails = split(' *, *', $recipient_email_list);

foreach ($recipient_emails as $recipient_email)
{
  echo $recipient_email.'|';
}

Then the output is as below:

abc@example.com|def@example.com|ghi@example.com|jkl@example.com|mno@example.com|

In above example, split function actually splits an input string into an array by regular expression ‘ *, *’ i.e. split by zero or more spaces after or before the comma character.

I hope you will find this useful. If you have more inputs or questions, then please share in comments section.

Written by Aditya

January 16th, 2009 at 8:38 am

Posted in Programming

Tagged with , , ,