PHP - List All Files In Dir, Then Put Content Of Files Into Array
Hello
I have a simple question about file handling... Is it possible to list all files in directories / subdirectories, and then read ALL files in those dirs, and put the content of their file into an array? Like this: array: [SomePath/test.php] = "All In this php file is being read by a new smart function!"; [SomePath/Weird/hello.txt = "Hello world. This is me and im just trying to get some help!";and so on, until no further files exists in that rootdir. All my attempts went totally crazy and none of them works... therefore i need to ask you for help. Do you have any ideas how to do this? If so, how can I be able to do it? Thanks in Advance, pros Similar TutorialsI am trying to find a script that will show just the file names of files in a specific directory. I tried this code posted previously on this forum and it works but shows the directory name. Code: [Select] <?php filesInDir('attachments'); function filesInDir($tdir) { $dirs = scandir($tdir); foreach($dirs as $file) { if (($file == '.')||($file == '..')) { } elseif (is_dir($tdir.'/'.$file)) { filesInDir($tdir.'/'.$file); } else { echo $tdir.'/'.$file."<br>"; } } } ?> Result is: attachments/Sedona_and_Slot_Canyon_links.docx Thanks for the help. Hi, I'm automating a process of Inserting a CSV to a database. I'm doing it in PHP. I need to go to http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/ and get the list of the files in this directory. Which is the best way of doing it in PHP? Best Regards, Hi im using ftp_rawlist () to list files in my web hosting folder /public_html/ it works fine, but is there anyway to only show/list .php & html files? Hi Sorry if this is the wrong place for this but I'm totally stumped here and I know its a basic question but I'm very new to php and I need help :-) Basically all i would like to do is list the files and folders in the following directory alphabetically, I know i need to put them in an array etc but I don't know how and would really appreciate some help! So any help would be very gratefully received. Here's my code so far: <?php $sub = ($_GET['dir']); if (strstr($sub, "..")) {$sub = "";} $path = '../media/Documents'; $path = $path . "$sub"; $dh = opendir($path); $i=1; while (($file = readdir($dh)) !== false) { if(substr($file,0,1) != ".") { if (substr($file, -4, -3) =="."){ echo "<font size=2 face=\"Arial, Helvetica, sans-serif\">$i. $file <br />"; }else{ echo "<font size=2 face=\"Arial, Helvetica, sans-serif\">$i. <a href='?dir=$sub/$file'>$file</a><br />"; } $i++; } } closedir($dh); ?> Many thanks in advance! I have a script that works perfectly, for one type of file extension. What I want to do now is be able to list all files in a set of file types. I want to pass the argument to the fileSystem class's loadFiles method like this: $some_var = $fileSystem->loadFiles(DATA_DIRECTORY, "csv,xls,etc"); Then in the loadFiles method it reads the dir for each file, then test its extension. If they are of the right type, then push it on the returned array. Now I am having problems testing if the file's extension is in the array. If I use if (strpos(getExt($file), $array_of_wanted_exts))... php would match php3.. Does anybody have a better method? Hello everyone I have two dropdown lists. First one you can see the tables of my db and the second one the files inside a folder. The problem is that i can't send my selections from the dropdown list to an other file. My project is to choose a table, then a CSV file and then load the file in db. index.php: Code: [Select] <?php //EMFANISH PINAKWN include("../forma/dbCon.php"); echo "<form action='load_table_test.php' method='POST'>"; $sql="SHOW TABLES FROM misthodosia"; $result=mysql_query($sql); if (!$result) { echo "Υπάρχει πρόβλημα με την βάση\n"; echo 'MySQL Error: ' . mysql_error(); exit; } echo"<select>"; while ($row = mysql_fetch_row($result)) { echo "<option name='{row[0]}' value='{row[0]}'>{$row[0]}</option>"; } echo"</select>"; mysql_free_result($result); //==========================EMFANISH ARXEIWN========================== function populateDropdown(){ $path = glob("C:\\xampp\\htdocs\\dbadmin\\upload_files\\*"); //the double \\ is not a typo you //have to escape it //if the path cannot be found if(!($path)){ echo("Δεν υπάρχει ο φάκελος"); return; }//if //the path is valid else{ foreach($path as $k){ $i = basename($k); echo "<option name='$i'>".$i."</option>"; }//foreach }//else }//populateDropdown echo"<select>"; populateDropdown(); echo"</select> "; echo"<input type='submit' name='submit' value='Φόρτωσε1111111' />"; echo "</form>"; $hello="hello"; ?> load_table_test.php: Code: [Select] <?php include("../forma/dbCon.php"); echo $_POST['hello']; echo $_POST['{row[0]}']; echo $i; //$pinakas=$_POST['pinakas'] //$arxeio=$_POST['arxeio'] //$pinakas=$_POST['row'] //$arxeio=$_POST['diadromi'] //mysql_query("LOAD DATA LOCAL INFILE "$arxeio" INTO TABLE $pinakas //FIELDS //TERMINATED BY ',' //ENCLOSED BY '\"' //LINES TERMINATED BY '\n') echo "$arxeio"; echo "$pinakas"; echo "<br/><br/><br/><br/><br/><a href='index.php'>Επιστροφή στην προηγούμενη σελίδα.</a>"; ?> errors: Code: [Select] Notice: Undefined index: hello in C:\xampp\htdocs\dbadmin\load_table_test.php on line 6 Notice: Undefined index: {row[0]} in C:\xampp\htdocs\dbadmin\load_table_test.php on line 8 Notice: Undefined variable: i in C:\xampp\htdocs\dbadmin\load_table_test.php on line 9 Notice: Undefined variable: arxeio in C:\xampp\htdocs\dbadmin\load_table_test.php on line 27 Notice: Undefined variable: pinakas in C:\xampp\htdocs\dbadmin\load_table_test.php on line 28 I'm pretty new to php and I'm furiously trying to get this code to list the folders/files alphabetically but to no avail! I'd really appreciate it if someone could take a look and guide me as to what to do, I'm pulling what little hair i have left out! I can currently see the folder contents but the order is all over the place. Thanks very much!!! -------------------------- <?php $sub = ($_GET['dir']); if (strstr($sub, "..")) {$sub = "";} $path = '../media/Movies'; $path = $path . "$sub"; $dh = opendir($path); $i=1; while (($file = readdir($dh)) !== false) { if(substr($file,0,1) != ".") { if (substr($file, -4, -3) =="."){ echo "<font size=2 face=\"Arial, Helvetica, sans-serif\">$i. $file <br />"; }else{ echo "<font size=2 face=\"Arial, Helvetica, sans-serif\">$i. <a href='?dir=$sub/$file'>$file</a><br />"; } $i++; } } closedir($dh); ?> -------------------------- Hey guys, I'm very new to PHP so I apologize for any stupid mistakes or if I'm a little slow understanding things. I have put together a small website and I wanted to use a PHP script to display a list of files and folders (and sub folders). Basically a ghetto equivalent of an FTP page so I can apply CSS and make things look a little pretty. I have the following code I found from Google that will display all of the files and folders, not perfect but it will work for now! However I can't seem to work out the syntax to make them a hyperlink. Any help would be appreciated! <?php function getDirectory( $path = '.', $level = 0 ){ $ignore = array( 'cgi-bin', '.', '..' ); // Directories to ignore when listing output. Many hosts // will deny PHP access to the cgi-bin. $dh = @opendir( $path ); // Open the directory to the handle $dh while( false !== ( $file = readdir( $dh ) ) ){ // Loop through the directory if( !in_array( $file, $ignore ) ){ // Check that this file is not to be ignored $spaces = str_repeat( ' ', ( $level * 4 ) ); // Just to add spacing to the list, to better // show the directory tree. if( is_dir( "$path/$file" ) ){ // Its a directory, so we need to keep reading down... echo "<strong>$spaces $file</strong><br />"; getDirectory( "$path/$file", ($level+1) ); // Re-call this same function but on a new directory. // this is what makes function recursive. } else { echo "$spaces $file<br />"; // Just print out the filename } } } closedir( $dh ); // Close the directory handle } ?> So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png fileĀ which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is? Hello Coder Guys, I need a small help from you. I want to list all files & directories based on last file modification time of server. I want to list new files as first & old files as last. Consider "files" as the directory name which contains all files & directories. Please make the php code to display all files & directories from "files" directory based on last file modification time of server. Thanks IN Advance ! I have a folder containing files. I want to replace some characters in the file names (e.g. "_" with "-"), then make a list of new files (renamed ones). Thanks Hello, In m script, I need to get the content of another php file as a string, including the content of all the files which are included in it and in lower levels. Any idea how to do it? I tried output buffer+include but it doesn't get the content of the included files. Thanks I came accross this code on YouTube and it works great for listing the content of a folder that the .php file is in. However, how can I alter this code to list files of all folders and sub-folders? I thought plugging in an asterik might work on the "$path =" line, but it didn't. Code: [Select] <?php $path = "."; $handle = opendir($path); while ($file = readdir($handle)) { echo $file . "<br>"; } closedir($handle); ?> Hello. I have a directory with files that look like this: priceguide_20100809.pdf priceguide_20100808.pdf priceguide_20100807.pdf priceguide_20100806.pdf I am trying to come up with a function that will grab and save the filename with the biggest date .. ie: priceguide_20100809.pdf. Any assistance would be greatly appreciated!! show list of files uploaded by current session user to the database. I want to show different users when they log in to the website...they can see a list of old files that they have uploaded. can anyone tell me the code/script to this.....please, ty Hello, I'd like to make an array preferably multidimensional from files what are in subdirectory. Here is a code what I wrote but I doesn't work well becouse I wanted to load that string into javascript array..but it didnt work becouse it had some special characters.. Code: [Select] $dir = opendir('f'); if($dir) { $result = ""; while (($file = readdir($dir)) !== false ) { if(strpbrk($file, 'mp3')) { $result = $result ."{ Track name: \"$file\", location: \"f/$file\" },<br/>"; } } echo $result; } I am using WPSQT plugin in my blog site .I code some files in PHP also.how to add that files in plugin files.
How would I copy an array of selected files? I know how to list them using a 'for' loop, and how to separate them using a 'foreach' loop, but I am unable to get a checkbox array to copy to a destination folder. Help is appreciated. Hi, I have this php code to display the url of the files and it works fine, it just has a weird order when it is echoed out. Here is the code: Code: [Select] <?php $date = date("Y-m-d"); $picarray = array(); $handle = opendir ('pqimages/'.$date.'/'); while (false !== ($file = readdir($handle))) { if($file != "." && $file != "..") { $picarray[] = "http://randomaydesigns.com/pqimages/".$date."/".$file.""; } } $json_array = json_encode($picarray); echo $json_array; ?>There are three files in the folder and they are 33,34,35.jpg it displays them like 33,35,34.jpg Any Recommendations? Thanks, GEORGE Here is my current code to display files from the end to beginning : Code: [Select] <?php function func() { $date = date("Y-m-d"); $picarray = array(); $userarray = array(); $handle = opendir ('pqimages/'.$date.'/'); while (false !==($file = readdir($handle))) { if($file != "." && $file != "..") { $picarray[] = "http://blah.com/pqimages/".$date."/".$file.""; $userarray[]= "pqimages/".$date."/".$file.""; } } sort($picarray); sort($userarray); closedir($handle); $json_array = json_encode($picarray); echo $json_array; } func(); ?> How could I change this from end to beginning for ($picarray)? Cheers, George |