Php – Identifying Specific Characters from Text Input

PHP

Original title:
to read and count the occurrence of only limited characters of A,G,C,T present in the input text file, for example only 100 out of 500 and draw a thin verticular rectangle barcode images using gd

It read and counts only first 10 characters and draw a barcode image, instead of specified 100 characters.

<?php
$file="co3.txt";
$handle=fopen($file, 'r');

$A=0;
$G=0;
$C=0;
$T=0;

$img = imagecreate(850,80);
$white = imagecolorallocate($img, 255,255,255);
$green=imagecolorallocate($img, 0, 128, 0);
$black=imagecolorallocate($img, 0, 0, 0);
$red=imagecolorallocate($img, 255, 0, 0);
$blue=imagecolorallocate($img, 0, 0, 255);

$x1=40;
$y1=40;
$x2=43;
$y2=80;

$contents = '';

#while(( ($contents=fread( $handle, 100)) !='')) {
while(( ($contents=fread($handle, 100)) )) {
for ($i=0; $i<=100; $i++)

{

  if($contents[$i] == 'A')
{

$A++;
imagefilledrectangle($img, $x1, $y1, $x2, $y2, $green);
$x1 = $x1+6;
$x2 = $x2+6;

}

else
if($contents[$i] == 'G')

{

$G++;
imagefilledrectangle($img, $x1, $y1, $x2, $y2, $black);
$x1 = $x1+6;
$x2 = $x2+6;

}

else
if($contents[$i] == 'C')

{

$C++;
imagefilledrectangle($img, $x1, $y1, $x2, $y2, $blue);
$x1 = $x1+6;
$x2 = $x2+6;

}

else
if($contents[$i] == 'T')

{

$T++;
imagefilledrectangle($img, $x1, $y1, $x2, $y2, $red);
$x1 = $x1+6;
$x2 = $x2+6;

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
}

}

}

?>

Best Answer

I'm guessing you only not so much the first 10 letters, but up to the point when a T is found. Then, the misplaced snippet producing the image ouptut this image. The loop may continue up to 100, producing possibly a few more images (with each new T), but I don't know PHP behavior in such cases, since some of the HTTP response is readily written...

Alternatively you may be seeing the last of these images. At any rate, by fixing the misplaced

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

things should start to look more as expected.