PHP中在print输出的iframe链接拼接$_GET['id']报错求解决方案
问题与解决方案
问题详情
我通过HTTP_REFERER判断隐藏iframe以防止直接访问,初始代码可正常运行:
<?php $referrer = $_SERVER['HTTP_REFERER']; if (preg_match('~mysite\.com$~', parse_url($referrer, PHP_URL_HOST))) { print ('<iframe src="https://www.dailymotion.com/embed/video/" scrolling="no" width="622" height="350" frameborder="no" allowfullscreen></iframe>'); } ?>
但尝试在iframe的src中加入<?php echo $_GET['id']; ?>后,修改后的代码抛出语法错误:
<?php $referrer = $_SERVER['HTTP_REFERER']; if (preg_match('~mysite\.com$~', parse_url($referrer, PHP_URL_HOST))) { print ('<iframe src="https://www.dailymotion.com/embed/video/<?php echo $_GET['id']; ?>" scrolling="no" width="622" height="350" frameborder="no" allowfullscreen></iframe>'); } ?>
错误提示:
Parse error: syntax error, unexpected 'id' (T_STRING) in /www/wwwroot/domain.com/index.php on line 4
错误原因
- 当前已处于PHP执行环境,不需要在
print字符串中再次嵌套<?php ?>标签,这属于无效写法。 - 字符串外层使用单引号包裹,内部
$_GET['id']的单引号与外层引号冲突,导致PHP无法正确解析字符串边界。
修复方案
方案1:字符串拼接或变量解析
方式A:双引号解析变量
用双引号包裹整个输出字符串,PHP会自动解析字符串中的变量(注意转义内部的双引号):
<?php $referrer = $_SERVER['HTTP_REFERER']; if (preg_match('~mysite\.com$~', parse_url($referrer, PHP_URL_HOST))) { print ("<iframe src=\"https://www.dailymotion.com/embed/video/{$_GET['id']}\" scrolling=\"no\" width=\"622\" height=\"350\" frameborder=\"no\" allowfullscreen></iframe>"); } ?>
方式B:单引号拼接
用.运算符连接字符串和变量,避免引号冲突:
<?php $referrer = $_SERVER['HTTP_REFERER']; if (preg_match('~mysite\.com$~', parse_url($referrer, PHP_URL_HOST))) { print ('<iframe src="https://www.dailymotion.com/embed/video/' . $_GET['id'] . '" scrolling="no" width="622" height="350" frameborder="no" allowfullscreen></iframe>'); } ?>
方案2:退出PHP环境输出HTML
在条件判断中暂时退出PHP,直接编写HTML代码,再嵌入PHP变量输出:
<?php $referrer = $_SERVER['HTTP_REFERER']; if (preg_match('~mysite\.com$~', parse_url($referrer, PHP_URL_HOST))) { ?> <iframe src="https://www.dailymotion.com/embed/video/<?php echo $_GET['id']; ?>" scrolling="no" width="622" height="350" frameborder="no" allowfullscreen></iframe> <?php } ?>
额外注意事项
- 安全过滤:务必对
$_GET['id']进行XSS防护,比如使用htmlspecialchars():$safeId = htmlspecialchars($_GET['id'], ENT_QUOTES); // 后续用$safeId替代$_GET['id'] - Referer局限性:
HTTP_REFERER可被篡改或为空,不能作为唯一的访问控制手段。
内容的提问来源于stack exchange,提问作者johnsow
相关产品推荐
相关产品推荐

