If I have PHP script, how can I get the filename of the currently executed file without its extension?
Given the name of a script of the form "jquery.js.php", how can I extract just the "jquery.js" part?
Just use the PHP magic constant __FILE__ to get the current filename.
But it seems you want the part without .php. So...
basename(__FILE__, '.php');
A more generic file extension remover would look like this...
function chopExtension($filename) {
return pathinfo($filename, PATHINFO_FILENAME);
}
var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // string(15) "bob.i.have.dots"
Using standard string library functions is much quicker, as you'd expect.
function chopExtension($filename) {
return substr($filename, 0, strrpos($filename, '.'));
}
When you want your include to know what file it is in (ie. what script name was actually requested), use:
basename($_SERVER["SCRIPT_FILENAME"], '.php')
Because when you are writing to a file you usually know its name.
Edit: As noted by Alec Teal, if you use symlinks it will show the symlink name instead.
See http://php.net/manual/en/function.pathinfo.php
pathinfo(__FILE__, PATHINFO_FILENAME);
Here is the difference between basename(__FILE__, ".php") and basename($_SERVER['REQUEST_URI'], ".php").
basename(__FILE__, ".php") shows the name of the file where this code is included - It means that if you include this code in header.php and current page is index.php, it will return header not index.
basename($_SERVER["REQUEST_URI"], ".php") - If you use include this code in header.php and current page is index.php, it will return index not header.
This might help:
basename($_SERVER['PHP_SELF'])
it will work even if you are using include.
Here is a list what I've found recently searching an answer:
//self name with file extension
echo basename(__FILE__) . '<br>';
//self name without file extension
echo basename(__FILE__, '.php') . '<br>';
//self full url with file extension
echo __FILE__ . '<br>';
//parent file parent folder name
echo basename($_SERVER["REQUEST_URI"]) . '<br>';
//parent file parent folder name with //s
echo $_SERVER["REQUEST_URI"] . '<br>';
// parent file name without file extension
echo basename($_SERVER['PHP_SELF'], ".php") . '<br>';
// parent file name with file extension
echo basename($_SERVER['PHP_SELF']) . '<br>';
// parent file relative url with file etension
echo $_SERVER['PHP_SELF'] . '<br>';
// parent file name without file extension
echo basename($_SERVER["SCRIPT_FILENAME"], '.php') . '<br>';
// parent file name with file extension
echo basename($_SERVER["SCRIPT_FILENAME"]) . '<br>';
// parent file full url with file extension
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
//self name without file extension
echo pathinfo(__FILE__, PATHINFO_FILENAME) . '<br>';
//self file extension
echo pathinfo(__FILE__, PATHINFO_EXTENSION) . '<br>';
// parent file name with file extension
echo basename($_SERVER['SCRIPT_NAME']);
Don't forget to remove :)
<br>
alex's answer is correct but you could also do this without regular expressions like so:
str_replace(".php", "", basename($_SERVER["SCRIPT_NAME"]));
you can also use this:
echo $pageName = basename($_SERVER['SCRIPT_NAME']);
A more general way would be using pathinfo(). Since Version 5.2 it supports PATHINFO_FILENAME.
So
pathinfo(__FILE__,PATHINFO_FILENAME)
will also do what you need.
$argv[0]
I've found it much simpler to use $argv[0]. The name of the executing script is always the first element in the $argv array. Unlike all other methods suggested in other answers, this method does not require the use of basename() to remove the directory tree. For example:
echo __FILE__; returns something like /my/directory/path/my_script.php
echo $argv[0]; returns my_script.php\
Update:
#Martin points out that the behavior of $argv[0] changes when running CLI. The information page about $argv on php.net states,
The first argument $argv[0] is always the name that was used to run the script.
However, a comment from (at the time of this edit) six years ago states,
Sometimes $argv can be null, such as when "register-argc-argv" is set to false. In some cases I've found the variable is populated correctly when running "php-cli" instead of just "php" from the command line (or cron).
Please note that based on the grammar of the text, I expect the comment author meant to say the variable is populated incorrectly when running "php-cli." I could be putting words in the commenter's mouth, but it seems funny to say that in some cases the function occasionally behaves correctly. 😁
This works for me, even when run inside an included PHP file, and you want the filename of the current php file running:
$currentPage= $_SERVER["SCRIPT_NAME"];
$currentPage = substr($currentPage, 1);
echo $currentPage;
Result:
index.php
Try This
$current_file_name = $_SERVER['PHP_SELF'];
echo $current_file_name;
Although __FILE__ and $_SERVER are the best approaches but this can be an alternative in some cases:
get_included_files();
It contains the file path where you are calling it from and all other includes.
Example:
included File: config.php
<?php
$file_name_one = basename($_SERVER['SCRIPT_FILENAME'], '.php');
$file_name_two = basename(__FILE__, '.php');
?>
executed File: index.php
<?php
require('config.php');
print $file_name_one."<br>\n"; // Result: index
print $file_name_two."<br>\n"; // Result: config
?>
Try this
$file = basename($_SERVER['PATH_INFO']);//Filename requested
$filename = "jquery.js.php";
$ext = pathinfo($filename, PATHINFO_EXTENSION);//will output: php
$file_basename = pathinfo($filename, PATHINFO_FILENAME);//will output: jquery.js
__FILE__ use examples based on localhost server results:
echo __FILE__;
// C:\LocalServer\www\templates\page.php
echo strrchr( __FILE__ , '\\' );
// \page.php
echo substr( strrchr( __FILE__ , '\\' ), 1);
// page.php
echo basename(__FILE__, '.php');
// page
As some said basename($_SERVER["SCRIPT_FILENAME"], '.php') and basename( __FILE__, '.php') are good ways to test this.
To me using the second was the solution for some validation instructions I was making
Related
I have a directory - .../dir - that contains many files - john.txt, bob.txt, anne.pdf, tom.txt, etc...
I am given a file name, and need to retreive its extension. I have high confidence that for each filename (ie john, bob, etc), there is only one file - so there shouldn't be a case when there's both john.txt and john.pdf. But let's say in case that this happens, picking only the first file is ok. Let's say PDF since it's earlier alphabetically.
I only found scandir(), but it returns the whole directory. I could search the array it retrns, but I'm hoping, maybe there's something more efficient?
You should check pathinfo() function for getting an extension.
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
As for searching file, in particular, directory you can use a glob() function
$file = glob("../dir/jon.*");
You can try something like this:
$filename = 'ana';
$files = glob($filename . '.*');
if ($files && ($ext = pathinfo($files[0], PATHINFO_EXTENSION))) {
echo $ext;
}
I searched everywhere for this problem and can't find the solution. I have this:
<?php
$file_name = $_GET['name'];
$file_delete = '../u/' . $file_name;
unlink($file_delete);
//header("location: $file_delete");
?>
unlink returns the error: No such file or directory, but if I try header("location: $file_delete"); it opens the file (picture in this case).
Where may I be wrong?
Get Absolute path first for the file to be deleted and check file exist before delete:
$file_name = $_GET['name'];
$base_dir = realpath($_SERVER["DOCUMENT_ROOT"]);
$file_delete = "$base_dir/your_inner_directories_path/$file_name";
if (file_exists($file_delete)) {unlink($file_delete);}
After some research, unlink() doesn't seem to allow you to use relative paths (with "../").
Here's an alternative:
<?php
$file_name = $_GET['name'];
$file_delete = dirname(__FILE__, 2) . '\\u\\' . $file_name;
unlink($file_delete);
?>
$file_delete here is the absolute path to the file you want to delete.
Reminder: / is used for Unix systems, \ for Windows.
PHP doc:
- http://php.net/manual/en/function.unlink.php
- http://php.net/manual/en/function.dirname.php
I also had same issue with my code. What I did to solve the issue is:
First execute:
var_dump($image_variable) // var_dump($file_delete) in your case.
It outputs: string(23)(my-image-path )
When I started counting string I just found 22 characters. I wondered where is the 23rd?
I checked and count carefully, at the end I found that there is space at the end of my image path. So I used php trim() function to remove white spaces. Like,
$trimed_path = trim($image_variable) // trim($file_delete) in your case.
Second: Now execute,
unlink($trimed_path).
OR CHECK LIKE
if(unlink($trimed_path))
{
echo "File Deleted";
}
else
{
echo "Error Deleting File";
}
Took me a couple of hours to figure out. As mentioned above unlink() is picky when it comes to paths.
Solution is:
1st) Define the path (this is how Wordpress does it btw):
define( 'ROOTPATH', dirname(dirname(__FILE__)) . '/' );
2) Do:
unlink(ROOTPATH.'public_html/file.jpg');
I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.
inside ajax folder, there are files:
json.php, load.php, script.php
main.php
<?php
$dir = dir("ajax");
while (($file = $dir->read()) !== false)
{
echo "filename: " . $file . "<br />";
}
$dir->close();
It show:
filename: .
filename: ..
filename: json.php
filename: load.php
filename: script.php
Question:
In the result, what does the first two items mean? . .. ?
Those are the current (.) and parent (..) directories.
You can get rid of them in following way:
$result = array_diff($result, array('..', '.'));
. and .. are "directories" which equate to the current directory, and parent directory, respectively.
for example, if you are in the ajax folder, json.php can also be accessed with ./json.php.
on the other hand, ../json.php will look for the file in the parent folder (same directory as the ajax folder).
. is current folder.
.. is parent folder. Any folders on window and linux have two this.
If you want to read some type of file, you can use glob function of php.
$files = glob($dirpath.'/*.php');
Single dot: . This represents current directory.
Double dot: .. This represents parent directory.
My current directory structure is as follows:
C:\xampp\htdocs\PHP_Upload_Image_MKDIR
In other words, the following directories do NOT exist at all.
C:\xampp\htdocs\PHP_Upload_Image_MKDIR\uploaded
C:\xampp\htdocs\PHP_Upload_Image_MKDIR\uploaded\s002
The problem is that when I run the following script, the function is_dir always return TRUE.
Based on the manual, http://us2.php.net/manual/en/function.is-dir.php
is_dir: Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Do I miss something here?
Thank you
$userID = 's002';
$uploadFolder = '/PHP_Upload_Image_MKDIR/uploaded/';
$userDir = $uploadFolder . $userID;
echo '<br/>$userDir: ' . $userDir . '<br/>';
if ( is_dir ($userDir))
{
echo "dir exists"; // always hit here!!!
}
else
{
echo "dir doesn't exist";
}
mkdir($userDir, 0700);
C:\xampp\htdocs\PHP_Upload_Image_MKDIR>dir /ah
Volume in drive C is System
Volume Serial Number is 30B8-2BB2
Directory of C:\xampp\htdocs\PHP_Upload_Image_MKDIR
File Not Found
C:\xampp\htdocs\PHP_Upload_Image_MKDIR>
//////////////////////////////////////////////////////////
Based on Artefacto's comments:
Here is the output of C:\PHP_Upload_Image_MKDIR\uploaded\s005
echo '<br/>' . realpath($userDir) . '<br/>';
Thank you for the solutions.
Best wishes
Also, it seems as if the dir you are checking is PHP_Uploaded_Image_MKDIR/uploaded/s002, which is an absolute path starting from the root filesystem.
Try prepending C:\xampp\htdocs\ to this and see if it works then. Also, check to see if the folder exists at the root of the volume.
Try file_exists() instead.
http://php.net/manual/en/function.file-exists.php
If you've run that script more than once, then is_dir($userDir) will return true because of this line (the last one) in your script:
mkdir($userDir, 0700);
You can use rmdir() or some other method to delete it.
To test is_dir(), try a directory name that has never been used / created. Something like the following should return false, when it does, you know that is_dir() works:
if ( is_dir ("/PHP_Upload_Image_MKDIR/uploaded/lkjlkjlkjkl"))