I have a page working as I need it to, with the last /arist-name/ parsing into the correct variable, but the client is adding /artist-name/?google-tracking=1234fad to their links, which is breaking it.
http://www.odonwagnergallery.com/artist/pierre-coupey/ WORKS
http://www.odonwagnergallery.com/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID] DOES NOT WORK
$expl = explode("/",$_SERVER["REQUEST_URI"]);
$ArtistURL = $expl[count($expl)-1];
$ArtistURL = preg_replace('/[^a-z,-.]/', '', $ArtistURL);
Please help, I have been searching for a solution. Thanks so much!
PHP has a function called parse_url which should clean up the request uri for you before you try to use it.
parse_url
Parse a URL and return its components
http://php.net/parse_url
Example:
// This
$url_array = parse_url('/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID]');
print_r($url_array);
// Outputs this
Array
(
[path] => /artist/pierre-coupey/
[query] => mc_cid=b7e918fce5&mc_eid=[UNIQID]
)
Here is a demo: https://eval.in/873699
Then you can use the path piece to perform your existing logic.
If all your URLs are http://DOMAIN/artist/SOMEARTIST/
you could do:
$ArtistURL = preg_replace('/.*\/artist\/(.*)\/.*/','$1',"http://www.odonwagnergallery.com/artist/pierre-coupey/oij");
It would work in this context. Specify other possible scenarios if there are others. But #neuromatter answer is more generic, +1.
if you simply want to remove any and all query parameters, this single line would suffice:
$url=explode("?",$url)[0];
this would turn
http://www.odonwagnergallery.com/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID]&anything_else=whatever
into
http://www.odonwagnergallery.com/artist/pierre-coupey/
but if you want to specifically remove any mc_cid and mc_eid parameters, but otherwise keep the url intact:
$url=explode("?",$url);
if(count($url)===2){
parse_str($url[1],$tmp);
unset($tmp['mc_cid']);
unset($tmp['mc_eid']);
$url=$url[0].(empty($tmp)? '':('?'.http_build_query($tmp)));
}else if(count($url)===1){
$url=$url[0];
}else{
throw new \LogicException('malformed url!');
}
this would turn
http://www.odonwagnergallery.com/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID]&anything_else=whatever
into
http://www.odonwagnergallery.com/artist/pierre-coupey/?anything_else=whatever
Related
How can I take out the part of the url after the view name
Example:
The URL:
http://localhost/winner/container.php?fun=page&view=eims
Extraction
eims
This is called a GET parameter. You can get it by using
<?php
$view = $_GET['view'];
If this is for a URL which is not part of your website (e.g. Not your domain), but you wish to parse it. Something like this will work
$url = "http://example.com/index.php?foo=bar&acme=baz&view=asdf";
$params = explode('?', $url)[1]; // This gets the text AFTER the ? Note: If using PHP 5.3 or less, this may not work. You would then need to split it into two lines with the [1] happening on $params.
$pairs = explode('&', $params);
foreach($pairs as $p => $pair) {
list($keys[$p], $values[$p]) = explode('=', $pair);
$splits[$keys[$p]] = $values[$p];
}
echo $splits['view'];
<?php echo $_GET['view']; ?> //eims
If that's current URL, the simple and rock solid approach is to use the filter functions:
filter_input(INPUT_GET, 'view')
Otherwise, you can use parse_url() with PHP_URL_QUERY as second argument. The resulting string can be split with e.g. parse_str().
Are sure you are writing this "echo $_GET['view'];" in the container.php file?
Maybe write why do you need that "view".
Cut some word from php available ?
First access to page for example
www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success
From my php code, i will get $curreny_link_redirect = test.php?ABD_07,_oU_876.00/8999&message=success
And i want to get $curreny_link_redirect_new = test.php?ABD_07,_oU_876.00/8999
( Cut &message=success )
How can i do ?
<?PHP
$current_link = "$_SERVER[REQUEST_URI]";
$curreny_link_redirect = substr($current_link,1);
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
echo $curreny_link_redirect_new;
?>
Your str_replace call is inverse of what it should be. What you want to replace should be the first parameter, not the second.
//Wrong
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
//Right
$curreny_link_redirect_new = str_replace('&message=success','', $curreny_link_redirect);
While simple way to do this is to use regex (or even static with str_replace()), I recommend to use built-in functions for url handling. This may be useful when working with complex parameters or multiple parameters:
$data = 'www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success';
$url = parse_url($data);
parse_str($url['query'], $url['query']);
//now, do something with parameters:
unset($url['query']['message']);
$url['query'] = http_build_query($url['query']);
$url = http_build_url($url);
-please, note, that http_build_url() is a PECL function (pecl_http to be precise). The way above may look more complex, but it has benefits - first, as I've already mentioned, this will be easy to modify for working with complex parameters or multiple parameters. Second, it will produce valid url - i.e. encode such things as slashes, spaces, e t.c. - in result. Thus, result will always be correct url.
Do like this
<?php
$str = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $str = array_shift(explode('&',$str));
Try this:
$current_link_path = substr($_SERVER['PHP_SELF'], 1);
$params = $_GET;
if ($params['message'] == 'success') {
unset($params['message']);
}
$current_link_redirect = $current_link_path . '?' . http_build_query($params);
Maybe not an answer, but a disclaimer for future visitors:
1) I would strongly recommend the function: http://pl1.php.net/parse_url.
And in that case:
$current_link = "$_SERVER[REQUEST_URI]";
$arguments = explode('&', parse_url($current_link, PHP_URL_QUERY));
print_r($arguments);
2) To build new url, use http://pl1.php.net/manual/en/function.http-build-url.php. This is the best, future modifications ready solution I think.
In that case this solution is a little overkill, but these functions are really great, and worth to introduce here.
Best regards
I have some images in my database
http://***.com/2013/12/reign-death-midseason-finale-featured.jpg?w=500
http://***.com/reign-death-midseason-finale-featured.png?w=120
http://***.com/2013/12/finale-featured.jpg?w=50
http://***.com/2013/finale-featured.jpg?w=50&h=50
http://***.com/2013/12/reign-death-midseason-finale-featured.jpg
I want to change the images with w= to same width and ?w=50&h=50 also. all with W should come as w=600 and w=600&h=600. This is what I was trying str_replace but there is a problem with this that w= always change and in some cases there is height also and it also need to be changed, i have search net and found that it can be done with preg_replace don't know how.
EDIT
Answer needed is if(hight is null) result is case 1 w=600 and if h is not null case 2 w=600&h=600
please help
Sorry it took me a while, I was kinda busy
try the following
$pattern = '~(?<=\W(w|h)\=)(\d+?)(?=\D|$)~';
$replace = '600';
$subject = 'http://localhost/2013/finale-featured.jpg?w=50&h=50';
echo preg_replace($pattern,$replace,$subject);
try this with many variations of your URIs
PS: this kind of advanced string finding/replacing is the domain of regular expressions. If you find you need to do a lot of this, consider starting to learn about them, it's a whole language in itself. I used some assertions (lookahead (?<=) and lookbehind (?=)) for this particular solution
If you want to avoid using a regular expression you can parse the URL and query string into arrays, which would make evaluating the query string values much easier.
$url = 'http://***.com/2013/finale-featured.jpg?w=50&h=50';
$urlArray = parse_url($url);
parse_str($urlArray['query'], $queryStringArray);
if ( !isset($queryStringArray['h']) || $queryStringArray['h'] === null ) {
} else if ( ... ) {
} else if ( ... ) {
}
Can anyone suggest a method in php or a function for parsingSEO friendly urls that doesn't involve htaccess or mod_rewrite? Examples would be awesome.
http://url.org/file.php/test/test2#3
This returns: Array ( scheme] => http [host] => url.org [path] => /file.php/test/test2 [fragment] => 3 ) /file.php/test/test2
How would I separate out the /file.php/test/test2 section? I guess test and test2 would be arguments.
EDIT:
#Martijn - I did figure out what your suggested before getting the notification about your answer. Thanks btw. Is this considered an ok method?
$url = 'http://url.org/file.php/arg1/arg2#3';
$test = parse_url($url);
echo "host: $test[host] <br>";
echo "path: $test[path] <br>";
echo "frag: $test[fragment] <br>";
$path = explode("/", trim($test[path]));
echo "1: $path[1] <br>";
echo "2: $path[2] <br>";
echo "3: $path[3] <br>";
echo "4: $path[4] <br>";
You can use explode to get the parts from your array:
$path = trim($array['path'], "/"); // trim the path of slashes
$path = explode("/", $path);
unset($path[0]); // the first one is the file, the others are sections of the url
If you really want to make it zerobased again, add this as last line:
$patch = array_values($path);
In response to your edit:
You want to make this as flexible as you can, so no fixed coding based on a max of 5 items. Although you probably will never exceed that, just don't pin yourself to it, just overhead you dont need.
If you have a pages system like this:
id parent name url
1 -1 Foo foo
2 1 Bar, child of Foo bar-child-of-foo
Make a recursive function. Pass the array to a function which takes the first section to find a root item
SELECT * FROM pages WHERE parent=-1 AND url=$path[0]
That query will return an id, use that in the parent column with the next value of the array. Unset each found value of the $path array. In the end, you will have an array with the remaining parts.
To sketch an example:
function GetFullPath(&$path, $parent=-1){
$path = "/"; // start with a slash
// Make the query for childs of this item
$result = mysqli_query($conn, "SELECT * FROM pages WHERE parent=".$parent." AND url=".current($path)." LIMIT 1");
// If any rows exists, append more of the url via recursiveness:
if($result->num_rows!==0){
// Remove the first part so if we go one deeper we start with the next value
$path = array_slice($patch,1); // remove first value
$fetch = $result->fetch_assoc();
// Use the fetched value to go deeper, find a child with the current item as parent
$path.= GetFullPath($path, $fetch['parent']);
}
// Return the result. if nothing is found at all, the result will be "/", probs home
return $path;
}
echo GetFullPath($path); // I pass it by reference, any alterations in the function happen to the variable outside the scope aswell
This is a draft, I did not test this, but you get the idea im trying to sketch. You can use the same method to get the ID of the page you are at. Just keep passing the variable back up again c
One of these days im getting the hang of recursiveness ^^.
Edit again: Oops, that turned out to be quite some code.
I want remove a parameter from a URL:
$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';
I am trying to get this result:
https://stackoverflow.com/?name=alaa&
https://stackoverflow.com/?&star=5
I am trying to do it using preg_replace, but I've no idea how it can be done.
$link = preg_replace('~(\?|&)counter=[^&]*~','$1',$link);
Relying on regular expressions can screw things up sometimes..
You should use, the parse_url() function which breaks up the entire URL and presents it to you as an associative array.
Once you have that array, you can edit it as you wish and remove parameters.
Once, completed, use the http_build_url() function to rebuild the URL with the changes made.
Check the docs here..
Parse_Url Http_build_query()
EDIT
Whoops, forgot to mention. After you get the parameter string, youll obviously need to separate the parameters as individual ones. For this you can supply the string as input to the parse_str() function.
You can even use explode() with & as the delimeter to get this done.
I would recommend using a combination of parse_url() and http_build_query().
Handle it correctly! !
remove_query('http://example.com/?a=valueWith**&**inside&b=value');
Code:
function remove_query($url, $which_argument=false){
return preg_replace( '/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);
}
A code example how I would grab a requested URL and remove a parameter called "name", then reload the page:
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //complete url
$parts = parse_url($url);
parse_str($parts['query'], $query); //grab the query part
unset($query['name']); //remove a parameter from query
$dest_query = http_build_query($query); //rebuild new query
$dest_url=(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http").'://'.$parts['path'].'?'.$dest_query; //add query to host
header("Location: ".$dest_url); //reload page
parse_url() and parse_str() are buggy. Regular expressions can work but have the tendency to break. If you want to correctly deconstruct, make changes, and then reconstruct a URL, you should look at:
http://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
ExtractURL() generates parse_url()-like output but does much more (and does it right). CondenseURL() takes an array from ExtractURL() and constructs a new URL from the information. Both functions are in the 'support/http.php' file.
Years later...
$_GET can be manipulated like any other array in PHP. Simply unset the key and create the http query using the http_build_query function.
// Populate _GET with sample data...
$_GET = array(
'value_a' => "A",
'key_to_remove' => "Don't delete me bro!",
'value_b' => "B"
);
// Should output everything...
// "value_a=A&key_to_remove=Don%27t+delete+me+bro%21&value_b=B"
echo "\n".http_build_query( $_GET );
// Remove the key from _GET...
unset( $_GET[ 'key_to_remove' ] );
// Should output everything else...
// "value_a=A&value_b=B"
echo "\n".http_build_query( $_GET );
This is working for me:
function removeParameterFromUrl($url, $key)
{
$parsed = parse_url($url);
$path = $parsed['path'];
unset($_GET[$key]);
if(!empty(http_build_query($_GET))){
return $path .'?'. http_build_query($_GET);
} else return $path;
}