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

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);

Related

Replace GET variable value in PHP [duplicate]

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

Is there a PHP equivalent to Java's ServletRequest.getParameterValues()? [duplicate]

This question already has answers here:
How to pass an array within a query string?
(12 answers)
Closed 4 years ago.
I have an array of parameter values (with matching parameter names) in my request URL, like this:
?my_array_of_values=First&my_array_of_values=Second
In a Java servlet, I can detect them like this:
ServletRequest request = ...;
String[] myArrayOfValues = request.getParameterValues("my_array_of_values");
And this will result in:
myArrayOfValues[0] = "First";
myArrayOfValues1 = "Second";
...which is what I want.
However, I am not sure how to get the same results in PHP. For the same (above) parameters, when I try:
print_r($_GET);
it results in
Array ( [my_array_of_values] => Second )
...i.e., the "First" parameter is lost.
I can see why this happens, but is there a way to detect such an array of parameter values in PHP as you can in Java/servlets? If not, is there a recommended workaround or alternative way of doing it?
I don't know about the strange magic that happens in a Java environment, but query params must have different names or else they will overwrite each other.
In the example of ?my_array_of_values=First&my_array_of_values=Second only the last given value is returned. It is the same as assigning different values to the same variable one after the other.
You may retrieve a single parameter as array though, by using angle brackets after the parameter name:
?my_array_of_values[]=First&my_array_of_values[]=Second
In that case $_GET['my_array_of_values'] will be an array with all the given values.
See also: Authoritative position of duplicate HTTP GET query keys

PHP: Url as parameter

I'm building a small restful api and I'm asking if it's possible to seperate the url to php file and the end of the url.
E.g. www.mydomain.com/api/parameter/1/2/
In this case the php file is adressed with www.mydomain.com/api/ or www.mydomain.com/api/index.php and parameter/1/2/ is the parameter.
I want a CRUD interface so that GET without parameter gets a list of all data. To achieve this I need to check if a parameter is attached and to extract the parameter.
Other example
www.mydomain.com/topics/ => gets all topics
www.mydomain.com/topics/1/posts/ => gets all posts of topic 1,
www.mydomain.com/topics/1/posts/2/ => gets post 2 of topic 1
My question is: Is it possible and how?
You would probably have to read the request URI from the end of the URL using $_SERVER['request_uri']. This would return /api/parameter/1/2. You could then substring it if the length is reliable, or use a regex with preg_match to get just the parameter section. e.g.
preg_match("parameter\/.*", $_SERVER['request_uri'], $matches)
would return either the string parameter/1/2 in the $matches variable, or false if no match was found
But yeah like others are saying, you're probably better using GET parameters if you can, and just do a check using isset() to see if there are any parameters.

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.

PHP - Data after "?" in URL displays different information

I know the title isn't very clear. I'm new to PHP, so there might be name for this kind of thing, I'll try to explain as best as I can. Sometimes in a URL, when using PHP, there will be a question mark, followed by data. I'm sorry, I know this is very noobish, but I'm not sure what it's called to look for a tutorial or anything. Here is what I mean:
http://www.website.com/error_messages.php?error_id=0
How do you configure it to display different text depending on what the number is (in this example it's a number)
Could somebody please tell me what this is called and how I could do this? I've been working with PHP for a couple days and I'm lost. Thank you so very much for understanding that I am very new at this.
That "data" is the URL querystring, and it encodes the GET variables of that HTTP request.
Here's more info on query strings: http://en.wikipedia.org/wiki/Query_string
In PHP you access these with the $_GET "super-global" variable:
// http://www.website.com/error%5Fmessages.php?error%5Fid=0
// %5F is a urlencoded '_' character, which your webserver will most likely
// decode before it gets to PHP.
// So ?error%5Fid=0 reaches PHP as the 'error_id' GET variable
$error_id = $_GET['error_id'];
echo $error_id; // this will be 0
The querystring can encode multiple GET variables by separating them with the & character. For example:
?error_id=0&error_message=Something%20bad%20happened
error_id => "0"
error_message => "Something bad happened"
In that example you can also see that spaces are encoded as %20.
Here's more info on "percent encoding": http://en.wikipedia.org/wiki/Percent-encoding
The data after the question mark is called the "query string". It usually contains data in the following format:
param1=value1&param2=value2
Ie, it is a list of key-value pairs, each pair separated with the ampersand character (&). In order to pass special characters in the values, they have to be encoded using URL-encoding format: Using the percent sign (%) followed by two hexadecimal characters representing the character code.
In PHP, parameters passed via the query string are automatically propagated to your script using the super-global variable $_GET:
echo $_GET['param1']; // will produce "value1" for the example above.
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];
It's called the query string.
In PHP you can access its data via the superglobal $_GET
For example:
http://www.example.com/?hello=world
<?php
// Use htmlspecialchars to prevent cross-site scripting attacks (XSS)
echo htmlspecialchars($_GET['hello']);
?>
If you want to create a query string to append to a URL you can use http_build_query():
$str = http_build_query(array('hello' => 'world'));
As previously described, the data after the ? is the querystring (or GET data), and is accessed using the $_GET variable. The $_GET variable is an array containing the name=value pairs in the querystring.
Here is a breif description of $_GET and an example of it's usage:
http://www.w3schools.com/php/php_get.asp
Data can also be submited to a PHP script as POST data (found in the $_POST variable), which is used for passwords, etc, and is not stored in the URL. The $_REQUEST variable contains both POST and GET data. POST and GET data usually originates from being entered into a web form by a user (but GET data can also come directly from a link to an address, like in your example). More info about using web forms in PHP can be found here:
http://www.w3schools.com/php/php_forms.asp
its called "query string"
and you can retrieve it via $_SERVER["QUERY_STRING"]
or you can loop through $_GET
in this case the error_id, you can check it by something like this
echo $_GET['error_id'];
The term you are looking for is GET. So in php you need to access the GET variables in $_GET['variable_name'], e.g. in the example you gave $_GET['error_id'] will contain the value 0. You can then use this in your logic to echo back different information.
The bit after the question mark is called a Query String. The format is typically, although not necessarily always, key-value pairs, where the pairs are separated by an ampersand (&) and the value is separated from the name by an equals sign (=): ?var1=value1&var2=value2&.... Most web programming environments provide an easy way to access name-value pairs in this format. For example, in PHP, there is a superglobal, which is an associative array of these key-value-pairs. In your example, error_id would be accessible via:
$_GET['error_id']
The reason for the name "GET" is that query string variables are typically associated with a HTTP GET request. POST requests can contain GET variables too, whereas GET requests can't contain POST variables.
As to the rest of your question, you could approach the text issue in a number of ways, the simplest being switching on the error id:
$error_id = isset($_GET['error_id']) ? $_GET['error_id'] : 0;
switch($error_id) {
case 1:
echo "Error 1";
break;
default:
echo "Unknown Error";
break;
}
and more complex ways involve looking up the error message from a file, database or what have you.

Categories