0

I have a domain name say for example : www.example.com I would like to get a dynamic data using PHP that is after this domain name. Example : www.example.com/samsung.

This samsung shall be anything that a user comes from. I want to get this samsung in my PHP. The major problem here is that when ever I open this www.example.com/samsung or www.example.com/vivo page the browser goes to vivo directory and throws a 404 error.

For now I have solved getting the data from this format : www.example.com/?samsung

<?php 
$key = array_search('', $_GET);
echo $key;
?>

But I want to get rid of the ? and have a pure www.example.com/samsung type.

Yaseen Hussain
  • 62
  • 1
  • 10

2 Answers2

1

This will give you last part of url

$url = $_SERVER['PHP_SELF'];
$url_array = explode('/',$url);
$result = end($url_array);
$Cleaned_url = str_replace("?", "", $result);
echo $Cleaned_url;

UPDATE : Creating Seo url :

.htaccess File

RewriteRule ^([a-zA-Z0-9_-]+)$ your_page.php?p=$1 [L,NC]

In php file when linking to url.

I save urls in database in news_url column

<a href="<?php echo $row["news_url"]; ?>" title="">post title</a>

This setup will give you www.example.com/samsung and solve your 404 notfound problem with right setup. Attetion : Creating seo urls with htaccess requires knowledge just copy paste wont work.

you can search on google : for how to create seo url with htaccess

This examples are working 100%.

  • 1
    Or just $result = end(explode('/', $_SERVER['PHP_SELF'])); – iJamesPHP2 Jan 11 '20 at 14:10
  • How to prevent the 404 error redirection at first place. – Yaseen Hussain Jan 11 '20 at 18:41
  • @YaseenHussain Ask another question for 404 with details will answer, Sorry, dont know what you are talking about –  Jan 11 '20 at 18:45
  • When you open example.com/samsung, it takes to a 404 error page because there is no file called samsung or vivo. I want the system to treat samsung as a variable rather than a page. (Just like how codeigniter considers a first variable as controller). – Yaseen Hussain Jan 11 '20 at 18:48
  • @YaseenHussain question and your example in question is about this : **Get Text after domain name from URL**. But anyway I gave that answer is well in my comment under your question. its about your php codes and htaccess file there is nothing I can do with that. Search for htaccess seo url with php on google –  Jan 11 '20 at 18:56
0

Use parse_url. See also this answer

Clemens Tolboom
  • 1,872
  • 18
  • 30