What are some best practices for sending commands to a COM port using PHP?

Sending commands to a COM port using PHP requires opening the port, writing the command to the port, and then closing the port properly. It is important to handle errors and exceptions that may occur during the process to ensure reliable communication with the device connected to the COM port.

<?php
$port = 'COM1'; // Specify the COM port to communicate with
$command = 'AT+CGMI'; // Command to send to the device connected to the COM port

$serial = fopen($port, 'r+');
if (!$serial) {
    die('Failed to open COM port');
}

fwrite($serial, $command . "\r\n");

$response = fread($serial, 1024);
echo 'Response from device: ' . $response;

fclose($serial);
?>