Problem with script counter.php

Hey @taz1 — when posting code blocks, please either use three backticks before and after, or, easier still, just highlight the code and use the </> button. :slight_smile:

I copied some scripts from the above posts and made the following:

Online Demo [with ource code]

The default is `$DEBUG``` which saves a random number to “counter.txt” and creates a temporary jpg file to display the results.

Selecting Use: header(“Content-Type: image/png”) does not use `$DEBUG```

I find it is a lot easier to modify working code:)

###Source:

<?php
declare(strict_types=1); // PHP 7 specific
error_reporting(-1); ini_set('display_errors', '1');

$title = 'Problem with PHP script counter';
$sp    = 'https://www.sitepoint.com/community/t/problem-with-script-counter-php/214562/49';
define('jj', '<br>');

//=====================================================
function fred($val)
{
    echo '<pre>'; 
        var_dump($val); 
    echo '</pre>';
}


// START
    session_start();
    $__DEBUG__ = ! isset( $_GET['debug'] ); // Change this to false when you want to stop the extra echos
    $counter_name = "counter.txt";

// Check if a text file exists. If not create one and initialize it to zero.
    if ( ! file_exists($counter_name) )
    {
        // echo $__DEBUG__ ? "Counter file did not exist" : NULL; // ** DEBUG
        $f = fopen($counter_name, "w");
        fwrite($f,"0");
        fclose($f);
    }

// DEBUG - create large number
    if($__DEBUG__)
    {
        $f = fopen($counter_name, "w");
        fwrite($f, sprintf('%d', mt_rand(1,12345)) );
        fclose($f);
    }    


// GET/SET COUNTER  
    // Read the current value of our counter file
    $f = fopen($counter_name,"r");
    $counterVal = fread($f, filesize($counter_name));
    fclose($f);
    // if ($__DEBUG__) echo "Counter value is " . $counterVal; // ** DEBUG
    

// INCREMENT COUNTER, MAYBE CREATE    
    // Has visitor been counted in this session?
    // If not, increase counter value by one
    if(!isset($_SESSION['hasVisited'])){
        $_SESSION['hasVisited']="yes";
        $counterVal++;
        $f = fopen($counter_name, "w");
        fwrite($f, $counterVal);
        fclose($f);
        // echo $__DEBUG__ ? "Incremented counter" : NULL; // ** DEBUG
    }

// GET COUNTER Values
    $counterVal = str_pad($counterVal, 5, "0", STR_PAD_LEFT);
    $chars = str_split($counterVal);
    // $im = imagecreatefrompng("canvas2.png"); // 300 x 75

// CREATE Associated images for each counter item
    $src1 = imagecreatefrompng("dy-otto-" .$chars[0] . ".png"); // 56 x 75
    $src2 = imagecreatefrompng("dy-otto-" .$chars[1] . ".png");
    $src3 = imagecreatefrompng("dy-otto-" .$chars[2] . ".png");
    $src4 = imagecreatefrompng("dy-otto-" .$chars[3] . ".png");
    $src5 = imagecreatefrompng("dy-otto-" .$chars[4] . ".png");

// BUILD Image
    $im = imagecreate(320,77); // 300 x 75
    imagecopymerge($im, $src1,   0, 0, 0, 0, 56, 75, 100);
    imagecopymerge($im, $src2,  60, 0, 0, 0, 56, 75, 100);
    imagecopymerge($im, $src3, 120, 0, 0, 0, 56, 75, 100);
    imagecopymerge($im, $src4, 180, 0, 0, 0, 56, 75, 100);
    imagecopymerge($im, $src5, 240, 0, 0, 0, 56, 75, 100);


# OUTPUT Results
    if( $__DEBUG__ )
    {

        $fff = 'tmp-001.jpg';
         $jpg = imagejpeg($im, $fff);
        imagedestroy($im);

        echo $page = '
        <!doctype html>
        <html>
        <head>
        <title> $title </title>
        <style>
            html,
            body   {margin:0; padding:0; background-color:black; color:snow;}
            #top   {margin:0; padding:0; height:2em; background-color:#000;}
            .bd1   {border:solid 1px #123;} 
            .bgs   {background-color:snow; color:#333;}
            .clb   {clear:both;}
            .fgc   {color:cyan;} 
            .flr   {float:right;}
            .mga   {margin:0 auto;} .mg2 {margin:2em auto;}
            .p42   {padding:0.42em}
            .ooo   {margin:0; padding:0;}
            .tac   {text-align:center}
            .w88   {width:88%;}
        </style>    
        </head>
        <body>
        
        <div id="top">
            <em class="flr"> <a href="' .$sp .'"><em class="fgc">SitePoint Forum</em></a> &nbsp; </em>
            <h1>' .$title .'</h1>
            <hr class="clb" />
        </div>';

        echo '<div class="clb mg2 bgs"><br>';
            if ($jpg) // file_exists($fileName)
            {
                echo '<dl class="clb w88 mg2 bgs">';
                    echo '<dt><b>File: </b> counter.txt content ==> ' . $counterVal .'<dt>';
                    echo '<dd>';
                        echo '<img src="' .$fff .'" alt="counter" />';
                    echo '</dd>';
                  echo '<dd>&nbsp;</dd>';
                  echo '<dd>&nbsp;</dd>';

                    echo '<dt"> <a href="index.php?debug"> Use: header("Content-Type: image/png") </a> </dt>';
                  echo '<dd>&nbsp;</dd>';
                echo '</dl>';    
            }    

            // Show Source
            echo '<div id="src" class="w88 mga p42 bd1">';
                echo '<b>Source: </b><br>';
                highlight_file(__FILE__);
            echo '</div>';    

        echo '</div></body></html>';
    }else{
        // Output and free from memory
        header('Content-Type: image/png');
        imagepng($im);
    }


1 Like

John. first time clicking that link I seem to get an error:

Fatal error: Uncaught TypeError: fwrite() expects parameter 2 to be string, integer given in /var/www/johns-jokes.com/public_html/downloads/sp-f/taz1-script-counter/index.php:56 Stack trace: #0 /var/www/johns-jokes.com/public_html/downloads/sp-f/taz1-script-counter/index.php(56): fwrite(Resource id #4, 1372) #1 {main} thrown in /var/www/johns-jokes.com/public_html/downloads/sp-f/taz1-script-counter/index.php on line 56

It’s fine if I go back and click again.

G :open_mouth:

Many thanks for debugging.

I will have a look tomorrow when I am back on the desktop.

Meanwhile I would appreciate anybody who can offer a solution to the inherited legacy script.

1 Like

@taz1 I’m sure it’s getting quite frustrating for you. The first thing to note is that the code should work “as is” without any modification. I have proved this on my own XAMPP localhost as well as on a live website, @droopsnoot has also confirmed this on his own setup.

In case it helps I have uploaded the complete package including the resized images and canvas image here.

I hope this helps.

1 Like

You have to take the debug section out, though, because while it’s outputting that debug text information, it will mess up the image data that gets sent afterwards. You also need to change the array elements so that they start $chars[1] in the imagecopymerge() lines - I know I said change them to start at zero, but that was wrong - as @Gandalf said back in post 47.

ok noted thank you and i am sorry still getting use to coding

Thanks i am trying to learn so i thought i would compare your code to the one i am using i could find no difference, so i thought lets use your package, but still did not work same result, no images appear even though the counter.txt is counting up. So its got to be my system setup or if anyone has any thoughts.
I am using Arch linux for the OS which is command line interface, then i have install apache. MySQL and PHP giving me a LAMP system, not usre why the images are not showing i am at a loss now could it be the code my my index file as shown below:-

<img alt="Hit counter" src="counter.php" />

It does rather suggest it is your setup. I’m running out of ideas. What version of PHP are you running? What browser?

i have tried it on firefox, chrome and IE.
Chrome is the one i main use on my win7 pc and PHP is
PHP Version => 7.0.3

If you run a

<?php
phpinfo();
?>

or look at your php.ini file

extension=php_bz2.dll
extension=php_curl.dll
extension=php_fileinfo.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_gmp.dll
extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
extension=php_ldap.dll
extension=php_mbstring.dll
extension=php_exif.dll      ; Must be after mbstring as it depends on it
extension=php_mysqli.dll
;extension=php_oci8_12c.dll  ; Use with Oracle Database 12c Instant Client
extension=php_openssl.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=php_shmop.dll

Can you tell if the image extension is enabled? (i.e. the “gd” line has no leading semi-colon)

1 Like

yes i open /etc/php/php.in did a search for gd and found a semi-colon as shown below:-

;extension=gd.so

I also did a search further down and found this:-
[gd]
; Tell the jpeg decode to ignore warnings and try to create
; a gd image. The warning will then be displayed as notices
; disabled by default
; http://php.net/gd.jpeg-ignore-warning
;gd.jpeg_ignore_warning = 0

i did remove the semi colon from the extension line but no change.

You may need to restart the server for the change to take.

restarted but still the same, what about the other gd bit in the php.ini file, also my php.ini file looked a bit different to your example or does that not matter, by the way thanks for helping

and phpinfo() says GD is loaded and running?

where does it say that please

For some reason I have always assumed that trying to install a wrong version would fail completely, but thinking about it now that could very likely not be the case.

For example, I have Windows 10, so I go to the PHP download page for Windows.

x86 or x64, Thread Safe of Not Thread Safe

Cheesh! How should I know?

After poking around my OS and a lot of guesswork I installed x64 Thread Safe

You wouldn’t be able to miss it.

Try running the script shown in the demo as a stand alone file because it will show all errors or produce a jpg image if successful.

Updated and hopefully cleared all errors:

Updated Demo With source code and all images.

1 Like

That’s weird I don’t have that gd section when I run http://ipadress/info.php