I am a beginner to PHP so please forgive any ignorance...
I am using the exec() command as following to get the list of files in my media directory..
<?php // exec.php
$cmd = "dir"; // Windows
exec(escapeshellcmd($cmd), $output, $status);
if ($status) echo "Exec command failed";
else
{
echo "<pre>";
foreach($output as $line) echo "<a href='$line'>$line</a> \n";
}
?>
The problem is it gives the list of files along with the various timestamps of the filenames-
Volume in drive F is Movies
Volume Serial Number is 172B-1DE0
06/17/2011 01:11 AM 6,318 bck.gif
Hence, here it creates clickable link to each line for the output which needless to say does not work.
What I want is that it will only create clickable links for the filenames and not the extra meta information, which the user can then click to launch his native program like this-
video1.mpg
video2.mpg
bck.gif
You're far better off using PHP's directory manipulation functions instead. The scandir() function should be of particular interest to you.
http://uk.php.net/manual/en/book.dir.php
http://uk.php.net/manual/en/function.scandir.php
Don't forget that the scandir listing will include . and .. ao you'll need to remove them from the results set unless you plan to use them for navigation.
There is no need to use exec(); to list files in the directory, PHP has many build in functions for dealing with the file system:
From the readdir() manual page:
<?php
if ($dirHandle = opendir('.')) {
while (false !== ($nodeHandle = readdir($dirHandle ))) {
if ($nodeHandle == '.' || $nodeHandle == '..') {
continue;
}
echo "$nodeHandle \n";
}
closedir($dirHandle);
}
?>
Related
I have the following code which sorts files in its current directory:
<?php
$folders = array_filter(glob('*'), 'is_dir');
foreach ($folders as $foldlist) {
echo "<tr><td><img src=\"/index/RESSOURCES/icon/folder.png\"></td><td>{$foldlist}</td><td><img src=\"/RESSOURCES/icon/info.png\"></td></tr>";
}
$files = glob("*.*");
foreach ($files as $filename) {
$type=substr($filename,strrpos($filename,'.')+1);
echo "<tr><td><img src=\"/index/RESSOURCES/icon/{$type}.png\"></td><td>{$filename}</td><td><img src=\"/RESSOURCES/icon/info.png\"></td></tr>";
}
?>
It works, don't worry about that. There is only a minor problem that I've been troubleshooting for the last few days:
If you run my code, you'll see that before every file name, there is an icon. It fetches the right icon by taking the file s format. Cool, right?
But here is my problem:
Lets say I have two files: dummy.zip and dummy.tar.
Both files will fetch "zip.png" and "tar.png" - The two icons are exactly the same. So basically, im making the client load two times the same icon, witch makes my page significally slower. Nothing dramatic? Well, I have over a hundred files right now... Witch pretty much all of them having a different format.
How can I make it so:
if $icon == zip OR tar OR gz LOAD zip.png?
Cheers.
After your line
$type = substr($filename,strrpos($filename,'.')+1);
and before
echo "<tr><td><img src=\"/index/RESSOURCES/icon/{$type}.png\"></td><td>{$filename}</td><td><img src=\"/RESSOURCES/icon/info.png\"></td></tr>";
you may just add the following code
if($type == 'zip' || $type == 'tar' || $type == 'gz') {
$type = 'zip';
}
It will load zip.png for all the three cases
I have a script I am using to filter some ROM and ISO files.
I have (with a lot of help) got a working script where files are filtered by filename, however I am trying to add a section in which I can include extra ad-hoc filenames to be filtered for me by providing them in a local .txt file. This is working OK, however in my .txt file I am having to put the full filename (including the .txt extension) into the .txt - for example my "manualregiondupes.txt file looks like this:
Game One.zip
Game Two.zip
Game Three.zip
Whereas I want it to just type them in my .txt file like so:
Game One
Game Two
Game Three
The current regex i'm using is trying to match the full filename it finds (including the .zip extension) whereas I want it to just match the section before the file extension. I have to be careful, however - as I don't want a game like:
"Summer Heat Beach Volleyball (USA)" being matched if "Beach Volleyball (USA)" is in the .txt.
Same goes for words on the other side - like
"Sensible Soccer (USA) (BETA)" being matched if "Sensible Soccer (USA)" is in the .txt
Here is my script;
// Make sure what manualregiondupes.txt is doing
if (file_exists('manualregiondupes.txt'))
{
$manualRegionDupes = file('manualregiondupes.txt', FILE_IGNORE_NEW_LINES);
$manualRegionPattern = "/^(?:" . implode("|", array_map(function ($i)
{
return preg_quote(trim($i) , "/");
}
, $manualRegionDupes)) . ')$/';
echo "ManualRegionDupes.txt has been found, ";
if (trim(file_get_contents('manualregiondupes.txt')) == false)
{
echo "but is empty! Continuing without manual region dupes filter.\n";
}
else
{
echo "and is NOT empty! Applying the manual region dupes filter.\n";
}
}
else
{
echo "ManualRegionDupes.txt has NOT been found. Continuing without the manual region dupes filter.\n";
}
// Do this magic for every file
foreach ($gameArray as $thisGame) {
if (!$thisGame) continue;
// Probably already been removed
if (!file_exists($thisGame)) continue;
// Filenames in manualregiondupes.txt
if (file_exists('manualregiondupes.txt'))
{
if (trim(file_get_contents('manualregiondupes.txt')) == true)
{
if (preg_match($manualRegionPattern, $thisGame))
{
echo "{$thisGame} is on the manual region dupes remove list. Moved to Removed folder.\n";
shell_exec("mv \"{$thisGame}\" Removed/");
continue;
}
}
}
... SCRIPT CONTINUES HERE BUT ISN'T RELEVANT!
What's the easiest way of doing this? I think i've just asked a very long question when it's actually quite simple, but oh well - I am not very good with PHP (or any script to be honest!) so apologies and thankyou's in advance! :D
You can use pathinfo in regex like -
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
it gives you perfect file name output without extension for
file.txt -> file
file.sometext.txt -> file.sometext
I would like to move a file from one directory to another. However, the trick is, I want to move file with entire path to it.
Say I have file at
/my/current/directory/file.jpg
and I would like to move it to
/newfolder/my/current/directory/file.jpg
So as you can see I want to retain the relative path so in the future I can move it back to /my/current/directory/ if I so require. One more thing is that /newfolder is empty - I can copy anything in there so there is no pre-made structure (another file may be copied to /newfolder/my/another/folder/anotherfile.gif. Ideally I would like to be able to create a method that will do the magic when I pass original path to file to it. Destination is always the same - /newfolder/...
You may try something like this if you're in an unix/linux environment :
$original_file = '/my/current/directory/file.jpg';
$new_file = "/newfolder{$original_file}";
// create new diretory stricture (note the "-p" option of mkdir)
$new_dir = dirname($new_file);
if (!is_dir($new_dir)) {
$command = 'mkdir -p ' . escapeshellarg($new_dir);
exec($command);
}
echo rename($original_file, $new_file) ? 'success' : 'failed';
you can simply use the following
<?php
$output = `mv "/my/current/directory/file.jpg" "/newfolder/my/current/directory/file.jpg"`;
if ($output == 0) {
echo "success";
} else {
echo "fail";
}
?>
please note I'm using backtick ` to execute instead of using function like exec
I have created my own l($text) function in php for a multi lingual website. i use it like this in my documents :
echo '<h1>' . l('Title of the page') . '</h1';
echo '<p>' . l('Some text here...') . '</p>';
My question is, with a php script, how can i scan all my .php files to catch all this function usages and list all the arguments used into a mysql table?
the goal, of course, is to not forget any sentences in my traduction files.
I didn't find anything on google or here, so if you have any ideas, or need some more information.
Could you:
read all *.php files with glob()
then use a regex to pull the strings out (preg_match())
strings simple mysql insert?
Seems simple enough?
i just finished, your help was usefull ! :-)
here is my ugly code for those who can be interested. it's not beautifuly coded, but not made to be loaded 10000 times per day so...
<?php
// define a plain text document to see what appen on test
header('Content-Type: text/plain; charset=UTF-8');
$dossier = 'pages/'; // folder to scan
$array_exclude = array('.', '..', '.DS_Store'); // system files to exclude
$array_sentences_list = array();
if(is_dir($dossier)) // verify if is a folder
{
if($dh = opendir($dossier)) // open folder
{
while(($file = readdir($dh)) !== false) // scan all files in the folder
{
if(!in_array($file, $array_exclude)) // exclude system files previously listed in array
{
echo "\n".'######## ' . strtoupper($file) . ' ##########'."\n";
$file1 = file('pages/'.$file); // path to the current file
foreach($file1 AS $fileline)
{
// regex : not start with a to z characters or a (
// then catch sentences into l(' and ')
// and put results in a $matchs array
preg_match_all("#[^a-z\(]l\('(.+)'\)#U", $fileline, $matchs);
// fetch the associative array
foreach($matchs AS $match_this)
{
foreach($match_this AS $line)
{
// technique of "I do not want to break my head"
if(substr($line, 0, 3) != "l('" AND substr($line, 0, 4) != " l('" AND substr($line, 0, 4) != ".l('")
{
// check if the sentence is not already listed
if(!in_array($line, $array_sentences_list))
{
// if not, add it to the sentences list array and write it for fun !
$array_sentences_list[] = $line;
echo $line . "\n";
}
}
}
}
}
}
}
closedir($dh);
}
}
?>
small precision : i do have to escape various cases as :
-> CSS : background: url('image.jpg');
and
-> jQuery : $(this).html('bla bla');
so here is why the regex starts with [^a-z(] :-)
it works very well now! just have to finish later with recording entries in a mysql table and ensure that i can load the script from time to time when there are changes on the site... keep the existing translation, overwrite the existing files etc... no problem with that.
thanks a gain, this website is really helpful ! :-)
Instead of the traditional navigation, I am trying to emulate the terminal navigation, or how you navigate with vim.
Example:
..
index
otherfile
This is my code:
$dir = realpath(dirname(__FILE__));
if(is_dir($dir)){
if($open = opendir($dir)){
while(($file = readdir($open)) !==false){
if(is_dir($file)){
if($file == '.'){ }
else{
echo "".$file."<br/>";
}
}
else{
$name = explode('.php',$file);
echo "".$name[0]."<br/>";
}
}
}
}
else{
echo $dir." Was not found";
}
}
How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list.
I want to sort files by given them a number example '1file.php' '2anotherfile.php'..
How could I sort them by the number, then remove the number and '.php', and finally print it out?
If you feel like refactoring something please do so...
"How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list."
Just check if the current item is the current file, if it is then skip it:
else {
if ($name == basename(dirname(__FILE__))) continue; // if this is the current file, go to the next iteration of the loop
$name = explode('.php',$file);
echo "".$name[0]."<br/>";
}
Note that this assumes you are in the same directory as the file (which it can do because $dir is always the directory the script is in), if not you can just add a directory check as well.
"How can add a number to the start of the file or folder, example 1index.php, then on the code, organize all the files and folder by number, and print them without the number and '.php'?"
Well I'm not too sure what you mean by this, but if you mean sort alphabetically, then it is already alphabetically sorted when you get the list.