PHP Parse URL From Current URL

2020-05-01 08:04发布

I am trying to parse url and extract value from it .My url value is www.mysite.com/register/?referredby=admin. I want to get value admin from this url. For this, I have written following code. Its giving me value referredby=admin, but I want only admin as value. How Can I achieve this? Below is my code:

<?php 
    $url = $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    setcookie('ref_by', parse_url($url, PHP_URL_QUERY));
    echo $_COOKIE['ref_by'];

 ?>

标签: php
6条回答
爷的心禁止访问
2楼-- · 2020-05-01 08:31
$referred = "referredby=admin";
$pieces = explode("=", $referred);
echo $pieces[1]; // admin
查看更多
叛逆
3楼-- · 2020-05-01 08:32

Is not a really clean solution, but you can try something like:

$url = "MYURL";
$parse = parse_url($url);
parse_str($parse['query']);

echo $referredby; // same name of the get param (see parse_str doc)

PHP.net: Warning

Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.

Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.

Read section on security of Using Register Globals explaining why it is dangerous.

查看更多
家丑人穷心不美
4楼-- · 2020-05-01 08:33
$referred = $_GET['referredby'];
查看更多
乱世女痞
5楼-- · 2020-05-01 08:34

You can use parse_str() function.

$url = "www.mysite.com/register/?email=admin";
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
查看更多
Anthone
6楼-- · 2020-05-01 08:37

Try this code,

$url = "www.mysite.com/register/?referredby=admin";
$parse = parse_url($url, PHP_URL_QUERY);
parse_str($parse, $output);
echo $output['referredby'];

查看更多
三岁会撩人
7楼-- · 2020-05-01 08:42

I don't know if it's still relevant for you, but maybe it is for others: I've recently released a composer package for parsing urls (https://www.crwlr.software/packages/url). Using that library you can do it like this:

$url = 'https://www.example.com/register/?referredby=admin';
$query = Crwlr\Url\Url::parse($url)->queryArray();
echo $query['referredby'];

The parse method parses the url and returns an object, the queryArray method returns the url query as array.

查看更多
登录 后发表回答