I have several parameters which I pass to pages, such as unique id's from my database, error messages and form data. I would like to hide all of these parameters, to keep the url clean, except for the id. I tried looking this up for both PHP and JavaScript, but didn't find a solution, so I started fiddling around.
If I refresh the page when I have hidden the id, the route cannot find the id anymore, which generates a bunch of errors on the page. I want to hide all parameters except for the id so I don't get these errors. I managed to remove all parameters using this bit of Javascript:
let clean_url = window.location['href'].split('?')[0];
window.history.pushState(null, null, clean_url);
I tried to only show the id (which is always a positive integer) if it is set, but when changing my JS to the next block of code, it shows all parameters again.
let url_string = window.location['href'];
let url = new URL(url_string);
let id = url.searchParams.get("id");
if (typeof id !== 'undefined') {
let clean_url = url_string.split('?')[0].concat("?id={0}".format(id));
} else {
let clean_url = window.location['href'].split('?')[0];
}
window.history.pushState(null, null, clean_url);
Can anyone tell me what's the problem with my code, or if it is solvable in php? Thanks in advance.
EDIT: due to my lack of time, I won't be able to set my feedback messages to the $_SESSION. I have found a way to fix my javascript so all parameters except for the id
parameter are hidden:
let url_string = window.location['href'];
let short_url = window.location['href'].split('?')[0];
let url = new URL(url_string);
let id = url.searchParams.get("id");
if (id == null) {
window.history.pushState(null, null, short_url);
} else {
let clean_url = short_url.concat(`?id=${id}`);
window.history.pushState(null, null, clean_url);
}
Use the good medium for your data.
That's not always true but a good rule of thumb is that error messages goes in $_SESSION and forms data goes in $_POST.
For example, your form could look like this :
<form method="post" action="myurl1.php?id=123">
<!--you could also use a hidden field to send the id with post : <input type="hidden" name="id" />-->
<input name="test" />
</form>
And the processing of your form could give this :
if(empty($_POST[test])){
$_SESSION['error']='Empty test field';
}
header('Location: myurl2.php?id='.$_GET['id']); //or $_POST['id'] if you used a hidden field
Point is you decide how you send the data, and you should use the url only when it have value for your users.
(More on php sessions here)