What are the best practices for toggling lamp states using PHP and Raspberry Pi?

When toggling lamp states using PHP and Raspberry Pi, it is important to ensure that the GPIO pins are properly configured and that the code is structured to handle both turning the lamp on and off. Using conditional statements and GPIO libraries can help achieve this functionality.

<?php

// Include the PHP GPIO library
require_once('vendor/autoload.php');

// Set the GPIO pin number for controlling the lamp
$pin = 17;

// Initialize the GPIO
$gpio = new PhpGpio\Gpio();
$gpio->setup($pin, "out");

// Check the current state of the lamp
$current_state = $gpio->read($pin);

// Toggle the lamp state
if ($current_state == 0) {
    $gpio->output($pin, 1);
    echo "Lamp turned on";
} else {
    $gpio->output($pin, 0);
    echo "Lamp turned off";
}

// Clean up the GPIO
$gpio->unexport($pin);

?>