Posts Tagged ‘PHP’

Basic OCR

4. January 2010

No Comments »

This is a very basic optical character recognition script written in PHP. This is untested and serves merely a proof of concept. As noted in the comments, adjusting the sample size can improve results, since with a large sample size on a small image there can be many collisions. A database is needed to compare output results of this script with known values.

<?php

/* create a test image */
$im = @imagecreate(100, 20) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 1, 5, 5,  "Hello, World!", $text_color);

/***
 * Assumptions:
 *   A monochrome image where characters are black
 *   A single character is connected
 *   Characters are disjointed by white space
 */

$width = imagesx($im);
$height = imagesy($im);

/***
 * Notes:
 *   The smaller the sample size the more accurate it will be,
 *   however, it will take longer. Larger images can use a larger
 *   sample size wihtout compromizing much accuracy.
 */
$x_sample = 1;
$y_sample = 1;

$last = 0;
for($i = 0; $i < $width; $i++) {
    $col = array();

    for($j = 0; $j < $height; $j++) {
        $col[$j] = imagecolorat($im, $i, $j);
    }

    if(($current = array_sum($col)) > 0) {
        if($last == 0) {
            $l = 0;
        }

        for($k = 0; $k < $height; $k++) {
            if(($l % $x_sample) == 0) {
                if(($k % $y_sample) == 0) {
                    $sample .= $col[$k];
                }
            }
        }

        $l++;
        $last = $current;
    } else {
        $last = 0;
    }

    if(!empty($sample) && $last == 0) {
        echo $sample . "\n";
        $sample = "";
    }
}
?>

Output (each line represents a character)

00000011111100000000000000001000000000000000000010000000000000000011111100000000
00000000011000000000000000001011000000000000000011010000000000000000010100000000
000000100001000000000000001111110000000000000000000100000000
000000100001000000000000001111110000000000000000000100000000
00000000011000000000000000001001000000000000000010010000000000000000011000000000
000000000001000000000000000001100000000000000000010000000000
00000011111100000000000000000110000000000000000001100000000000000011111100000000
00000000011000000000000000001001000000000000000010010000000000000000011000000000
00000000111100000000000000000100000000000000000010000000000000000000010000000000
000000100001000000000000001111110000000000000000000100000000
00000000011000000000000000001001000000000000000010100000000000000011111100000000
00000001110100000000

Using PHP and GD to add border to text

4. January 2010

No Comments »

<?php
/**
 * Writes the given text with a border into the image using TrueType fonts.
 * @author John Ciacia
 * @param image An image resource
 * @param size The font size
 * @param angle The angle in degrees to rotate the text
 * @param x Upper left corner of the text
 * @param y Lower left corner of the text
 * @param textcolor This is the color of the main text
 * @param strokecolor This is the color of the text border
 * @param fontfile The path to the TrueType font you wish to use
 * @param text The text string in UTF-8 encoding
 * @param px Number of pixels the text border will be
 * @see http://us.php.net/manual/en/function.imagettftext.php
 */
function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {

    for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
        for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
            $bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);

   return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}
<?php
$img = imagecreatefrompng("/home/john/Desktop/test.png");
$font_color = imagecolorallocate($img, 0, 0, 0);
$stroke_color = imagecolorallocate($img, 255, 0, 0);
imagettfstroketext($img, 10, 0, 10, 50, $font_color, $stroke_color, "abstract.ttf", "Hello, World!", 2);
?>

Basic CAPTCHA

4. January 2010

No Comments »

Very basic code demonstrating the use of the GD library by creating a simple CAPTCHA.

<?php
function randomString($length){
    $pattern = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    if(empty($length)){
        $length = "10";
    }

    for($i=0; $i<$length; $i++){
        $string .= $pattern{rand(0,61)};
    }

    return $string;
}

function captcha() {
    header("Content-type: image/png");
    $im = @imagecreate(100, 50) or die("Cannot Initialize new GD image stream");
    $background_color = imagecolorallocate($im, 0, 0, 0);
    $text_color = imagecolorallocate($im, 255, 0, 0);
    $string = randomString();
    imagestring($im, 10, 5, 5,  $string, $text_color);
    imagepng($im);
    imagedestroy($im);
}

captcha();
?>

Illogical PHP Logic

17. July 2009

No Comments »

In algebra, after we learn the basic distributive, commutative, and associative properties, the transitive property of equality is usually next in the curriculum. For those of you who do not recall the terminology, the transitive property of equality says if $a == $b and $b == $n then $a == $n. Using this age old logic, you can prove FALSE == TRUE and 0 == 1 in PHP. Here is how:


$a = 0;
$b = "Hooray for PHP logic and dynamic type casting?";
var_dump(((FALSE == $a) == ($a == $b)) == ($b == TRUE));
var_dump((((0 == $a) == ($a == $b)) == ($b == TRUE) == (TRUE == 1));

Returns
bool(true)
bool(true)

Q.E.D

Note: I am comparing values not types. That being said, forgive me when I flame you for using PHP inappropriately. A string is NOT an integer and an integer is NOT a boolean. They should not be used as such.

Setting up a LAMP server with Ubuntu

5. July 2009

No Comments »

Ubuntu, known for its ease of use, makes no exception for setting up an apache, mysql, and php stack. Since the release of Feisty Fawn, Ubuntu has come packed with tasksel – a user interface for installing tasks.

1. At your command prompt, run tasksel as root.

john@earth:~$ sudo tasksel

2. Select LAMP server
1

3. Continue the installation by following the prompts.

It works!
4

One tool I have difficulty living without is phpMyAdmin. From the command prompt type

sudo apt-get install phpmyadmin

Continue the installation by following the prompts. If you are using a version of Ubuntu older than 9.04 (Jaunty) you will need to add the following line to /etc/apache2/apache2.conf Continue the installation by following the prompts. Version 9.04 does this automatically. You will be able to access phpMyAdmin by browsing directly to http:///phpmyadmin

Tic Tac Toe

22. May 2009

1 Comment »

A graphical Tic Tac Toe board using PHP-Gtk

#!/usr/local/bin/php -q
<?php
class TicTacToe extends GtkWindow{

    private $_buttons;
    private $_dialog;
    private $_count;
    private $_menu;
    private $_lbl;

    public function __construct()
    {
        parent::__construct();

        $this->set_title('Tic-Tac-Toe');
        $this->set_size_request(250, 250);
        $this->set_position(Gtk::WIN_POS_CENTER);
        $this->connect_simple('destroy', array('gtk', 'main_quit'));

        #Create the Buttons and add them to the table
        for($i = 0; $i < 9; $i++) {
            $this->_buttons[$i] = new GtkButton('');
            $this->_buttons[$i]->connect_simple('clicked', array($this, 'clicked'), $i);
        }

        #Create a GtkTable
        $tbl = new GtkTable(3, 3);

        #Add nine buttons to the table
        for($i = 0; $i < 9; $i++) {
            $tbl->attach($this->_buttons[$i], ($i%3), ($i%3)+1, floor($i/3), floor($i/3)+1);
        }

        $this->buildMenu();

        #GtkStatusBar
        $status = new GtkStatusbar();
        $context = array('Not Connected', 'Connected');
        $status->push($status->get_context_id($context[0]), $context[0]);

        #GtkVBox
        $vbox = new GtkVBox();
        #Add the GtkVBox to the main window
        $this->add($vbox);
        #Add the GtkMenu to the GtkVBox
        $vbox->pack_start($this->_menu, false);
        #Add the GtkTable to the GtkVBox
        $vbox->pack_start($tbl, true, true);
        #Add the GtkStatusBar to the GtkVBox
        $vbox->pack_start($status, false);

        $this->show_all();

        $this->server();

    }

    private function server()
    {
        #Not implemented
    }

    private function buildMenu()
    {
        #GtkMenu
        $this->_menu = new GtkMenuBar();
        $this->_menu->append($file_item = new GtkMenuItem('_File'));
        $this->_menu->append($help_item = new GtkMenuItem('_Help'));

        $file_item->set_submenu($file_menu = new  GtkMenu());
        $file_menu->append($file_new_item = new GtkMenuItem('_New'));
        $file_menu->append($file_connect_item = new GtkMenuItem('_Connect'));
        $file_menu->append($file_quit_item = new GtkMenuItem('_Quit'));

         $help_item->set_submenu($help_menu = new  GtkMenu());
        $help_menu->append($help_about_item = new GtkMenuItem('_About'));

        $file_new_item->connect_simple('activate', array($this,'restart'));
        $help_about_item->connect_simple('activate', array($this,'about'));
        $file_quit_item->connect_simple('activate', array('Gtk','main_quit'));
    }

    public function about()
    {
        $about = new GtkAboutDialog();
        $about->set_authors(array("John Ciacia"));
        $about->set_comments("Tic-Tac-Toe created using the PHP-Gtk extension.");
        $about->set_copyright("Copyright (C) 2008 John Ciacia");
        $about->set_license("This software is released under the GNU GPL");
        $about->set_version("1.0");
        $about->set_website("http://www.codecall.net");
        $about->set_website_label("http://www.codecall.net");
        $about->show_all();
    }

    public function clicked($i)
    {
        !isset($this->_count) ? $this->_count = 0 : $this->_count++;
        ($this->_count % 2 == 0) ? $this->_lbl = 'X' : $this->_lbl = 'O';

        $this->_buttons[$i]->set_label($this->_lbl);
        $this->_buttons[$i]->set_sensitive(false);

        $this->_check();
    }

    private function _check()
    {
        $win = false;

        $combinations = array(
            0 => array(0, 1, 2),
            1 => array(3, 4, 5),
            2 => array(6, 7, 8),

            3 => array(0, 3, 6),
            4 => array(1, 4, 7),
            5 => array(2, 5, 8),

            6 => array(0, 4, 8),
            7 => array(2, 4, 6));

        for($i = 0; $i < 8; $i++)
        {
            if( ($this->_buttons[$combinations[$i][0]]->get_label() ==
                    $this->_buttons[$combinations[$i][1]]->get_label()) && 

                ($this->_buttons[$combinations[$i][1]]->get_label() ==
                    $this->_buttons[$combinations[$i][2]]->get_label()) && 

                ($this->_buttons[$combinations[$i][0]]->get_label() != "")){

                $win = true;
            }
        }

        if($win) {
            $this->end_dialog(true);
        }
        else if(!$win && $this->_count == 8) {
            $this->end_dialog();
        }
        else {
            ;
        }
    }

    private function end_dialog($win = false){

        $this->_dialog = new GtkDialog(null, $this);
        $this->_dialog->set_title("Play Again?");
        $this->_dialog->set_default_size('100','100');
        $this->_dialog->set_modal(true);
        $this->_dialog->set_transient_for($this);
        $this->_dialog->set_resizable(false);
        $this->_dialog->connect_simple('destroy', array($this, 'destroy'));
        if($win) {
            $label = new GtkLabel($this->_lbl . " has won the game. Play again?");
        } else {
            $label = new GtkLabel("It's a tie! Play again?");
        }
        $button_yes = new GtkButton('_Yes');
        $button_yes->connect_simple('clicked', array($this, 'restart'));
        $button_no = new GtkButton('_No');
        $button_no->connect('clicked', array($this, 'destroy'));

        $vbox1 = $this->_dialog->vbox;
        $vbox2 = $this->_dialog->action_area;
        $vbox1->pack_start($label);
        $vbox2->pack_start($button_yes);
        $vbox2->pack_start($button_no);
        $this->_dialog->show_all();
    }

    public function restart()
    {
        if(isset($this->_dialog)) { $this->_dialog->hide_all(); }
        unset($this->_count);

        foreach($this->_buttons as $button):
            $button->set_label('');
            $button->set_sensitive(true);
        endforeach;
    }

    public function destroy()
    {
        echo "Good Bye!\n";
        Gtk::main_quit();
    }

}

new TicTacToe();
Gtk::main();

?>

tictactoe

Email Obfuscator

22. May 2009

No Comments »

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>GEO</title>
<script type="text/javascript">
//<![CDATA[
window.onload = function () {
    geo();
}

function geo() {
    if (!document.getElementsByTagName) // Check for browser support
            return false;
    if (rot13)
        var map = rot13init(); 

    var links = document.getElementsByTagName('a');

    function geo_decode(anchor) {
        var href = anchor.getAttribute('href');
        var address = href.replace(/.*contact\/([a-z0-9._%-]+)\+([a-z0-9._%-]+)\+([a-z.]+)/i, '$1' + '@' + '$2' + '.' + '$3');
        var linktext = anchor.innerHTML;
            if (href != address) {
                anchor.setAttribute('href','mailto:' + (rot13 ? str_rot13(address,map) : address)); // Add mailto link    
                anchor.innerHTML = linktext; // IE Fix
        }
    }

    for (var l = 0 ; l < links.length ; l++)
    {
        links[l].onclick = function()
        {
            geo_decode(this);
        }

        links[l].onmouseover = function()
        {
                geo_decode(this);

        }
    }
}

var rot13 = 1;

function rot13init() {
    var map = new Array();
    var s = "abcdefghijklmnopqrstuvwxyz";
    for (var i = 0 ; i < s.length ; i++)
        map[s.charAt(i)] = s.charAt((i+13)%26);
    for (var i = 0 ; i < s.length ; i++)
        map[s.charAt(i).toUpperCase()] = s.charAt((i+13)%26).toUpperCase();
    return map;
}

function str_rot13(a,map) {
    var s = "";
    for (var i = 0 ; i < a.length ; i++) {
        var b = a.charAt(i);
        s += (b>='A' && b<='Z' || b>='a' && b<='z' ? map[b] : b);
    }
    return s;
}
//]]>
</script>
</head>

<body>
<?php

function cloakmail($content) {

    preg_match_all("^[-a-z-A-Z-0-9\._]+@[-a-z-A-Z-0-9\._]+\.[a-z]{2,4}^", $content, $emails);

    for($i = 0; $i < count($emails[0]); $i++) {
        $username = explode("@", $emails[0][$i]);
        $domain = explode(".", str_rot13($username[1]));

        if(count($domain) > 2) {
            $replace = '<a href="contact/' . str_rot13($username[0]) . '+'
            . $domain[0] . '+'
            . $domain[1] . '.'
            . $domain[2] .'" rel="nofollow">' . asc2html($emails[0][$i]) . '</a>';
        } else {
            $replace = '<a href="contact/' . str_rot13($username[0]) . '+'
            . $domain[0] . '+'
            . $domain[1] .'" rel="nofollow">' . asc2html($emails[0][$i]) . '</a>';
        }

        $content = str_replace($emails[0][$i], $replace, $content);
    }

    return $content;
}

function asc2html($email) {
    $html = "";
    $len = strlen($email);
    for($i = 0; $i < $len; $i++) {
        $html .= "&#" . ord($email[$i]);
    }
    return $html;
}

$content = "Sidewinder@anything.extreme-hq.com<br />\n
Sidewinder@extreme-hq.com";

echo cloakmail($content);
?>
</body>
</html>

Binary to Decimal Conversion

21. May 2009

No Comments »

Converts a binary number to its decimal equivalent. However unlike the bindec function, this will preserve the binary/radix point.

Code

<?php

/**
 * Convert a binary number with our without
 * a radix point to its decimal equivalent.
 *
 * @param $binary The binary number to convert.
 * @param $output Show the calculations.
 * @return The decimal conversion
 */
function bin2dec($binary, $output = false) {
    $N = 0;
    $o = "";
    list ( $rhs, $lhs ) = explode ( ".", $binary );
    $rhs = strrev ( $rhs );
    for($i = 0; $i < strlen ( $rhs ); $i ++) {
        $d = $rhs [$i] * pow ( 2, $i );
        $N = $d + $N;
        $o = ($d == 0) ? $o : $o . $d . " + ";
    }

    for($i = 0; $i < strlen ( $lhs ); $i ++) {
        $d = $lhs [$i] * pow ( 2, - ($i + 1) );
        $N = $d + $N;
        $o = ($d == 0) ? $o : $o . $d . " + ";
    }

    return ($output) ? substr ( $o, 0, - 3 ) . " = " . $N : $N;
}

?>

Usage

echo bin2dec ( "1011101.1000101", true );

Output

1 + 4 + 8 + 16 + 64 + 0.5 + 0.03125 + 0.0078125 = 93.5390625

Usage

echo bin2dec ( "1011101.1000101");

Output

93.5390625

Note that the MySQL client library is not bundled anymore!

9. May 2009

No Comments »

Unable to get PHP configured to my specifications using the Ubuntu repositories, I decided to install it from source. However, I kept getting the error:

Note that the MySQL client library is not bundled anymore!

Not wanting to install MySQL from source, I found a package in the Ubuntu repositories that installed the necessary library files.

sudo apt-get install libmysqlclient15-dev

After I installed that package, PHP was able to install successfully.

imagettftext only displays yellow text

9. May 2009

No Comments »

Lately I have been doing some work with the PHP GD library. I wanted to put text on an image so I naturally used imagettftext(). I started by copying the example code provided by the manual and intended on modifying the code to fit my needs. When I executed the code my my browser, the text was yellow. I took a look at the code, and the results did not match. The text should have been black. I tried adjusting the imagecolorallocate parameters to reflect a different color. However, this time with I executed the code, no text showed up. It turns out I needed configure PHP –with-freetype-dir. After a recompile with the new configuration it worked fine.

./configure \
–disable-magic-quotes \
–enable-bcmath \
–enable-sockets \
–with-mysq=/usr/local \
–with-apxs2=/usr/local/apache2/bin/apxs \
–with-curl \
–with-gd \
–with-freetype-dir=/usr
–with-png \
–with-jpeg \
–with-ttf

text1