Keep a GET variable in URL - php

I have a bit of an odd question, I'm sure most of you realise that these sorts of questions arise out of certain situations that a developer has no control over!
I would like to work out how to keep a querystring parameter in the URL at all times. If the parameter is not set, I'd like a default to be appended to the URL ?param=something
I asked a previous question relating to this and have been able to use htaccess to add a default query - but this only works fir the initial request whereas I need to ensure it is always present in the address.
I am thinking of using a cookie - set with PHP and then queried with .htaccess.
So, I am asking if this is possible and if there is a better way of doing this?

Without changing all the URLs I can't see this being possible and as discussed it is a very hacky way to do it.
I would suggest you give them a "special" button that they use for copying a link. Make them use this button to copy the link instead of the URL. You can then control the data properly without hacking the website.
Edit: You "could" add some JQuery in to append ALL links with your param. Have you thought about this?
$(document).ready(function() {
$('a[href]').each(function() {
this.href = this.href + '?something=<?php echo $_SESSION["myparam"]; ?>'
});
});
You could get the param from the initial page load / session but this would require your users to have JS enabled (Which most people do now).
p.s Untested semi-pseudo code. I can test it properly if you decide to go down this route.

$_GET and $_POST superglobal variable those are not meant to used like this. And I don't know why is it required but anyway you can get the required functionality using Session or Cookies. What you are trying to do is not practical. Industry standard is to use session and cookie. Try them out I'm sure it will helps you out for sure. If you have any issues let me know.

If you are using Apache 2, then you could add a rewrite rule that appends a GET parameter to each request that doesn't have "param=..." in its URL. Something like (untested):
RewriteCond %{QUERY_STRING} !(\A|&)param=
RewriteRule (.*) $1?param=defaultvalue [QSA]
See modrewrite 's doc for details. You can add another RewriteCond on %{REQUEST_URI} if you want to limit this to some URL.

I only learned php about 3 months ago so I hope I am not leading you down a path, this is what I would try.
Edit: It has been about 5 months now since I learned php. My Previous version before this edit only "built" the get to append (and it probably didn't work).
if (!isset($_GET['param'])) {$_GET['param'] = 'something';}
$var = '';
while ($other_gets = $_GET)
{
foreach ($other_gets as $key=>$value)
{
if ($key = 'something') {}//do nothing we want the other gets
else {$var .= '&'.$key.'='.$value;}
}
}
$get = '?'.$user_param.$other_gets;
preg_replace your extensions
$string = 'your webpage before output';
$patterns = array();
$patterns[0] = '/.html/';
$patterns[1] = '/.php/';
$patterns[2] = '/yoursite.com /';//with space
$replacements = array();
$replacements[0] = '.html'.$get;
$replacements[1] = '.php'.$get;
$replacements[2] = 'yoursite.com/index.php'.$get;
Then print your string
echo preg_replace($patterns, $replacements, $string);

Related

Passing variable through subdomain wildcard redirect?

I am working on a new script that basically instead when somebody searches for something on my website how it normally goes to here:
http://domain.com/index.php?q=apples
to
http://apples.domain.com
I have made this work perfectly in PHP as well as htaccess but the problem I am having is using the original keyword afterwards on the new subdomain page.
Right now I can use parse_url to get the keyword out of the url but my script also filters out potential problems like:
public function sanitise($v, $separator = '-')
{
return trim(
preg_replace('#[^\w\-]+#', $separator, $v),
$separator
);
}
So if somebody searches for netbook v1.2
The new subdomain would be:
http://netbook-v1-2.domain.com
Now I can take the keyword out but it's with the dashes and not original. I am looking for a way to send over the original keyword with the 301 redirect as well.
Thanks!
You can either just replace the hyphen with spaces when they visit the new subdomain or, since you're on the same top-level domain, you can just cookie the keyword when redirecting them:
setcookie('clientkeyword', 'netbook-v1-2.domain.com:netbook v1.2', 0, '/', '.domain.com');
Look at this answer: https://stackoverflow.com/a/358334/992437
And see if you can use the POST or GET data that's already there. If so, that might be your best bet.

Change URL using PHP

e.g. i have page with url http://mysite.com?page=3&var=10 also there is form on page.
When form submitted there some actions in php but i need to remove this ?page=3&var=10 after form was submitted somehow is there way compatible with all browsers trough PHP without mod_rewrite?
This is an old topic, but just in case anyone else is searching for this in the future, you can use the javascript replaceState to change the history and browser bar label. A simple php function to do this:
function set_url( $url )
{
echo("<script>history.replaceState({},'','$url');</script>");
}
Then would simply call this function with the desired url (presumably dropping the post variables):
set_url("http://example.com");
A page reload or a back after calling another page will now have the new url location in the history.
I think that using POST may be a more elegant solution, but if you must use GET this is a work around.
If you're using action=index.php, then all values will be posted to index php, ?page=3&var=10 will be automatically removed.
If you want to post to the same page you can either use 'action=index.php?page=3&var=10' or action=<?php echo $_SERVER['PHP_SELF'] ?>
You can check at the beginning of the page if something submitted and then redirect to whatever you want with header('Location: http://www.example.com/'); More about header function http://php.net/manual/en/function.header.php
Yeah, the solution is quite simple (even if not really SEO friendly):
<?php
header("Location: http://mysite.com")
?>
just for information...why do you need it?
use parse_str to get the query string as an associative array that is easy to modify. Then use http_build_query to convert the associative array into a query string.
$queryString = $s['QUERY_STRING'];
$params = array();
parse_str($queryString, $params);
//change $params as needed
$queryString = http_build_query($params);
if ($queryString) {
$queryString = '?'.$queryString;
}
return preg_replace("/\\?.*/s","",$s['REQUEST_URI']).$queryString;
preg_replace("/\\?.*/s","",$s['REQUEST_URI']) removes the original query string allowing you to replace it.
Does this work for you?
header('Location:/');
mod_rewrite cannot affect what's displayed in the user's browser address bar, UNLESS the rewrite does an externally visible redirect. Otherwise it only rewriting things within the webserver, and that's invisible to the user.
If you want to affect the user's address bar, you'll have to do a redirect via header('Location: ...') after the form's finished processing.

Encrypting or Hiding Strings sent in the url

I am trying to send a Topic name in the URL like,
<a href="hello?TopicN=blahblahblha">
and then output the topic name as the Forum topic title. But the problem is the user can just change the name if they want which doesnt do any harm since I dont really do anything with teh name but I was wondering is there a way to encrypt or swap the letters so its not so obvious what the topicN is ?
I also tried md5 encryption but, md5 is only 1 way so that doesnt help. Could use sessions, not sure since i store user login details in sessions,
any ideas and examples would be helpful,
Thank you
MD5 is hashing, not encryption, so that won't help.
Consider passing an identifier to a row in your database so that you could lookup the title.
<a href="hello.php?TopicN=1234">
Trusting the client is a big no-no for many reasons, and this is one of them.
Using the session to store this information would work, but it seems inappropriate given that (I suspect) TopicN could (or, does) change frequently.
Good luck!
Ian
You could use base64_encode and base64_decode, it makes it less obvious.
base64_encode(blahblahblha) = YmxhaGJsYWhibGhh
base64_decode(YmxhaGJsYWhibGhh) = blahblahblha
I'd question the purpose or benefit of this requirement though.
I would advise you to do the reverse even.
Make it more search engine and user friendly, like so: forum/thread/blabla
If you are using Apache search for Rewrite Engine
Try this:
File: .htaccess
RewriteEngine On
RewriteRule url/(.*) url_parser.php?url=$1 [L,QSA]
File with the links:
Link
File: url_parser.php
<?php
$encodedURL = filter_input(INPUT_GET, 'url', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$unencodedURL = base64_decode($encodedURL);
$urlParts = parse_url($unencodedURL);
$newURL = $urlParts['path'];
// See if there are any extra _GET parameters on this URL:
// Add encoded _GET params:
$newURL .= '?' . $urlParts['query'];
// Add extra _GET parameters:
$newURL .= '&' . $_SERVER['QUERY_STRING'];
// Add any passed #
$newURL .= '#' . $urlParts['fragment'];
// Redirect to the new URL:
header('Location: ' . $newURL);
// If you want to hide the URL completely, do this:
readfile($newURL);

Doing a URL re-write while using PHP GET method

When I click on a comment section for a given entry on a site I have, the URL looks like this:
http://www...com/.../comments/index.php?submission=Portugal%20Crushes%20North%20Korea&submissionid=62&url=nytimes.com/2010/06/22/sports/soccer/22portugalgame.html?hpw&countcomments=3&submittor=johnjohn12&submissiondate=2010-06-21%2019:00:07&dispurl=nytimes.com
I want to make it look like this URL:
http://www...com/.../comments/Portugal-Crushes-North-Korea-62
I understand that this involves adding rules to the .htaccess file. I have two questions:
Since I am using the GET method in PHP, the ugly URL has a bunch of variables appended to it. I don't want all of these variables to appear in the clean URL. Is it possible to only include a few of the variables in the clean URL but still have a rule directing it to an ugly URL with all of the variables?
Once I have the .htaccess rules written, do I go back and change the links in the source code to direct to the clean URLs? If so, how do I do this using the GET method when the clean URL does not have all of the variables that I want to pass along?
Thanks in advance,
John
I'm not sure why you need all that data in the URL. You should be storing things like the submission title, its date and author in a database and then refer to it with an ID. That way, your URLs will be shorter and prettier:
http://www.example.org/article.php?id=1
http://www.example.org/article/1/
You can accomplish this with a simple RewriteRule in your .htaccess file, like so:
RewriteEngine On
RewriteRule ^articles/([0-9]+)/ article.php?id=$1
No, you can not leave variables out and expect them to be passed anyway. If you do this, the information is no longer in the URL, so you don't have a way to get it.
You can use post instead of get if you want to pass variables without them showing up in the URL.
I join the word of Sjoerd, but there are a lot of ways how you can rewrite your url like you want to!
Apache and (IIS too) supports url-s like this one: http://example.com/index.php/my-rewritten-url_62
function URISegment($segment)
{
$uri_array = explode('/',$_SERVER['REQUEST_URI']);
$uri_count = count($uri_array);
$returning_uri = array();
for($i = 0;$i<$uri_count;$i++)
{
if(empty($uri_array[$i]) || $uri_array[$i] == "index.php")
unset($uri_array[$i]);
else
array_push($returning_uri,$uri_array[$i]);
}
if($segment < count($returning_uri))
return $returning_uri[$segment];
else
return false;
}
This works, but you need to define the base url too, and this needs to be called at the beginning of the file, and implemented at every image, script, etc. call.
function BaseURL()
{
if(isset($_SERVER['HTTP_HOST']))
{
$base = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
$base .= '://'. $_SERVER['HTTP_HOST'];
$base .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
}
else
{
$base = 'http://localhost/';
}
return $base;
}
After this you can use instead of this:
// http://example.com/?MyKey=Some-data
$MyKey = $_GET['MyKey']; //which is the first item
echo $MyKey;
// results: Some-data
This:
// http://example.com/?MyKey=Some-data
$MyKey = URISegment(0);
echo $MyKey;
// results: Some-data
You've got the same result by each one.
PS:
I like this solution because I can mix url types as I need them like:
example.com/index.php/index/evaled-article?some=db-stored&code=snipplet
And of course you can rewrite your url like FRKT said :)
And of course, if you want to hide the index.php you need to use mod_rewrite, because there's no way

Editing and creating things with address bar code?

How do I make it so that I can make a thing at the end of the address where the .php is and then tell it to do certain things. For example pull up a page like this:
sampardee.com/index.php?page=whatever
Help?
Anything else I could do with this?
This is generally achieved with the global php array $_GET. You can use it as an associative array to 'get' whatever variable you name in the url. For example your url above:
//this gives the $page variable the value 'whatever'
$page = $_GET['page'];
if($page == 'whatever'){
//do whatever
}
elseif($page == 'somethingelse'){
//do something else
}
Check out the php documentation for more information:
$_GET documentation
and there's a tutorial here:
Tutorial using QUERY_STRING and _GET
A small improvement over Brett's code:
if (array_key_exists('page', $_GET) === false)
{
$_GET['page'] = 'defaultPage';
}
$page = $_GET['page'];
// ... Brett Bender's code here
$_GET is usually used if you are sending the information to another page using the URL.
$_POST is usually used if you are sending the information from a form.
If you ever need to write your code so that it can accept information sent using both methods, you can use $_REQUEST. Make sure you check what information is being sent though, especially if you are using it with a database.
From your question it looks like you are using this to display different content on the page?
Perhaps you want to use something like a switch to allow only certain page names to be used?
i.e.
$pageName=$_REQUEST['page'];
switch($pageName){
case 'home':$include='home.php';break;
case 'about':$include='about.php';break;
case default:$include='error.php';break;
}
include($include);
This is a really simplified example, but unless the $page variable is either home or about, the website will display an error page.
Hope it helps!
I'm not quite sure what you're asking, but I think you're asking how to use GET requests.
Make GET requests against any PHP page as follows:
www.mysite.com/page.php?key1=value1&key2=value2
Now, from within PHP, you'll be able to see key1 -> value1, key2 -> value2.
Access the GET hash from within PHP as follows:
$myVal1 = $_GET['key1'] #resolves to "value1"
$myVal2 = $_GET['key2'] #resolves to "value2"
From here, play with your GET variables as you see fit.
The system of adding page parameters to a URL is know as HTTP GET (as distinct from HTTP POST, and some others less commonly used).
Take a look at this W3 schools page about GET in PHP and ahve a play about in getting parameters and using them in your PHP code.
Have fun!

Categories