Replace GET variable value in PHP [duplicate] - php

This question already has answers here:
How to get and change URL variable PHP
(8 answers)
Closed 8 months ago.
everyone.
Is it possible to replace a specific GET variable value by using RegEx?
Here is what I have in mind.
I have a URL: https://example.com/category/?var1=value1&page=2&var2=value2
It can have different GET variables, but the one that it always has is "page".
What I want to do is this:
Set the URL value to a string variable in PHP code - Done.
$current_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
In that string replace the value of the "page" variable with another value but keep the rest of the URL the same so that I could use them for paging buttons - Struggling
Take the string variable and echo it in a href tag - Done.
Next
The "page" value, of course, is not always 2 - it represents the page number where the user currently is so can be anything from 1 to any other integer.
I'm trying to do it with explodes and joins, but haven't succeeded yet. Maybe there is an easier way to replace values using RegEx?

Here's a quick way to replace a parameter. Note, however, that this solution doesn't necessarily work out of the box for all URLs as some may not have a query.
# Your URL.
$url = "https://example.com/category/?var1=value1&page=2&var2=value2";
# Parse your URL to get its composing parts.
$parts = parse_url($url);
# Save the query of the URL.
$query = $parts["query"];
# Parse the query to get an array of the individual parameters.
parse_str($query, $params);
# Replace the value of the parametre you want.
$params["page"] = "your-value";
# Build the query.
$newQuery = http_build_query($params);
# Replace the old query with the new one.
$newUrl = str_replace($query, $newQuery, $url);
Snippet

Related

How to get hash(#) value in query string [duplicate]

This question already has answers here:
Get fragment (value after hash '#') from a URL [closed]
(10 answers)
Closed 6 years ago.
I am trying to post # parameter in query string like...
www.demo.php?tag=c#
Now i am trying to get tag value in another page with
$_GET['tag']
But i am not getting somehow # value is not coming with $_GET. I can get only "c".
The hash character (#) has a special meaning in URLs. It introduces a fragment identifier. A fragment identifier is usually used to locate a certain position inside the page.
A fragment identifier is handled by the browser, it is removed from the URL when the browser makes the HTTP request to the server.
Being a special character, if you want it to have its literal value you must encode it. The correct way to write the URL in your question is:
www.demo.php?tag=c%23
When it's written this way, $_GET['tag'] contains the correct value ('c#').
If you generate such URLs from PHP code (probably by getting the values of tag from an external resource like a database) you have to use the PHP function urlencode() to properly encode the values you put in URLs. Or, even better, create an array with all the URL arguments and their values then pass it to http_build_query() to generate the URL:
$params = array(
'tag' => 'c#',
'page' => 2,
);
$url = 'http://localhost/demo.php?'.http_build_query($params);

inserting an extra param at the end of the URL

i'm trying to inject an extra param at the end of the query string of a url being passed as a value.
i have tried
<?PHP preg_replace('/(http:\/\/www.site.com)/i','$1',$_GET['url']."&EXTRA-PARAM");
but sometimes URL does not contain any query string. how can i make it start with ? instead of & if there is no query string presant
The preg_replace you have in your question has no effect:
preg_replace('/(http:\/\/www.site.com)/i','$1',$_GET['url']."&EXTRA-PARAM");
Whatever the last argument is, it will be returned by that preg_replace call. Either you don't have a match and nothing is replaced, or you have a match, but then you replace what you found with... what you found. So in both cases you get the same result.
$1 is a back-reference to http:\/\/www.site.com, so actually the quoted statement is equivalent to this:
preg_replace('/http:\/\/www.site.com/i','http:\/\/www.site.com',
$_GET['url']."&EXTRA-PARAM");
Your final value is always:
$_GET['url']."&EXTRA-PARAM"
So, you could just have used that, and skip the preg_replace.
What I answer here is how to better write that part ($_GET['url']."&EXTRA-PARAM"), i.e. the question: "inserting an extra param at the end of the URL".
This concatenation can lead to missing ?. Worse, it will not lead to a functional parameter if $_GET['url'] has a hash (#).
Here is a solution for that with preg_replace_callback. It takes into account that a given URL may or may not have:
a hash (#) component;
a question mark ?
some query after the ?
some & to separate query parts
The function accepts as second argument what needs to be added to the query part of the provided URL, which may be a string (must be URL encoded), or an associative array with items to add to the URL. This array will then be fed to the function http_build_query:
function addUrlQuery($url, $qry) {
if (!is_string($qry)) $qry = http_build_query($qry);
return preg_replace_callback("/^(.*?)(\?(.*?))?(#.*)?$/",
function ($matches) use ($qry) {
return $matches[1] . "?" .
(empty($matches[3]) ? "" : $matches[3] . "&") .
$qry .
(empty($matches[4]) ? "" : $matches[4]);
}, $url);
}
Example use:
$url = addUrlQuery($_GET['url'], "EXTRA-PARAM");
echo addUrlQuery("http://myserver.com?x#title", ["EXTRA-PARAM" => 1]);
echo addUrlQuery("http://myserver.com/" . $relative_url, "EXTRA-PARAM");
You can see the function run on several test cases on eval.in.
The problem with $_GET['url']
If you have a URL passed as a query argument to the current URL, like this:
http://myserver.com/index.php?url=http://test.com/index.php?a=1
Then you must realise this is not a good URL. Some characters need to be escaped. Certainly the ampersand (&) needs to be escaped. If you have this:
http://myserver.com/index.php?url=http://test.com/index.php?a=1&b=2
Ask yourself: is b a query parameter of the current URL, or of the URL passed as url argument?
The answer: it is a query parameter of the current URL. You would access it with $_GET['b']. And the value of $_GET['url'] is now just:
http://test.com/index.php?a=1
So... you need to escape & when you want b to be a query argument of the url parameter, and not of the current query:
http://myserver.com/index.php?url=http://test.com/index.php?a=1%26b=2
Note the %26: it is the code for &. Now if you look at $_GET['url'] you will get:
http://test.com/index.php?a=1&b=2
What if URL is provided without proper encoding?
In this case, you have to make assumptions. If you know for sure that the url parameter is the only parameter you will get on the current URL, then you can conclude that any other you get, really belong to the URL that is passed via that url parameter.
You would then take all the parameters from $_GET, except url, and add them (with the function above) to the value of $_GET['url'].

how to read ending URL numbers as a value?

I have a survey page that will reference an invoice number. I'm trying to make the URL clean so that there are no question marks or equal sign. For example:
http://www.MyWebsite.com/survey/832551
Where 832551 is the invoice ID in reference. I am trying to avoid ?invoice_ID=832551.
How can I get a php page to read that and make it a variable value?
php 4.0.8
Make an variable with url
//You get all the url in array
$var = $_SERVER["REQUEST_URI"];
//Explode it in array, with slash '/'
$var_array = explode("/",$_SERVER["REQUEST_URI"]);
//Get the last element of array, which will be the invoice_id
$invoice_id = array_pop($var_array);
But if you use some of php framework this is how you get controller attribute by default,
I suggest you to use some php framework with MVC structure.
It is what we call URL rewriting.
You can find a good example here
http://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/

Parsing URL query in PHP [duplicate]

This question already has answers here:
Parse query string into an array
(12 answers)
Closed 8 months ago.
Assuming a URL of www.domain.org?x=1&y=2&z=3, what would be a smart method to separate out the query elements of a URL in PHP without using GET or REQUEST?
$url = parse_url($url);
echo $url[fragment];
I don't think it's possible to return query parts separately, is it? From what I can tell, the query will just say x=1&y=2&z=3, but please let me know if I am wrong. Otherwise, what would you do to parse the $url[query]?
Fragment should be Query instead. Sorry for the confusion; I am learning!
You can take the second step and parse the query string using parse_str.
$url = 'www.domain.org?x=1&y=2&z=3';
$url_parts = parse_url($url);
parse_str($url_parts['query'], $query_parts);
var_dump($query_parts);
I assumed you meant the query string instead of the fragment because there isn't a standard pattern for fragments.
The parse_url function returns several components, including query. To parse it you should run parse_str.
$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $parsedQueryString);
If you are going just to parse your HTTP request URL:
use the $_REQUEST['x'], $_REQUEST['y'], and $_REQUEST['z'] variables to access the x, y, and z parameters;
use $_SERVER['QUERY_STRING'] to get the whole URL query string.
I was getting errors with some of the answers, but they did lead me to the right answer.
$url = 'www.domain.org?x=1&y=2&z=3';
$query = $url[query];
parse_str($query);
echo "$x &y $z";
And this outputs 1 2 3, which is what I was trying to figure out.
As a one-liner with no error checking
parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $query);
$query will contain the query string parameters.
Unlike PHP's $_GET, this will work with query parameters of any length.
I highly recommend using this URL wrapper (which I have written).
It is capable of parsing URLs of complexity like protocol://username:password#subdomain.domain.tld:80/some/path?query=value#fragment and has many more goodies.

Extracting a URL string with same results as a $_GET [duplicate]

This question already has answers here:
Getting vars from URL
(6 answers)
Closed 8 years ago.
Ok, so I have a string like so:
index.php?page=test2;sa=blah
And I need only to grab what gets returned using $_GET['page'], so it will return, test2 in this case. BUT page MUST be defined DIRECTLY after index.php? before it can return an actual string. How do I do this? I just need the same results returned from a $_GET for the page variable. I can also have just this:
index.php?page=blah
Should return blah
or this:
index.php?page=anything&sa=blah
Returns anything
or this:
index.php?action=blah;page=2
Returns empty string, cause this is NOT directly after index.php?
or basically any url, but it needs to grab the variable of page if it exists, only after index.php?. And sometimes page might not even exist at all, in this case, an empty string should be returned.
How can I do this? I am not browsing to the URL in my browser, so, don't think $_GET will work, but it needs to simulate and return the EXACT same results that $_GET will return in the browser, but only if page is defined directly after index.php?
parse_url and parse_str are your friends.
Please use following code:
function get($name, $url) {
$src = parse_url($url);
$src = $src['query'];
parse_str($src, $tag);
return $tag[$name];
}
you can check if the element received at $_GET is equal that you expect by comparison or a simple if statement. if not, then process the string to find it (if needed). Maybe also used the index of the elemnt to determine if process or not.

Categories