Adding to url with link - php

My url contains many variables that I want untouched (don't worry they aren't important).
Let's say it contained...
../index.php?id=5
How would I make a url that just adds
&current=1
rather than replacing it entirely?
I'd like...
../index.php?id=5&current=1
rather than..
../index.php?current=1
I know it's a simple question but that's why I can't figure it out.
Thanks.

To append a parameter to a URL you can do this:
function addParam( $url, $param ){
if( strrpos( $url, '?' ) === false){
$url .= '?' . $param;
} else {
$url .= '&' . $param;
}
return $url;
}
$url = "../index.php?id=5";
$url = addParam( $url, "current=1");

You should just create your link to 'add' that parameter
The Link
and then obviously in the index.php somewhere you'll look for the current variable and do what you need to:
<?php
if(isset($_GET['current']) && !empty($_GET['current]) {
// Do stuff here for the 'current' variable
$current = trim($_GET['current']);
}
?>

On the links that you require the $current variable, I suppose that you could just casually put it in the href attribute. For the index,php file, so something like this....
if(isset($_GET['current']))
{
$current = $_GET['current'];
//Do the rest of what you need to do with this variable
}

Try this one:
$givenVar = "";
foreach($_GET as $key=>$val){
$givenVar .= "&".$key."=".$val;
}
$var = "&num=1";
$link = "?".$givenVar."".$var;
echo $link;

You can just add the variable to the href,
When you clink it while the address is
../index.php?id=5
trust me you then go to
../index.php?id=5&current=1
BUT if you click that link again, than you 'll go to
../index.php?id=5&current=1&current=1
Actually I thinks that's tricky and bad practice to just append the variable.
I suggest you to do it like:
<?php
$query = isset($_GET) ? http_build_query($_GET) . '&current=1' : 'current=1';
?>
A Label
take a look http://us.php.net/manual/en/function.http-build-query.php

I don't know why in Earth you would need this, but here we are. This should do the trick.
$appendString = "&current=1";
$pageURL = $_SERVER["REQUEST_URI"].$appendString;
$_SERVER["REQUEST_URI"] should return just the name of the requested page, with any other GET variable attached. The other string should be clear enough!

Related

Preventing adding link to another link

Hello I'm currently working with php to generate a menu with a own build CMS system.
I'm making a dynamic link with : $url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."/";
Than I'm adding . $row_menu['page_link'] from the database. At first it works perfect:
as example =
$row_menu['page_link'] = page2;
$url . $row_menu['page_link'];
it will return as example : http://example.com/page2
But when I click again, it adds page2 again like : http://example.com/page2/page2
How do i prevent this?
Thanks in advance!
Because at first time your $_SERVER['REQUEST_URI'] will be like http://example.com but when the user click on the link then the value of $_SERVER['REQUEST_URI'] would become http://example.com/page2.That's why it is appending two times.
Instead you can use HTTP_REFERER like
$url = $_SERVER['HTTP_REFERER'].$row_menu['page_link'];
Considering that your $_SERVER['HTTP_REFERER'] will results http://example.com.Also you can try like
$protocol = 'http';
$url = $protocol .'//'. $_SERVER['HTTP_HOST'] .'/'. $row_menu['page_link'];
REQUEST_URI will give you whatever comes after example.com, so leave that out all together.
$url = $_SERVER['HTTP_HOST'] . "/" . $row_menu['page_link'];
You can find a full list of the $_SERVER references here.
Try this:
$requested_uri = $_SERVER['REQUESTED_URI'];
$host = $_SERVER['HTTP_HOST'];
$uri_segments = explode('/',$requested_uri);
$row_menu['page_link'] = 'page2';
if($row_menu['page_link'] == $uri_segments[sizeof($uri_segments)-1]) {
array_pop($uri_segments);
}
$uri = implode('/',$uri_segments);
$url = 'http://'.$host.'/'.$uri.'/'.$row_menu['page_link'];
echo $url;

URL Replacement in PHP

I'm trying to change a value in a string that's holding my current URL. I'm trying to get something like
http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory
to look like
http://myurl.com/test/end.php?req=&srclang=english&destlang=english&service=MyMemory
replacing begin.php for end.php.
I need the end.php to be stored in a variable so it can change, but begin.php can be a static string.
I tried this, but it didn't work:
$endURL = 'end.php';
$beginURL = 'begin.php';
$newURL = str_ireplace($beginURL,$endURL,$url);
EDIT:
Also, if I wanted to replace
http://myurl.com/begin.php?req=&srclang=english&destlang=english&service=MyMemory
with
http://newsite.com/end.php?req=&srclang=english&destlang=english&service=MyMemory
then how would I go about doing that?
Assuming that you want to replace the script filename of the url, you can use something like this :
<?php
$endURL = 'end.php';
$url ="http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory";
$pattern = '/(.+)\/([^?\/]+)\?(.+)/';
$replacement = '${1}/'.$endURL.'?${3}';
$newURL = preg_replace($pattern , $replacement, $url);
echo "url : $url <br>";
echo "newURL : $newURL <br>";
?>
How do you want them to get to end.php from beigin.php? Seems like you can just to a FORM submit to end.php and pass in the variables via POST or GET variables.
The only way to change what page (end.php, begin.php) a user is on is to link them to another page from that page, this requires a page refresh.
I recently made a PHP-file for this, it ended up looking like this:
$vars = $_SERVER["QUERY_STRING"];
$filename = $_SERVER["PHP_SELF"];
$filename = substr($filename, 4);
// for me substr removed 'abc/' in the beginning of the string, you can of course adjust this variable, this is the "end.php"-variable for you.
if (strlen($vars) > 0) $vars = '?' . $vars;
$resultURL = "http://somewhere.com" . $filename . $vars;

keeping url parameters during pagination

Is there any way to keep my GET parameters when paginating.
My problem is that I have a few different urls i.e
questions.php?sort=votes&author_id=1&page=3
index.php?sort=answers&style=question&page=4
How in my pagination class am I supposed to create a link to the page with a different page number on it but yet still keep the other parts of the url?
If you wanted to write your own function that did something like http_build_query, or if you needed to customize it's operations for some reason or another:
<?php
function add_edit_gets($parameter, $value) {
$params = array();
$output = "?";
$firstRun = true;
foreach($_GET as $key=>$val) {
if($key != $parameter) {
if(!$firstRun) {
$output .= "&";
} else {
$firstRun = false;
}
$output .= $key."=".urlencode($val);
}
}
if(!$firstRun)
$output .= "&";
$output .= $parameter."=".urlencode($value);
return htmlentities($output);
}
?>
Then you could just write out your links like:
Click to go to page 2
You could use http_build_query() for this. It's much cleaner than deleting the old parameter by hand.
It should be possible to pass a merged array consisting of $_GET and your new values, and get a clean URL.
$new_data = array("currentpage" => "mypage.html");
$full_data = array_merge($_GET, $new_data); // New data will overwrite old entry
$url = http_build_query($full_data);
In short, you just parse the URL and then you add the parameter at the end or replace it if it already exists.
$parts = parse_url($url) + array('query' => array());
parse_str($parts['query'], $query);
$query['page'] = $page;
$parts['query'] = http_build_str($query);
$newUrl = http_build_url($parts);
This example code requires the PHP HTTP module for http_build_url and http_build_str. The later can be replaced with http_build_query and for the first one a PHP userspace implementation exists in case you don't have the module installed.
Another alternative is to use the Net_URL2 package which offers an interface to diverse URL operations:
$op = new Net_URL2($url);
$op->setQueryVariable('page', $page);
$newUrl = (string) $op;
It's more flexible and expressive.
How about storing your page parameter in a session, so you don't have to modify every single page url?

PHP: Adding parameters to a url?

If I have the url mysite.com/test.php?id=1. The id is set when the page loads and can be anything. There could also be others in there such as ?id=1&sort=new. Is there a way just to add another to the end without finding out what the others are first then building a new url? thanks.
As an alternative to Kolink's answer, I think I would utilize http_build_query(). This way, if there is nothing in the query string, you don't get an extra &. Although, it won't really make a difference at all. Kolink's answer is perfectly fine. I'm posting this mainly to introduce you to http_build_query(), as you will likely need it later:
http_build_query(array_merge($_GET, array('newvar'=>'123')))
Basically, we use http_build_query() to take everything in $_GET, and merge it with an array of any other parameters we want. In this example, I just create an array on the fly, using your example parameter. In practice, you'll likely have an array like this somewhere already.
"?".$_SERVER['QUERY_STRING']."&newvar=123";
Something like that.
Use this function: https://github.com/patrykparcheta/misc/blob/master/addQueryArgs.php
function addQueryArgs(array $args, string $url)
{
if (filter_var($url, FILTER_VALIDATE_URL)) {
$urlParts = parse_url($url);
if (isset($urlParts['query'])) {
parse_str($urlParts['query'], $urlQueryArgs);
$urlParts['query'] = http_build_query(array_merge($urlQueryArgs, $args));
$newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . $urlParts['query'];
} else {
$newUrl = $url . '?' . http_build_query($args);
}
return $newUrl;
} else {
return $url;
}
}
$newUrl = addQueryArgs(array('add' => 'this', 'and' => 'this'), 'http://example.com/?have=others');

Replacing a specific part of a query string PHP

I use $_SERVER['QUERY_STRING'] to get the query sting.
A example would be a=123&b=456&c=789
How could I remove the b value from the query string to obtain a=123&c=789 where b can be any value of any length and is alpha numeric.
Any ideas appreciated, thanks.
A solution using url parsing:
parse_str($_SERVER['QUERY_STRING'], $result_array);
unset($result_array['b']);
$_SERVER['QUERY_STRING'] = http_build_query($result_array);
The value is going to be $_GET['b'].
How about:
str_replace('&b='.$_GET['b'], '', $_SERVER['QUERY_STRING']);
you can use this function:
function Remove_QS_Key($url, $key) {
$url = preg_replace('/(?:&|(\?))'.$key.'=[^&]*(?(1)&|)?/i', "$1", $url);
return $url;
}
to remove any key you want, e.g.
echo Remove_QS_Key("http://domain.com/?a=b&ref=dusername&c=d&e=f&g=h", "ref");
result
http://www.domain.com/?a=b&c=d&e=f&g=h
Try this:
$query_new = preg_replace('/(^|&)b=[^&]*/', '', $query);
All the answers look good, but it will be more flexible if you do:
// Make a copy of $_GET to keep the original data
$getCopy = $_GET;
unset($getCopy['b']); // or whatever var you want to take out
// This is your cleaned array
var_dump($getCopy);
// If you need the URL-encoded string, just use http_build_query()
$encodedString = http_build_query($getCopy);
You simply make a variable using $_GET and exclude b query string in build process:
$query_string_new = 'a=' . urlencode($_GET['a']) . '&c=' . urlencode($_GET['c']);
The $query_string_new should now contain a=123&c=789
Pear already has a class(Net_URL2) that handles URL parsing/building:
Install via Composer: https://packagist.org/packages/pear/net_url2
Install as include: https://github.com/pear/Net_URL2/blob/master/Net/URL2.php
Example code:
$url = new Net_URL2('http://www.example.com/?one=1');
$url->setQueryVariable('two', 2);
echo $url; // http://www.example.com/?one=1&two=2
Here is a function to replace a query parameter: (like example.com?a=1&b=2 -> example.com?a=5&b=2)
function replace_qs_key($key, $value) {
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$current_url_without_qs = strtok($current_url, '?');
parse_str($_SERVER['QUERY_STRING'], $query_params);
$query_params['page'] = $value;
$_SERVER['QUERY_STRING'] = http_build_query($query_params);
$new_url = $current_url_without_qs .'?'. $_SERVER['QUERY_STRING'];
return $new_url;
}

Categories