I am trying to load a single post with custom URL. But it is redirecting to default URL because of "&" character. without & character, it is working fine. But how can I read this "&" in URL? My code is below,
function mutually_add_query_vars($vars) {
return array('L') + $vars;
}
add_filter('query_vars', 'mutually_add_query_vars');
and Loading for a single template
function mutually_template4($template) {
global $wp;
if ($wp->query_vars['L']=='6'.html_entity_decode('&').'au=2') {
return dirname( __FILE__ ) . '/single-ad.php';
}
else {
return $template;
}
}
add_filter('single_template', 'mutually_template4');
I tried with html_entity_decode, but it works nothing.
You need to encode
So & will be %26
What you need to do is URL encoding instead of HTML encoding (Both are different). Therefore, you can replace & with %26. Click here to see reference to URL encoding.
You can also use urlencode ( string $str ) PHP function to encode a string with URL friendly values.
GET parameter pairs in a URL start with a ? then are separated by an & symbol and key/values are separated by an = so myurl.com?L=6&au=2 would be parsed into two separate $wp_query_vars elements one being assigned to L and the other to au there should be no need to manually parse out the & symbol if for some reason your key/value included an & it would need to be URI encoded as %26 as other answers have suggested :)
function mutually_template4($template) {
global $wp;
if ($wp->query_vars['L']=='6' && $wp->query_vars['au']=='2') {
return dirname( __FILE__ ) . '/single-ad.php';
}
else {
return $template;
}
}
add_filter('single_template', 'mutually_template4');
Related
there is an external page, that passes a URL using a param value, in the querystring. to my page.
eg: page.php?URL=http://www.domain2.com?foo=bar
i tried saving the param using
$url = $_GET['url']
the problem is the reffering page does not send it encoded. and therefore it recognizes anything trailing the "&" as the beginning of a new param.
i need a way to parse the url in a way that anything trailing the second "?" is part or the passed url and not the acctual querystring.
Get the full querystring and then take out the 'URL=' part of it
$name = http_build_query($_GET);
$name = substr($name, strlen('URL='));
Antonio's answer is probably best. A less elegant way would also work:
$url = $_GET['url'];
$keys = array_keys($_GET);
$i=1;
foreach($_GET as $value) {
$url .= '&'.$keys[$i].'='.$value;
$i++;
}
echo $url;
Something like this might help:
// The full request
$request_full = $_SERVER["REQUEST_URI"];
// Position of the first "?" inside $request_full
$pos_question_mark = strpos($request_full, '?');
// Position of the query itself
$pos_query = $pos_question_mark + 1;
// Extract the malformed query from $request_full
$request_query = substr($request_full, $pos_query);
// Look for patterns that might corrupt the query
if (preg_match('/([^=]+[=])([^\&]+)([\&]+.+)?/', $request_query, $matches)) {
// If a match is found...
if (isset($_GET[$matches[1]])) {
// ... get rid of the original match...
unset($_GET[$matches[1]]);
// ... and replace it with a URL encoded version.
$_GET[$matches[1]] = urlencode($matches[2]);
}
}
As you have hinted in your question, the encoding of the URL you get is not as you want it: a & will mark a new argument for the current URL, not the one in the url parameter. If the URL were encoded correctly, the & would have been escaped as %26.
But, OK, given that you know for sure that everything following url= is not escaped and should be part of that parameter's value, you could do this:
$url = preg_replace("/^.*?([?&]url=(.*?))?$/i", "$2", $_SERVER["REQUEST_URI"]);
So if for example the current URL is:
http://www.myhost.com/page.php?a=1&URL=http://www.domain2.com?foo=bar&test=12
Then the returned value is:
http://www.domain2.com?foo=bar&test=12
See it running on eval.in.
My project Url is like this in yii:
http://localhost/php_pro_106/activate/Test?JJ=HEY+OOO
In my action :
public function actionTest()
{
print_r($_GET);
}
I am getting:
Array ( [JJ] => HEY OOO )
But I should get:
Array ( [JJ] => HEY+OOO )
What should I do for this,I need same Url ?
A + in a URL means a space. So you get the result you should have.
If you want to encode a + character in a URL, then you should represent it as %2B.
http://localhost/php_pro_106/activate/Test?JJ=HEY%2BOOO
If you are generating the URL programatically with PHP, you can use the urlencode function.
$keyname = "JJ";
$data = "HEY+OOO";
$url = "http://localhost/php_pro_106/activate/Test?" . urlencode($keyname) . "=" . urlencode($data);
You need to encode your URL (e.g. with urlencode in php). + needs to become %2B.
http://localhost/php_pro_106/activate/Test?JJ=HEY%2BOOO
"+" is one of reserved characters, according to RFC 2396.
If you want "+" in your example, you should use url encoding.
http://localhost/php_pro_106/activate/Test?JJ=HEY%2BOOO
If you produce URL from code, use urlencode() function to generate your URLS.
I've recently been developing a multi-lingual website. I've got a slight problem though.
Every time a button is clicked the language variable needs to change. i did this using the anchor tag (i.e English ).
The problem arises when other variables besides the language are added to the URL. I would like to redirect the page without getting rid of other variables and just changing the lang variable. So if the url contains "var1=value&var2=value&lang=En", I would like to alter the lang variable and keep the rest as they are. The lang variable can have 3 values: En, Az, Ru.
The method I tried so far:
function URI_ADD_AZ(){
$URI = $_SERVER['REQUEST_URI'];
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
unset($lang);
}
$new_URI = $URI . '?lang=Az';
return $new_URI;
}
Azeri
The problem:
Everytime the button is clicked the lang variable just gets added to the url not altered:
/?lang=Az?lang=Az?lang=Az?lang=Az
How can I make sure it does not keep getting repeated and avoid redirect loops?
The URI_ADD_AZ function posted in the question does not overwrite or remove preexisting occurrences of lang=* in the Query String, therefore duplication of "langs" in the URL. Also there is no handling of the requirement for ? or & depending on location of the key=value pair in the query string.
Here, to simplify things and limit the working string and therefore potential for introducing errors, the $_SERVER var QUERY_STRING is pulled, rather than the entire REQUEST_URI, and PHP_SELF is then prepended to the HREF value.
First thing here is to remove the lang=* including the & depending on it's position. A conditional reference is used to remove the trailing & only if the match is found at the beginning of the string.
Next $lang is retrieved from the $_GET var and validated. And if there's a valid $lang it is appended to the query string taking into consideration whether & is needed or not.
Finally, if not empty, the resulting query string is prepended with ? and returned.
function URI_ADD_AZ() {
$QS = preg_replace('/((^)|&)lang=[^&]*(?(2)&)?/', '', $_SERVER['QUERY_STRING']);
$lang = ( isset($_GET['lang']) && in_array($_GET['lang'], array('En','Az','Ru')) )? 'lang=' . $_GET['lang']: '';
if ( '' != $lang ) {
if ( '' == $QS ) { $QS = $lang; }
else { $QS .= "&$lang"; }
}
if ( '' != $QS ) {
return '?' . $QS;
}
}
Azeri
Simply provide Complete URL :-
Azeri
or, if you want to do it without reloading of page, you will have to use "jquery.history.js" file.
https://github.com/browserstate/history.js
History.pushState(null, 'title of my website', "?lang=<?php URI_ADD_AZ(); ?>);
Thanks
I am trying to create file links based a variable which has a "prefix" and an extension at the end.
Here's what I have:
$url = "http://www.example.com/mods/" . ereg("^[A-Za-z_\-]+$", $title) . ".php";
Example output of what I wish to have outputted (assuming $title = testing;):
http://www.example.com/mods/testing.php
What it currently outputs:
http://www.example.com/mods/.php
Thanks in advance!
Perhaps this is what you need:
$title = "testing";
if(preg_match("/^[A-Za-z_\-]+$/", $title, $match)){
$url = "http://www.example.com/mods/".$match[0].".php";
}
else{
// Think of something to do here...
}
Now $url is http://www.example.com/mods/testing.php.
Do you want to keep letters and remove all other chars in the URL?
In this case the following should work:
$title = ...
$fixedtitle=preg_replace("/[^A-Za-z_-]/", "", $title);
$url = "http://www.example.com/mods/".$fixedtitle.".php";
the inverted character class will remove everything you do not want.
OK first it's important for you to realize that ereg() is deprecated and will eventually not be available as a command for php, so to prevent an error down the road you should use preg_match instead.
Secondly, both ereg() and preg_match output the status of the match, not the match itself. So
ereg("^[A-Za-z_\-]+$", $title)
will output an integer equal to the length of the string in $title, 0 if there's no match and 1 if there's a match but you didn't pass it another variable to store the matches in.
I'm not sure why it's displaying
http://www.example.com/mods/.php
It should actually be outputting
http://www.example.com/mods/1.php
if everything was working correctly. So there is something going on there, and it's definitely not doing what you want it to. You need to pass another variable to the function that will store all the matches found. If the match is successful (which you can check using the return value of the function) then that variable will be an array of all matches.
Note that with preg_match by default only the first match will be returned. but it will still generate an array (which can be used to get isolated portions of the match) whereas preg_match_all will match multiple things.
See http://www.php.net/manual/en/function.preg-match.php for more details.
Your regex looks more or less correct
So the proper code should look something like:
$title = 'testing'; //making sure that $title is what we think it is
if (preg_match('/^[A-Za-z_\-]+$/',$title,$matches)) {
$url = "http://www.example.com/mods/" . $matches[0] . ".php";
} else {
//match failed, put error code in here
}
I am building a gallery in WordPress and I'm trying to grab a specific part of my URL to echo into the id of a div.
This is my URL:
http://www.url.com/gallery/truck-gallery-1
I want to isolate the id of the gallery which will always be a number(in this case its 1). Then I would like to have a way to print it somewhere, maybe in the form of a function.
You should better use $_SERVER['REQUEST_URI']. Since it is the last string in your URL, you can use the following function:
function getIdFromUrl($url) {
return str_replace('/', '', array_pop(explode('-', $url)));
}
#Kristian 's solution will only return numbers from 0-9, but this function will return the id with any length given, as long as your ID is separated with a - sign and the last element.
So, when you call
echo getIdFromUrl($_SERVER['REQUEST_URI']);
it will echo, in your case, 1.
If the ID will not always be the same number of digits (if you have any ID's greater than 9) then you'll need something robust like preg_match() or using string functions to trim off everything prior to the last "-" character. I would probably do:
<?php
$parts = parse_url($_SERVER['REQUEST_URI']);
if (preg_match("/truck-gallery-(\d+)/", $parts['path'], $match)) {
$id = $match[1];
} else {
// no ID found! Error handling or recovery here.
}
?>
Use the $_SERVER['REQUEST_URI'] variable to get the path (Note that this is not the same as the host variable, which returns something like http://www.yoursite.com).
Then break that up into a string and return the final character.
$path = $_SERVER['REQUEST_URI'];
$ID = $path[strlen($path)-1];
Of course you can do other types of string manipulation to get the final character of a string. But this works.