【发布时间】:2021-06-20 06:57:50
【问题描述】:
我是一名 IT 帮助台,几乎没有 PHP 经验。现在我在公司有个项目,让一个同事用VPN连接到公司的内网,然后远程唤醒他在公司的电脑。所以我的想法是在公司里建立一个基于PHP的网站,让一个同事输入他电脑的MAC地址,然后他提交后就可以远程唤醒他的电脑。我在网上找到了如下代码,但是应用的时候会出现错误。 错误信息是自爆
- 警告:C:\xampp\htdocs\wol\wol.php 第 41 行中未定义的数组键 1
- 警告:C:\xampp\htdocs\wol\wol.php 第 41 行中未定义的数组键 2
- 警告:C:\xampp\htdocs\wol\wol.php 第 41 行中未定义的数组键 3
- 警告:C:\xampp\htdocs\wol\wol.php 第 41 行中未定义的数组键 4
- 警告:C:\xampp\htdocs\wol\wol.php 第 41 行中未定义的数组键 5
- 魔包发送失败!
你能帮帮我吗?提前致谢。
wol.php
<?php
/**
* Implement Wake-on-LAN function
*/
class WOL
{
private $hostname; // The hostname of the wake-up device
private $mac; // The mac address of the wake-up device
private $port; // The port of the wake-up device
private $ip; // The IP address of the wake-up device (not necessary, the program will automatically obtain the corresponding ip according to $hostname)
private $msg = array(
0 => "The target machine is already awake.",
1 => "socket_create execution failed",
2 => "socket_set_option execution failed",
3 => "magic packet Sent successfully!",
4 => "magic packet Failed to send!"
);
function __construct($hostname,$mac,$port,$ip = false)
{
$this->hostname = $hostname;
$this->mac = $mac;
$this->port = $port;
if (!$ip)
{
$this->ip = $this->get_ip_from_hostname();
}
}
public function wake_on_wan()
{
if ($this->is_awake())
{
return $this->msg[0]; // If the device is already awake, no other operations will be performed
}
else
{
$addr_byte = explode(':', $this->mac);
$hw_addr = '';
for ($a=0; $a<6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a=1; $a<=16; $a++) $msg .= $hw_addr;
// Send data packets via UDP
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false)
{
return $this->msg[1]; // socket_create Execution failed
}
$set_opt = @socket_set_option($s, 1, 6, TRUE);
if ($set_opt < 0)
{
return $this->msg[2]; // socket_set_option Execution failed
}
$sendto = @socket_sendto($s, $msg, strlen($msg), 0, $this->ip, $this->port);
if ($sendto)
{
socket_close($s);
return $this->msg[3]; // magic packet Sent successfully!
}
return $this->msg[4]; // magic packet Failed to send!
}
}
private function is_awake()
{
$awake = @fsockopen($this->ip, 80, $errno, $errstr, 2);
if ($awake)
{
fclose($awake);
}
return $awake;
}
private function get_ip_from_hostname()
{
return gethostbyname($this->hostname);
}
}
?>
index.php
<?php
include("wol.php");
$WOL = new WOL("255.255.255.255","38-D5-47-AA-69-A2","9");
$status = $WOL->wake_on_wan();
echo $status;
?>
【问题讨论】:
-
"第 41 行 C:\xampp\htdocs\wol\wol.php 中未定义的数组键 1" 那么哪一个是第 41 行?
-
$addr_byte = explode(':', $this->mac);- 你的 MAC 地址应该是"38:D5:47:AA:69:A2"而不是"38-D5-47-AA-69-A2" -
这能回答你的问题吗? Wake on lan script that works - 代码稍微简单一些,并且处理了问题中的主要错误(Mac 格式)
-
@msbit,是的,你是对的!所有错误消息都消失了。但仍然无法发出魔术包。
-
如果您在代码中删除
@的使用,您将得到所有实际错误(@抑制)。我不确定 WOL 的实现是否完全正确;从en.wikipedia.org/wiki/Wake-on-LAN 它应该被发送到广播,而不是特定的 IP 地址。
标签: php wake-on-lan