如何获取url的最后一部分并建立重定向



当我提交帖子时,我会被重定向到一个url:

https://example.com/example/create/?usp_success=2&post_id=127065

现在我需要获取127065并用它构建一个重定向:

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
// testing this but I don't how to get the last bit of the url
// $newURL = "$actual_link/?p="
header('Location: '.$newURL);

我想重定向到的最终url是:

https://example.com/example/create/?p=127065

更新

如果我这样做(如评论中所建议的(

$id = $_GET['post_id'];
$newURL = get_home_url()."/".$id;
header('Location: '.$newURL);

我得到:

警告:无法修改标头信息-标头已由..发送。。在线42

第42行是:

header('Location: '.$newURL);

您需要使用两个函数的组合:parse_url()parse_str()

$actualLink = 'https://example.com/example/create/?usp_success=2&post_id=127065';
$queryArgs = [];
parse_str(parse_url($actualLink, PHP_URL_QUERY), $queryArgs);
if ($postID = $queryArgs['post_id']) {
$newURL = sprintf("%s/?p=%s", $actual_link, $postID);
header('Location: ' . $newURL);
}

$queryArgs将包含数组:

Array
(
[usp_success] => 2
[post_id] => 127065
)

使用$queryArgs['post_id']可以得到post_id的值

要修复此错误:

警告:无法修改标头信息-标头已由..发送。。在线42

在调用header()函数之前,需要确保没有任何输出。

使用parse_url()parse_str()

$url="https://example.com/example/create/?usp_success=2&post_id=127065";
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['post_id'];
$id = $_GET['post_id'];
header('Location: https://example.com/example/create/?p='.$id);

相关内容

最新更新