My index.php is stored in ***/101/index.php. What I want to do is to extract the parent folder name and use it as a $var.
I tried the $var = getcwd() . "\n"; , but it gets the whole structure, etc: c:/wamp/www/HC/101. Is it even possible to get out only the last folder in the line?
Try this:
$dirname = __DIR__;
basename($dirname); //Returns the current file directory name
In your example c:/wamp/www/HC/101 should return 101
$directory = str_replace(dirname(__DIR__), null, __DIR__):
Or basename(__DIR__)
See previous Question which was partly answered but there has been a change in requirements for the script: PHP - Exploding / Moving / Filename
i'm new to php and am stuck. I have loads of files that look like this:
2014-04-01 NS122345 - The date, the initials of the person and there employee code.
I want to be able to move the files that have NS or JB Or GA into there relevant folder/directories. So for NS it would go into the Nathan Saunders Folder, for JB into the Joe Bailey folder.
My directory structure looks like this:
root/wan/upload - Where files/images/docs are stored. Inside upload folder i have:
>2014-04-08 NS6565.doc
>2012-01-03 JB8932.doc
>2013-02-01 GA5434.doc
>etc
root/wan/administrator/components/com_upload - where my code is stored
This is my php code for moving, creating and checking the filename and putting it in the correct folder:
$dir = JPATH_BASE . DS . "upload";
$folders = array('SE528733B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/528733B','SE125673B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/125673B','SE3452312'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/3452312');
$files = scandir($dir);
foreach($files AS $file){
if(!is_file($dir.DS.$file)){ continue; }
$array = explode(' ', $file);
if(count($array)<2){ continue; }
$firstTwoLetters = substr($array[1], 0, 9);
$foldername = $firstTwoLetters;
if(is_dir($folders[$firstTwoLetters])||mkdir($foldername[$firstTwoLetters],0777, 1))
rename($dir.DS.$file,$foldername[$firstTwoLetters].DS.$file);
That code currently reads the filename if its already in the array "folders" it moves to the correct folder, I have changed it recently to make the folder automatically reading whatever file is in the upload section, but the problem comes when making the folder, the mkdir seems to make the directory:
1) in the wrong place it makes it where the code is stored which is in the com_upload section instead of making it in the upload folder.
2) Names it wrong it takes the first letter not the letters or numbers after it. E.g. "2014-04-08 NS6565.doc", makes the directory "N"
Any help to fixing those 2 problems would be great.
Thanks,
1) If you want to create the directory in another place or you use a relative path from the directory your code is or you use an absolute path.
2) When you are creating the directory you use $foldername but it isn't a name of any directory. It's instead the name of the file. Also, you use it as an array when it's a string (so it only take one char)
Try this:
$dir = JPATH_BASE . DS . "upload";
$folders = array('SE528733B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/528733B','SE125673B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/125673B','SE3452312'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/3452312');
$files = scandir($dir);
foreach($files AS $file){
if(!is_file($dir.DS.$file)){ continue; }
$array = explode(' ', $file);
if(count($array)<2){ continue; }
$firstTwoLetters = substr($array[1], 0, 9);
$foldername = substr($firstTwoLetters,0,2);
if(is_dir($dir. DS . $foldername)||mkdir($dir. DS . $foldername,0777, 1))
rename($dir.DS.$file,$dir . DS . $foldername . DS.$file);
I have some files on a directory that are autonamed like so:
file.html - 7-6-14.html (this is 1 file)
file.html - 8-7-14.html
file.html - 9-6-14.html
There are other files in the directory, but what im trying to do is to show JUST these files. I was trying scandir & array_keys - but that wasnt working out too well. The only thing i know is that all these files will have file.html - in the beginning of the filename (the last part is the date the file was created). Anybody have any ideas?
As taken from the PHP: glob reference page:
foreach (glob("file.html -*.html") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
scandir() is the way to go.
$files = scandir($dir);
foreach ($files as $fname) {
if (strpos($fname, "file.html") == 0) display_file();
}
is_dir() according to the php manual returns true if passed a string that refers to a folder.
It's returning false -- despite being passed an array of valid folder names -- this is probably something simple but I'm beating myself up over not finding it.
Here is the code:
define('TEST_SUBFOLDERS_FILES_PATH', 'C:/xampp/htdocs/theProj/mainSubdir/');
$currentFolder = ' ';
$rootOfmainSubdir = TEST_SUBFOLDERS_FILES_PATH';
$theArrayOfDirsAndFilesInmainSubdir;
// fill an array that contains all files and folders under the /mainSubdir folder
// using php's 'scandir()'
if( ($theArrayOfDirsAndFilesInmainSubdir = scandir($rootOfmainSubdir )) != FALSE )
{
$numArrayEntries = count($theArrayOfDirsAndFilesInmainSubdir);
echo "<br><br>The number of folders/files found is: " . $numArrayEntries;
// now do the triage on subfolders under /mainSubdir versus files
for($i = 0; $i < $numArrayEntries; $i++)
{
echo "<br><br>Current array element is: "
. $theArrayOfDirsAndFilesInmainSubdir[$i]
. " and is_dir() on this element returns --> "
. var_dump( is_dir($theArrayOfDirsAndFilesInmainSubdir[$i]) );
// rest of code
Here is what I see on the output for almost all the folders:
Current array element is: testFolderN and is_dir() on this element returns -->
boolean false
OR I see:
Current array element is: . and is_dir() on this element returns -->
boolean true
AND:
Current array element is: .. and is_dir() on this element returns -->
boolean true
I'm missing something really dumb here but sheesh. It seems that is_dir() is correctly returning TRUE only for the current folder "." and the parent folder ".."
If there is a nuance I'm missing in the use of is_dir() I'm not seeing it.
Help is appreciated -- all I'm going to do in the code is to make a list of the current subfolders under the TEST_SUBFOLDERS_FILES_PATH if I can get is_dir() to return TRUE not only for "." and ".." but also the other 'testFolderN' subfolders.
By the way -- there is a total of 5 subfolders, and one file in the directory, so the display of the count above is:
The number of folders/files found is: 8
You scan the $rootOfmainSubdir, but you test for is_dir()ness in your current directory. You can either prepend the root and directory separator before checking, or chdir() in there. Note, that your current directory also has . and .. entries.
You can replace everything with a simple call to glob
$dirs = glob("C:/xampp/htdocs/theProj/mainSubdir/*", GLOB_ONLYDIR);
Details :- http://php.net/manual/en/function.glob.php
You will have to prepend the $rootOfmainSubdir in your call to is_dir like this:
for($i = 0; $i < $numArrayEntries; $i++)
{
echo "<br><br>Current array element is: "
. $theArrayOfDirsAndFilesInmainSubdir[$i]
. " and is_dir() on this element returns --> "
. var_dump( is_dir(rootOfmainSubdir.$theArrayOfDirsAndFilesInmainSubdir[$i]) );
The manual says that the file name you give is_dir() is the
Path to the file. If filename is a relative filename, it will be checked relative
to the current working directory.
So you need to put "./" before each directory in order for is_dir to search the current directory for it. Otherwise, it looks under "/", probably not what you want.
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