2

I receive URLs from a PHP form with the _POST method.

I am sure they are URLs because jquery validate plugin tests them before sending.

Then I process them in PHP.

However, I want to make sure that :

domain.com or domain.com/

end with a /.

But, I want to make sure that :

domain.com/page or domain.com/page/ or domain.com/dir/page/ or domain.com/page.html

end without a /.

I found : PHP: how to add trailing slash to absolute URL which was quite helpful.

I now use :

$rawarrival = $_POST["arrival"];

$url = parse_url($rawarrival);

if(!isset($url['path'])) $url['path'] = '/';
$arrival = $url['scheme']."://".$url['host'].$url['path'];

Nevertheless, I still can't make it to get a long URL (longer than just the domain) without a "/".

How should I twist that to make it work ?

Thank you.

Community
  • 1
  • 1
yoann44
  • 43
  • 1
  • 7
  • 1
    You are never sure the input parameters are valid until you don't check them on the server-side. It's simply possible to edit or disable javascript validating or just send custom request from another program. Always remember, that you must validate input parameters on server-side, too. – jjurm May 21 '13 at 18:39
  • Alright people. It seems like I got the answer from another forum : http://www.siteduzero.com/forum/sujet/differencier-des-urls-longues-et-domaines-en-php $url = parse_url($rawarrival); $url['path'] = (isset($url['path']) && $url['path'] != '/') ? rtrim($url['path'], '/') : '/'; $arrival = $url['scheme']."://".$url['host'].$url['path']; It works fine. Thanks. – yoann44 May 21 '13 at 18:41
  • Ok jjurm. Thanks for the advice. I am not a dev. This is going to be only an internal tool and there is not much to hack... but sure. – yoann44 May 21 '13 at 18:43

1 Answers1

1

Look at the last character?

if (substr($url["path"], -1, 1) === "/") {
    $url["path"] = substr($url["path"], 0, -1);
}

(untested)

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 1
    you can use `substr($url["path"], -1)` – jjurm May 21 '13 at 18:40
  • Ok. I prefer to keep that one : $url = parse_url($rawarrival); $url['path'] = (isset($url['path']) && $url['path'] != '/') ? rtrim($url['path'], '/') : '/'; $arrival = $url['scheme']."://".$url['host'].$url['path']; – yoann44 May 21 '13 at 19:14