为何PHP POST表单无法传递数据?YouTube API认证上传问题
当前场景:处理YouTube API认证的页面能正常获取GET请求的code和scope,并生成表单提交到resumable_upload.php,但目标页面无法接收到任何POST变量。
相关代码
认证页面代码:
if (isset($_GET['code'])) { $code=$_GET['code']; $scope=$_GET['scope']; print "<form action='youtube-api-samples/resumable_upload.php' method='post' enctype='multipart/form-data'> <input type='hidden' name='code' value='$code' /> <input type='hidden' name='scope' value='$scope' /> video location: <input type='text' name='video'><br> <input type='submit'> </form>"; }
resumable_upload.php 部分代码:
$client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); $youtube = new Google_Service_YouTube($client); $tokenSessionKey = 'token-' . $client->prepareScopes(); if (isset($_POST['code'])) { $client->authenticate($_POST['code']); $_SESSION[$tokenSessionKey] = $client->getAccessToken(); header('Location: ' . $redirect); }
问题分析与解决方案
移除不必要的
enctype属性
表单中没有文件上传字段,却使用了enctype='multipart/form-data',这会导致PHP以文件上传的规则解析POST数据,普通文本字段的解析逻辑会受干扰。移除该属性后,表单将使用默认的application/x-www-form-urlencoded编码,确保POST变量能被正常读取。修改后的表单代码:
if (isset($_GET['code'])) { $code=$_GET['code']; $scope=$_GET['scope']; print "<form action='youtube-api-samples/resumable_upload.php' method='post'> <input type='hidden' name='code' value='$code' /> <input type='hidden' name='scope' value='$scope' /> video location: <input type='text' name='video'><br> <input type='submit'> </form>"; }验证表单路径正确性
确认action属性中的youtube-api-samples/resumable_upload.php是正确的相对路径。可以在认证页面中打印当前脚本目录:echo __DIR__;,对比目标文件的实际存储位置,避免因路径错误导致表单提交到无效页面,进而无法接收变量。启动会话保证后续逻辑正常
resumable_upload.php中使用$_SESSION存储令牌,但未调用session_start(),会导致会话无法正常工作。在文件最顶部添加session_start();(必须在任何输出之前执行):session_start(); $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); // 其余代码保持不变调试POST接收状态
在resumable_upload.php开头添加调试代码,快速确认是否接收到POST数据:var_dump($_POST); exit;如果输出为空,优先排查表单路径问题;如果有数据,则继续检查后续逻辑中的变量处理环节。
内容的提问来源于stack exchange,提问作者Yehuda Clinton

