Search code examples
phplinuxraspberry-piraspbianled

PHP script to lights up LED on Raspberry Zero Pi W


I do not know much about PHP, but I would like to ask how I should improve this script.

Adding a screenshot of my existing code, I will briefly describe.

Screenshot

The program causes the LED to turn on when the web button is pressed for the first time.

A condition must be met where it is given that the file size must be equal to 2 bytes. When the first condition is executed, a larger 4-byte number is written to the txt file.

By pressing the same button again, the second condition should be met, but there is an error that the file is overwritten, but the condition can not be fulfilled and I do not know why.

Do not you ask someone where there might be a problem or how would you possibly solve the problem you?

Here is part of the code:

    if(!file_get_contents("soubor.txt", 0)) {
            $soubor = fopen("soubor.txt","w+");
            $funkceled1 = 10;
            fwrite ($soubor, $funkceled1);
            fclose ($soubor);
        }

     if (isset($_GET['on1']) && file_get_contents("soubor.txt", 2)) {
                shell_exec("/usr/local/bin/gpio -g write 14 1");
                $soubor = fopen("soubor.txt","w+");
                $funkceled1 = 1000;
                fwrite ($soubor, $funkceled1);
                fclose ($soubor);
            }
     else if (isset($_GET['on1']) && file_get_contents("soubor.txt", 4)) {
                shell_exec("/usr/local/bin/gpio -g write 14 0");
                $soubor = fopen("soubor.txt","w+");
                $funkceled1 = 10;
                fwrite ($soubor, $funkceled1);
                fclose ($soubor);

Solution

  • Your code could be rewritten this way:

    $fileName = __DIR__.'/soubor.txt';
    // if the file does not exist or does not contain '10' nor '1000', create it with default value '10'
    if (!file_exists($fileName) || (file_get_contents($fileName) !== '10' && file_get_contents($fileName) !== '1000')) {
        file_put_contents($fileName, '10');
    }
    if (isset($_GET['on1']) && file_get_contents($fileName) === '10') {
        shell_exec("/usr/local/bin/gpio -g write 14 1");
        file_put_contents($fileName, '1000');
    } else if (isset($_GET['on1']) && file_get_contents($fileName) === '1000') {
        shell_exec("/usr/local/bin/gpio -g write 14 0");
        file_put_contents($fileName, '10');
    }