Archive

Archive for the ‘PHP’ Category

Prevent a delayed website because of a crashed server

November 1, 2013 No comments

When we are generating content for our website dinamically, sometimes information comes from outside, so the information we serve not only depends on our server, we have to retrieve it from another place, and this may not be controlled by us. Sometimes, server crashes, and you can get a timeout (over 20 or 30 seconds later), so our website will be terribly slow.

What we are going to do is to reduce this timeout. Imagine to situations:

  • We get the information, and transform it in anyway, we can apply caches to it, so the next time we need this information, can serve it as we downloaded it before. But maybe when we try to download again the information, the site doesn’t work. It’s worth checking.
  • We include external images or resources and they may not be ready. So we check the main server before using it. If the server is ok, we can let the user download the resource from outside; if it’s not we can put a placeholder resource, a backup or whatever.

We can check the availability with curl:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$url="URL de nuestro servidor";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOBODY, true); // Excluimos el cuerpo de la web
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Devolvemos el contenido a la variable
$data = curl_exec($ch);
if ($data)
    echo "It works";
else
    echo "Does not work: ".curl_error($ch);
curl_close($ch);
?>

So, if the foreign server lasts more than 1 second (CURLOPT_TIMEOUT param), we can say it doesn’t work (it may be overloaded, not working or it can be a connection problem, we don’t mind, we only know it doesn’t work properly.) But when working internally (for example to download contents we will format and cache later, inside a cron job… we can give a higher value here.
Foto: Orin Zebest (Flickr) CC-by

Know PHP methods visibility (public, protected, private)

October 24, 2013 No comments

When coding in Object Oriented PHP, sometimes we would like to know the visibility of certain methods. For example, we are using an instance of an unknown class in compile-time (or coding time) with its name in a variable just like:

1
2
3
4
5
<?php
  $class = (isset($_GET['class']))?$_GET['class']:false;
  if ($class)
    $myObject = new $class;
?>

So, if we are going to call any method, we should know its visibility first. Another example, could be when we are checking the visibility in a base class. A subclass (“Heir”) of “Base” was instanced, and some methods of Base are going to call methods of Heir, so Base must know if they can be called.

Let’s check the visibility with this code:

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
<?php
function methodType($class, $method)
{
  try
    {
      $method = new ReflectionMethod($class, $method);
     
      if ($method->isPrivate())
    return 'private';
      elseif ($method->isProtected())
    return 'protected';
      elseif ($method->isPublic())
    return 'public';
    }
  catch (Exception $e)
    {
      return 'error';
    }
}

class MyClass
{
  function __construct()
  {
  }

  private function myPrivate()
  {
    echo "shhh... this is private\n";
  }

  public function myPublic()
  {
    echo "Hello everybody!!\n";
  }

  protected function myProtected()
  {
    echo "Protected method!!\n";
  }

}

$myclass = new MyClass();

echo 'myPrivate: '.methodType($myclass, 'myPrivate')."\n";
echo 'myPublic: '.methodType($myclass, 'myPublic')."\n";
echo 'myProtected: '.methodType($myclass, 'myProtected')."\n";
echo 'notExists: '.methodType($myclass, 'notExists')."\n";
?>

Here we have methodType() function, giving the class and method, it will return a string “public”, “private”, “protected” or “error”. This function uses ReflectionMethod class from PHP, it can do lots of things more.4

Well, back to the second example, I’d like to record calls of some methods, so I will create a superclass MyClassBase with a invoker method used to call other methods inside the other class only if they are public:

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
function methodType($class, $method)
{
  try
    {
      $method = new ReflectionMethod($class, $method);
     
      if ($method->isPrivate())
    return 'private';
      elseif ($method->isProtected())
    return 'protected';
      elseif ($method->isPublic())
    return 'public';
    }
  catch (Exception $e)
    {
      return 'error';
    }
}

class MyClassBase
{
  function __construct()
  {
    echo "Class created\n";
  }
 
  public function invoker($method, $arguments=array())
  {
  try
    {
      $method = new ReflectionMethod($this, $method);
     
      if ($method->isPublic())
    {
      echo "I'm invoking method ".$method->name."...\n";
      return $method->invokeArgs($this, $arguments);
    }
      else
    echo "Method ".$method->name." is not public!!\n";
    }
  catch (Exception $e)
    {
      echo "Error invoking ".$method."\n";
    }
  }
}

class MyClass extends MyClassBase
{
  function __construct()
  {
    echo "Creating MyClass...\n";
  }

  private function myPrivate()
  {
    echo "shhh... this is private\n";
  }

  public function myPublic()
  {
    echo "Hello everybody!!\n";
  }

  public function myPublicCalls()
  {
    echo "I'm a public method that calls private methods...\n";
    $this->myPrivate();
  }

  public function myPublicArguments($arg1, $arg2)
  {
    echo "I'm a public method with two arguments: ".$arg1." and ".$arg2."\n";
  }

  protected function myProtected()
  {
    echo "Protected method!!\n";
  }

}

$myclass = new MyClass();

$myclass->invoker('notExists');
$myclass->invoker('myPrivate');
$myclass->invoker('myPublic');
$myclass->invoker('myPublicCalls');
$myclass->invoker('myPublicArguments', array('argument1', 'argument2'));
?>

The answer will be:

Creating MyClass…
Error invoking notExists
Method myPrivate is not public!!
I’m invoking method myPublic…
Hello everybody!!
I’m invoking method myPublicCalls…
I’m a public method that calls private methods…
shhh… this is private
I’m invoking method myPublicArguments…
I’m a public method with two arguments: argument1 and argument2

In fact, when a private or inexistent method is called, invoker() will give an error, and we can capture it easily, avoiding a PHP error to be triggered, or we can throw an exception. And if the method is public, we can run code before and after calling it, so we can log this call.

Another interesting thing is invoking the method with arguments, these arguments must be specified inside an array, so instead of calling:

1
2
3
<?php
myPublicArguments('argument1', 'argument2');
?>

When using the invoker we must do:

1
2
3
<?php
$myclass->invoker('myPublicArguments', array('argument1', 'argument2'));
?>

Alternate letters of several strings to create a new one

October 16, 2013 No comments

When hashing a password, it is recommended not only hashing the password. Concatenate the password string with other strings (or salt value), so those passwords won’t be broken using hashes databases. This is another technique to include salt to our passwords, or even a method to generate passwords.

This function will alternate letters of some given strings and put them in a new one. So if we take these two words: “Binary” and “Poetry”, it will generate “BPioneatrryy” (I’m sure you haven’t read that :) )

Lets see the function:

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
  function letterAlternate($strs)
  {
    $n_strs = count ($strs);

    if ($n_strs==1)        /* If there is only one string, return it */
      return $strs[0];

    /* Count the characters of every string and store them */
    $chars_str=array();
    for ($i=0; $i<$n_strs; $i++)
      $chars_str[$i]=strlen($strs[$i]);

    $max_str = max ($chars_str); /* The larges string determines when we stop */
    $res='';

    for ($j=0; $j<$max_str; $j++)
      {

    for ($i=0; $i<$n_strs; $i++)
      {
        /* If the string isn't finished, we'll add the character to the string */
        if ($j<$chars_str[$i])
          $res.=$strs[$i][$j];
      }
      }

    return $res;
  }

echo letterAlternate (array("Binary", "Poetry", "Gaspar", "Fernandez", "Programming", "Blog", "Free", "Software"));

We will get: BPGFPBFSioaerlronesrooefatpnggetrraarwyyrnaadmremezing

Swapping variable values in PHP [Short post]

October 11, 2013 No comments

Yesterday we talked about swapping variables in C and C++. This time, we will do it in PHP.

We can translate the C program to PHP, creating a temporary value and running the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$a = 11;
$b = 99;

echo "Original A value: ".$a."\n";
echo "Original B value: ".$b."\n";

$tmp = $a;
$a = $b;
$b = $tmp;

echo "New A value: ".$a."\n";
echo "New B value: ".$b."\n";
?>

It will simply work, but we can take advantages of built-in PHP functions, to make it shorter (and we won’t use a temporary variable):

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$a = 11;
$b = 99;

echo "Original A value: ".$a."\n";
echo "Original B value: ".$b."\n";

list($a, $b) = array($b, $a);

echo "New A value: ".$a."\n";
echo "New B value: ".$b."\n";
?>

So first we create an array with values $b and $a and then we separate this values in variables $a and $b. The result is the same.

File sizes for humans (PHP, C, C++)

When we get a file size, we usually get it in bytes. It’s ok to have this value, but, when giving the user this information, we must convert it to another unit to make it a little more accessible. When talking about megabytes or gigabytes, everyone will make a mess. So here are some snippets to help us do that:

First in PHP:

1
2
3
4
5
6
7
8
9
function human_size ($tam) {
        $i = 0;
        $unids=array("bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb");
        while ($tam>1024) {
                $tam = $tam /1024;
                $i++;
        }
        return number_format($tam,2,",",".").$unids[$i];
}

So we can call:

1
echo human_size(12939128332323);

It will return

11.77Tb

So we can have (as users) a better value.

In C++ we can do it that way:

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
#include <iostream>
#include <sstream>

using namespace std;

string human_size(long double size)
{
  static string units[10]={"bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb"};
  ostringstream out;
  int i= 0;

  while (size>1024) {
    size = size /1024;
    i++;
  }

  out.precision(3);
  out<<size<<units[i];
  return out.str();
}

int main()
{
  cout <<human_size(1232312333)<<endl;
}

This time we use ostringstream to build the output string, but the basis is the same as php, it’s only to have a copy-paste snippet :)

And finally, C language, this time, we don’t have a string type, so we have to use char arrays to make it possible, this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

char *human_size(char *store, long double size)
{
  static char units[10][6]={"bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb"};  
  int i= 0;

  while (size>1024) {
    size = size /1024;
    i++;
  }

  sprintf(store,"%.2Lf%s",size, units[i]);

  return store;
}

int main()
{
  char cadena[30];
  printf("Size: %s\n", human_size(cadena, 1293323872));
}

I know I’m using a lot of units: “bytes”, “Kilobytes”, “Megabytes”, “GigaBytes”, “Terabytes”, “Petabytes”, “Exabytes”, “Zetabytes”, “Yottabytes” and “Brontobytes”, and numeric variables won’t store such huge numbers. :)

This post is available in Spanish here: http://totaki.com/poesiabinaria/2010/03/tamano-de-archivo-para-seres-humanos-phpc-y-c/
Photo: Kate Haskell (Flickr) CC-by

Top