PHP Funktion für Wake-On-LAN
PHP function to send Wake On LAN packages
To wake up a defined machine via LAN you can enable this feature in its BIOS and send a magic package to start it:
Um einen Rechner im lokalen Netzwerk aufzuwecken kann WOL in dessen BIOS eingeschaltet werden und mithilfe dieser Funktion ein "magic package" zu ihm gesendet werden.
Function source code
Funktion
<?
/**
 * Sends a Wake-On-Lan magic package to the specified IP address.
 *
 * @package de.atwillys.php.fn.net
 * @param string $ip_address
 * @param string $mac_address
 * @param bool $throw_exceptions
 * @param int $port=7
 * @return bool
 * @throws Exception
 */
function wake_on_lan($ip_address, $mac_address, $throw=false, $port=7) {
  $msg = $hw_addr = '';
  if(strlen(preg_replace('|[0-9a-fA-F:]|i', '', $mac_address)) > 0) {
    if($throw) throw new Exception("Invalid MAC address");
    return false;
  }
  $mac_address = explode(':', $mac_address);
  for ($i=0; $i<6; $i++) $hw_addr .= chr(hexdec($mac_address[$i]));
  for ($i=0; $i<6; $i++) $msg .= chr(255);
  for ($i=0; $i<16; $i++) $msg .= $hw_addr;
  if (($sck = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) == false) {
    if($throw) throw new Exception(socket_strerror(socket_last_error($sck)));
    return false;
  }
  if (($o = socket_set_option($sck, SOL_SOCKET, SO_BROADCAST, true)) < 0) {
    @socket_close($sck);
    if($throw) throw new Exception("setsockopt() failed: " . strerror($o));
    return false;
  }
  if (!socket_sendto($sck, $msg, strlen($msg), 0, $ip_address, $port)) {
    @socket_close($sck);
    if($throw) throw new Exception("Failed to send magic message: " . strerror($o));
    return false;
  }
  @socket_close($sck);
  return true;
}
    

