Sam
Sam

Reputation: 3

How do I use PHP to grab the name of the file?

what I want to do is PHP to look at the url and just grab the name of the file, without me needing to enter a path or anything (which would be dynamic anyway). E.G.

http://google.com/info/hello.php, I want to get the 'hello' bit.

Help?

Thanks.

Upvotes: 0

Views: 119

Answers (6)

Mikulas Dite
Mikulas Dite

Reputation: 7941

This is safe way to easily grab the filename without extension

$info = pathinfo(__FILE__);
$filename = $info['filename'];

Upvotes: 1

murze
murze

Reputation: 4103

You could to this with parse_url combined with pathinfo

Here's an example

$parseResult = parse_url('http://google.com/info/hello.php');
$result = pathinfo($parseResult['path'], PATHINFO_FILENAME);

$result will contain "hello"

More info on the functions can be found here: parse_url pathinfo

Upvotes: 0

acm
acm

Reputation: 6637

http://php.net/manual/en/function.basename.php

$file = basename(__FILE__); // hello.php
$file = explode('.',$file); // array
unset($file[count($file)-1]); // unset array key that has file extension
$file = implode('.',$file); // implode the pieces back together
echo $file; // hello

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382606

You need basename and explode to get name without extension:

$name = basename($_SERVER['REQUEST_URI']);
$name_array = explode('.', $name);
echo $name_array[0];

Upvotes: 1

Gumbo
Gumbo

Reputation: 655129

$_SERVER['REQUEST_URI'] contains the requested URI path and query. You can then use parse_url to get the path and basename to get just the file name:

basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php')

Upvotes: 0

Anemoia
Anemoia

Reputation: 8116

$filename = __FILE__;

Now you can split this on the dot, for example

$filenameChunks = split(".", $filename);

$nameOfFileWithoutDotPHP = $filenameChunks[0];

Upvotes: 1

Related Questions