How to get user name in URL?

Asked

Viewed 549 times

2

I’m creating a website and would like to make a system of profiles of the kind: meusite.com/NICKUSUARIO.

And I’d like to know how to get this nick in the URL and pass to the file profile.php for example.

I know how to put ?nick=nickuser, but would like to do in a more pleasant way for user typing having to put only meusite.com/nickusuario.

4 answers

3

Just use parse_url for interprets a URL and returns its components, and subsequently the function trim to remove the /

$parse = parse_url( 'http://www.meusite.com/NICKUSUARIO' );
echo trim( $parse['path'] , '/' );

The above code returns only NICKUSUARIO.


Update

The full URL you can use 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']

  • But as I get this value from the url that the user type in the browser, in your example you just broke a string/url q vc already have, in case I don’t know what the user type in the browser yet. And how I redirect to a php file that url ?

  • @Belong profile.php is a include or a redirect?

3

I believe you’re trying to create URL’s friendly, all right, buddy? For this, you can create a file .htaccess and configure it so that the text after the bar is interpreted as a parameter GET, then to receive it in PHP you normally use the $_GET (in the case $_GET['nick']), as if the url were indeed ?nick=nickuser.

Would look like this:

.htaccess

RewriteEngine On

#Reescrita de URL
#Na linha abaixo será definido que o parâmetro nick poderá receber letras e números
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?nick=$1

Already in the php file, you would receive normal:

PHP

<?php
echo $_GET['nick'];
?>

In case the url accessed is 'profile.php/testeName' or 'profile.php? nick=testeName' the result will be the display of:

testeNome
  • Vlw was just :) I used it like this: Rewritecond %{SCRIPT_FILENAME} ! -d Rewritecond %{SCRIPT_FILENAME} ! -f Rewriterule ([a-za-Z0-9. _-]+)/? $ profile.php? username=$1 [L,QSA,N

1

$parse = parse_url( 'http://www.meusite.com/NICKUSUARIO' );
$value = trim( $parse['path'] , '/' );

Its url would be fixed and the user would type only what comes after the /, ex: http://www.meusite.com/stack

your variable $value would have the value you need there is only you use it as you intend, ex: <?php header("location:user.php?nick=".$value);?>

0

To simplify, I believe that doing so already solves the case:

 $value = trim($_SERVER['PATH_INFO'],'/');

There are other ways...

a) Using parse_url():

    $parse = parse_url($_SERVER['REQUEST_URI']);
    $value = trim( $parse['path'] , '/' );

b) Using preg_replace():

$value = preg_replace('/(.+).com\/(.*)/','$2', $_SERVER['REQUEST_URI']);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.