how to build hyperlink for query string in php - php

I have a question, How I can add another get variable in my current url
book.php?action=addressbook
i want to add
book.php?action=addressbook&page=2
how to generate hyperlink for this, i have tried it using $_SERVER['PHP_SELF'] but query string are not included in url its showing something like that
book.php?page=2
I want to append my other variables to query string
Please help

You can also use http_build_query(); to append more params to your URL
$params = $_GET;
$params["item"] = 45;
$new_query_string = http_build_query($params);
for instance:
$data = array('page'=> 34,
'item' => 45);
echo http_build_query($data); //page=34&item=45
or include amp
echo http_build_query($data, '', '&'); //page=34&&item=45

$get = $_GET;
$get['page'] = 2;
echo 'Page 2';

Related

Php parse url and remove parametr issue

I have url like this :
/leads/set_attributes.html?lead_id=3793&name=TEST
I need remove 'name' and return url.
I try do it like this:
$vars = [];
parse_str(html_entity_decode($sAddQuery), $vars);
unset($vars['name']);
$sAddQuery = http_build_query($vars);
But i always get
%3Flead_id=3793
as result. I tried use html_entity_decode for array elements but it did not help. How can i solve this? Thanks
Modify your code to :
<?php
$url = parse_url('/leads/set_attributes.html?lead_id=3793&name=TEST');
$str = $url['query'];
parse_str($str, $params); //parse URL
unset($params['name']); //unset name parameter
$string = http_build_query($params); //again built the URL string
var_dump($string);
?>
Hope it works!

Extract particular point of URL in PHP

I'm trying to get a very specific part of a URL using PHP so that I can use it as a variable later on.
The URL I have is:
https://forums.mydomain.com/index.php?/clubs/11-Default-Club
The particular part I am trying to extract is the 11 part between the /clubs/ and -Default-Club bits.
I was wondering what the best way to do this was. I've seen examples on here that use a regex-esque parser but I can't wrap my head around it for this particular instance.
Thanks
Edit; this is what I've tried so far using an explode query, but it seems to give me all sorts of elements which are not present in the URL above:
$url = $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
$url = array_filter($url);
$url = array_merge($url, array());
Which returns:
Array ( [0] => index.php?app=core&module=system&controller=widgets&do=getBlock&blockID=plugin_9_bimBlankWidget_dqtr03ssz&pageApp=core&pageModule=clubs&pageController=view&pageArea=header&orientation=horizontal&csrfKey=8e19769b95c733b05439755827a98ac8 )
If you expect that the string with dashes (11-Default-Club) will be always at the end you can try this:
$url = $_SERVER['REQUEST_URI'];
$urlParts = explode('/', $url);
$string = end($urlParts);
$stringParts = explode('-', $string);
$theNumber = $stringParts[0]; // this will be 11
I'd rather be explicit:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$query = parse_url($url, PHP_URL_QUERY);
$pattern = '#^/clubs/(\d+)[a-zA-Z-]+$#';
$digits = preg_match($pattern, $query, $matches)
? $matches[1]
: null;
var_dump($digits);
Output:
string(2) "11"
If this URL structure is fix for all URLs in your site and you only want to get the integer/number/digit part of the URL:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$int = (int) filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $int;
If this url structure is fix for all URLs in your site then below is best way to get your value.
<?php
$url = "https://forums.mydomain.com/index.php?/clubs/11-Default-Club";
$url = explode('/', $url);
$url = array_filter($url);
$end = end($url);
$end_parts = explode('-',$end);
echo $end_parts[0];
Output:
11

Grab values from PHP string

I have a variable in my PHP script called $url
Here's an example of how I use it:
<?php
$url = '/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";
I'd like to have a PHP snippet that grabs the valus of utm_source, utm_campaign & utm_medium. How do I achieve this?
Try This
<?php
$url = "/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";
$url_parsed=parse_url($url);
$query_params=[];
$query_parsed=parse_str($url_parsed['query'],$query_params);
echo $query_params['utm_source'].PHP_EOL.
$query_params['utm_campaign'].PHP_EOL.
$query_params['utm_medium'].PHP_EOL;
?>
Another way with explode function:
<?php
$url = "/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";
$params = explode("=", $url);
$utmSource = explode("&", $params[1]);
$utmCampaign = explode("&", $params[2]);
$utmMedium = $params[3];
I have a feeling that the function parse_str() is exactly what you are looking for. See https://secure.php.net/manual/en/function.parse-str.php

Remove "http://" from URL string

I am using a bit.ly shortener for my custom domain. It outputs http://shrt.dmn/abc123; however, I'd like it to just output shrt.dmn/abc123.
Here is my code.
//automatically create bit.ly url for wordpress widgets
function bitly()
{
//login information
$url = get_permalink(); //for wordpress permalink
$login = 'UserName'; //your bit.ly login
$apikey = 'API_KEY'; //add your bit.ly APIkey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//generate the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//fetch url
$response = file_get_contents($bitly);
//for json formating
if(strtolower($format) == 'json')
{
$json = #json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //for xml formatting
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
As long as it is supposed to be url and if there is http:// - then this solution is the simplest possible:
$url = str_replace('http://', '', $url);
Change your following line:
echo $json['results'][$url]['shortUrl'];
for this one:
echo substr( $json['results'][$url]['shortUrl'], 7);
You want to do a preg_replace.
$variable = preg_replace( '/http:\/\//', '', $variable ); (this is untested, so you might also need to escape the : character ).
you can also achieve the same effect with $variable = str_replace('http://', '', $variable )

Parsing GET request parameters in a URL that contains another URL

Here is the url:
http://localhost/test.php?id=http://google.com/?var=234&key=234
And I can't get the full $_GET['id'] or $_REQUEST['d'].
<?php
print_r($_REQUEST['id']);
//And this is the output http://google.com/?var=234
//the **&key=234** ain't show
?>
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
$my_url outputs:
http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234
So now you can get this value using $_GET['id'] or $_REQUEST['id'] (decoded).
echo urldecode($_GET["id"]);
Output
http://google.com/?var=234&key=234
To get every GET parameter:
foreach ($_GET as $key=>$value) {
echo "$key = " . urldecode($value) . "<br />\n";
}
$key is GET key and $value is GET value for $key.
Or you can use alternative solution to get array of GET params
$get_parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
$pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($pairs as $pair) {
$part = explode('=', $pair);
$get_parameters[$part[0]] = sizeof($part)>1 ? urldecode($part[1]) : "";
}
}
$get_parameters is same as url decoded $_GET.
While creating url encode them with urlencode
$val=urlencode('http://google.com/?var=234&key=234')
Click here
and while fetching decode it wiht urldecode
You may have to use urlencode on the string 'http://google.com/?var=234&key=234'
I had a similar problem and ended up using parse_url and parse_str, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
function so_5645412_url_params($url) {
$url_comps = parse_url($url);
$query = $url_comps['query'];
$args = array();
parse_str($query, $args);
return $args;
}
$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => http://google.com/?var=234&key=234 )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )
you use bad character like ? and & and etc ...
edit it to new code
see this links
http://antoine.goutenoir.com/blog/2010/10/11/php-slugify-a-string/
http://sourcecookbook.com/en/recipes/8/function-to-slugify-strings-in-php
also you can use urlencode
$val=urlencode('http://google.com/?var=234&key=234')
The correct php way is to use parse_url()
http://php.net/manual/en/function.parse-url.php
(from php manual)
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
if (isset($_SERVER['HTTPS'])){
echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}else{
echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}

Categories