首页 > 解决方案 > getUserMedia 抛出“使用未定义的常量......”

问题描述

我最近将我的网站迁移到 PHP 7.3。有一个输入框,我允许用户使用他们的媒体设备上传图片。自升级以来,我收到了一些“使用未定义常量...”的错误。

这是PHP代码:

function hasGetUserMedia() {
  return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}

if (hasGetUserMedia()) {
  echo '<input type="file" accept="image/* application/pdf" capture="camera" name="expimage" id="expimage" onchange="setExif(this.files)" />';
} 

尽管代码有效,但网页显示以下警告:

Warning
: Use of undefined constant navigator - assumed 'navigator' (this will throw an Error in a future version of PHP)

Warning
: Use of undefined constant mediaDevices - assumed 'mediaDevices' (this will throw an Error in a future version of PHP) 

Warning
: Use of undefined constant navigator - assumed 'navigator' (this will throw an Error in a future version of PHP)

Warning
: Use of undefined constant mediaDevices - assumed 'mediaDevices' (this will throw an Error in a future version of PHP)

Warning
: Use of undefined constant getUserMedia - assumed 'getUserMedia' (this will throw an Error in a future version of PHP)

我正在关注 WebRTC。定义常量的新格式是什么?

标签: phpgetusermedia

解决方案


这段代码从来没有工作过,它是一个很好的例子,说明了为什么以前作为通知错过的那些消息现在变成了警告,并且很快就会变成错误。

它似乎起作用的唯一原因是因为这条线

!!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);

被 PHP 解释为连接一堆字符串,给你

!!('navigatormediaDevices' && 'navigatormediaDevicesgetUserMedia')

PHP的类型杂耍规则是

!!(true && true)

这只是一种非常复杂的写作方式

true

在这种情况下,您的根本问题是您将 JS(它可以检测有关用户浏览器的信息,以及该行会在哪里做一些有用的事情)与 PHP(在涉及浏览器之前在服务器上运行)混淆了。

可能,您希望始终在 PHP 中回显表单控件,然后在 JS 中显示和隐藏它。但首先,您需要阅读一些有关两者如何结合在一起的教程,这样您就不会再陷入这样的混乱中。


推荐阅读