PHP - Renaming Files In A Folder And Make A List
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 Similar TutorialsI wrote this script to rename my many tv series I have on my pc, works by finding a string in the file name and replacing it
the script works fine until I want to replace the file name with something that is also in the path
file = band ep01.avi
path = j:\media\ TV shows\Band of Brothers\
so if I try to change "Band" to "Band of Brothers" the path changes as well
is there a way I can change the code so it dosent effect the path ??
<?php $path = 'J:\media\TV shows\Band of Brothers'; foreach(glob($path.'/*.*') as $filename){ echo $filename."</BR>"; } ?> <table align="center" width="200px" border="0" cellspacing="1" cellpadding="3"> <form name="form1" method="get" action="mov.php"> <tr> <td colspan="3"><strong> </strong></td> </tr> <tr> <td width="71">Replace</td> <td width="6">:</td> <td width="301"><input name="rep" type="text" id="rep"></td> </tr> <tr> <td>With</td> <td>:</td> <td><input name="with" type="text" id="with"></td> </tr> <tr> <tr> <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr></form> </table> <?php if (isset($_GET["rep"])) { $rep1=$_GET['rep']; } if (isset($_GET["with"])) { $with1=$_GET['with']; } foreach(glob($path.'/*.*') as $filename){ $strip = str_replace($rep1, $with1, $filename); echo $strip."</br>"; rename($filename,$strip); } ?> I got this script: But it give me error, file_get_contents cannot open stream. I need to add the FTP connection with user/pass paramaters. then look in set http url, to get the file contents(images) and transfer to ftp server location. Can Anyone take alook and tell me if I am going down the right path and how to get there. Please Code: [Select] function postToHost($host, $port, $path, $postdata = array(), $filedata = array()) { $data = ""; $boundary = "---------------------".substr(md5(rand(0,32000)),0,10); $fp = fsockopen($host, $port); fputs($fp, "POST $path HTTP/1.0\n"); fputs($fp, "Host: $host\n"); fputs($fp, "Content-type: multipart/form-data; boundary=".$boundary."\n"); // Ab dieser Stelle sammeln wir erstmal alle Daten in einem String // Sammeln der POST Daten foreach($postdata as $key => $val){ $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n"; } // Sammeln der FILE Daten if($filedata) { $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$filedata['name']."\"; filename=\"".$filedata['name']."\"\n"; $data .= "Content-Type: ".$filedata['type']."\n"; $data .= "Content-Transfer-Encoding: binary\n\n"; $data .= $filedata['data']."\n"; $data .= "--$boundary--\n"; } // Senden aller Informationen fputs($fp, "Content-length: ".strlen($data)."\n\n"); fputs($fp, $data); // Auslesen der Antwort while(!feof($fp)) { $res .= fread($fp, 1); } fclose($fp); return $res; } $postdata = array('var1'=>'today', 'var2'=>'yesterday'); $filedata = array( 'type' => 'image/png', 'data' => file_get_contents('http://xxx/tdr-images/images/mapping/dynamic/deals/spot_map') ); echo '<pre>'.postToHost ("localhost", 80, "/test3.php", $postdata, $filedata).'</pre>'; I want to copy everything in templates/blue to the folder code/ However: shell_exec("cp -r 'templates/blue' 'code'"); Creates a folder called blue inside code. I tried cp -r 'templates/blue/*' 'code', but that didn't do anything. Any ideas? Hii everyone. I'm using the following code to save a file into a folder, and allow files to be deleted from the folder. the upload works fine. The delete does work, but sometimes you have to click on the delete link a few times before the file is deleted. i'm wondering if someone can see where the problem is in the code. Also, when the file is deleted, the history entry is not added. i'm a bit confused why it doesn't. i'd appreciate any assistance which you can provide. thank you. Code: [Select] <?php include('db.php'); $CommID = $_GET['CommID']; // prevent server timeout if uploads take longer than 30 seconds. set_time_limit(0); if (isset($_GET['action'])) { $action = $_GET['action']; } else { $action = ''; } if (($action == 'view' or $action == 'dnld') and isset($_GET['id'])) { $id = $_GET['id']; // User is retrieving a file $sql = "SELECT * FROM communicationsattachments WHERE id = '$id'"; $result = @mysql_query($sql); if (!$result) { exit('Database error: ' . mysql_error()); } $file = mysql_fetch_array($result); if (!$file) { exit('No files found in database!'); } $uploadDir = "upload/"; $filename = $file['name']; $mimetype = $file['type']; $disposition = 'inline'; $filePath = $uploadDir . $filename; if ($action == 'dnld') { $disposition = 'attachment'; if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5') or strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7')) { $mimetype = 'application/x-download'; } } header("content-disposition: $disposition; name=$filename"); header("content-type: $type"); readfile($filename); exit(); } elseif ($action == 'del' and isset($_GET['id'])) { $id = $_GET['id']; $sql = "SELECT * FROM communicationsattachments WHERE id='$id'"; $result = @mysql_query($sql); if (!$result) { exit('Database error: ' . mysql_error()); } $file = mysql_fetch_array($result); if (!$file) { exit('File with given ID not found in database!'); } chdir('upload/'); $uploadDir = "upload/"; $filename = $file['name']; $mimetype = $file['type']; $disposition = 'inline'; $path="upload/" . $filename; if(unlink($path)) echo "File has been deleted file "; // User is deleting a file mysql_query ("DELETE FROM communicationsattachments WHERE id='$id'") or die(mysql_error()); // fetch name of case owner based on CommID Number $sql = "SELECT communications.CommID, communications.ActionOwner FROM communications WHERE communications.CommID='$CommID'"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No case owner found"; exit; } while ($row = mysql_fetch_assoc($result)) { $CaseOwner = $row["ActionOwner"]; } // Inserts history into the communications history table mysql_query("INSERT INTO communicationshistory (CommID, DateRecorded, TimeRecorded, StatusNotes) VALUES ('$CommID', CURDATE(), NOW(), 'Attachment Saved by $CaseOwner')") or die(mysql_error()); // header('location: ' . $_SERVER['PHP_SELF']); exit(); } elseif (isset($_FILES['upload'])) { // Bail out if the file isn't really an upload. if (!is_uploaded_file($_FILES['upload']['tmp_name'])) { echo "There was no file uploaded!"; //header('location: ' . $_SERVER['PHP_SELF']); exit; } $uploadDir = "upload/"; $fileName = $_FILES['upload']['name']; $tmpName = $_FILES['upload']['tmp_name']; $fileSize = $_FILES['upload']['size']; $fileType = $_FILES['upload']['type']; $uploaddesc = $_POST['desc']; $filePath = $uploadDir . $fileName; $result = move_uploaded_file($tmpName, $filePath); if (!$result) { echo "Error uploading file"; } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $query = "INSERT INTO communicationsattachments (name, type, description, CommID, size, path ) ". "VALUES ('$fileName', '$fileType', '$uploaddesc', '$CommID', '$fileSize', '$filePath')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); echo "<br>Files uploaded<br>"; // fetch name of case owner based on Mega Case Number $sql = "SELECT communications.CommID, communications.ActionOwner FROM communications WHERE communications.CommID='$CommID'"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No case owner found"; exit; } while ($row = mysql_fetch_assoc($result)) { $CaseOwner = $row["ActionOwner"]; } // Inserts history into the communications history table mysql_query("INSERT INTO communicationshistory (CommID, DateRecorded, TimeRecorded, StatusNotes) VALUES ('$CommID', CURDATE(), NOW(), 'Attachment Saved by $CaseOwner')") or die(mysql_error()); } // Default page view: lists stored files $sql = "SELECT * FROM communicationsattachments WHERE CommID=$CommID"; $filelist = @mysql_query($sql); if (!$filelist) { exit('Database error: ' . mysql_error()); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link href="styles.css" rel="stylesheet" type="text/css" /> <style type="text/css"> body { background-color: #cad7f6; } </style> <script type="text/javascript"> function refresh_parent(){ window.parent.location = window.parent.location.href; } </script> </head> <body> <div style="margin:20PX; background-color:#cad7f6; "> <form action="" method="post" enctype="multipart/form-data" > Upload File: <input type="file" name="upload" /> File Description: (not required) <input type="text" name="desc" maxlength="255" /> <input type="submit" value="Upload" onclick="refresh_parent()"/> <input name="MAX_FILE_SIZE" type="hidden" value="10737418240" /> </form> Files stored in the datebase for CommID <?php echo $CommID; ?> are listed below. You may attach as many files as necessary.<br /><br /> <table> <tr> <th>Filename: </th> <th>Description: </th> <th>Size: </th> </tr> <?php if (mysql_num_rows($filelist) > 0) { while ($f = mysql_fetch_array($filelist)) { ?> <tr valign="top"> <td width="200px"><?php echo $f['name']; ?> </td> <td width="200px"><?php echo $f['description']; ?> </td> <td><?php echo $f['size']; ?> </td> <td> [<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=dnld&id=<?php echo $f['id']; ?>">Download</a> | <a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=del&id=<?php echo $f['id']; ?>" onclick="refresh_parent()">Delete</a>] </td> </tr> <?php } } else { ?> <tr><td colspan="3">No Files!</td></tr> <?php } ?> </table> </div> </body> </html> i'm using a flash frontend, and i need help with a script that will take all the files in a folder (up to 6) and mail it to someone. i can do it as a zip or not. can anyone help please. hi all, i have this music website and i have to upload every album under this folder "newsongs" ... in AlbumName folder i have normal quilty songs and HQ folder..under HQ folder i have High Quilty songs for each album. i have this coding which moves Album folder and normal quilty songs to other folder "songs" but i also want to move subfolder "HQ" and High Quilty songs with AlbumName folder for($i=0;$i<=$ct;$i++) { $alb=$alname[$i]; $cat=$catname[$i]; $albids=$albid[$i]; $fon=$folder_name[$i]; $tmp_name=$doc_root."newsongs/$fon"; $uploads_dir=$doc_root."songs/$cat/$fon"; if ($handle = opendir($tmp_name)) { /* This is the correct way to loop over the directory. */ while (false !== ($file = readdir($handle))) { //echo "$file\n <br>"; if($file !=='..' and $file !=='.') { $song_path="songs/$cat/$fon/$file"; if(!is_dir("$tmp_name/$file") and (!is_dir("$uploads_dir/$file"))) { if(copy("$tmp_name/$file", "$uploads_dir/$file")) { $cp=1; $ext=substr($file,-4); if($ext=='.mp3') $insqry=mysql_query(" insert into tbl_songs set song_name='$file', album_id='$albids', artist_id='$artid', song_path='$song_path' "); unlink($tmp_name.'/'.$file); } else { echo "could not move songs "; } } } if($insqry) $msg="songs Added to the database"; else $msg="songs Not Added to the database"; } closedir($handle); thnx in advnce Inside one folder i have around 200 folder's and each folder's having 150 mp3 files. I want to get metadata of each mp3 file's below is the code which i have tried but getting below error. Fatal error: Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(C:\Users\Desktop\Rajesh song,C:\Users\Desktop\Rajesh song): The system cannot find the path specified. (code: 3)' in C:\xampp\htdocs\getID3-master\rajupal.php:4 Stack trace: #0 C:\xampp\htdocs\getID3-master\rajupal.php(4): RecursiveDirectoryIterator->__construct('C:\\Users\\Deskto...') #1 {main} thrown in C:\xampp\htdocs\getID3-master\rajupal.php on line 4 <?php include("getid3/getid3.php"); $directory = 'C:\Users\Desktop\Rajesh song'; $filename = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); while($filename->valid()) { if (!$filename->isDot()) { $getID3 = new getID3; $file = $getID3->analyze($filename); //print_r($file); $playtime_seconds = $file['playtime_seconds']; $dumpa=gmdate("H:i:s", $playtime_seconds); $filesize = $file['filesize']; $filepath = $file['filepath']; $filename = $file['filename']; $filename1 = $file['fileformat']; echo "<table class='table table-striped'>"; echo "<tr>"; echo "<th>File Path</th>"; echo "<th>Name</th>"; echo "<th>Size(kb)</th>"; echo "<th>Duration</th>"; echo "<th>File Type</th>"; echo "</tr>"; echo "<tr>"; echo "<td> ".$filepath."</td>"; echo "<td> ".$filename."</td>"; echo "<td> ".$filesize."</td>"; echo "<td> ".$dumpa."</td>"; echo "<td> ".$filename1."</td>"; echo "</tr>"; echo "</table>"; } $filename->next(); } ?> Edited July 26, 2020 by sapnawat Deci eu am asa config.php code: <?php error_reporting(0); $host = "93.xx.xx.xx"; $user = 'X@google.xxx'; $password = 'password'; $path = '/direcotry'; ?> apoi code: <?php include ('config.php'); $ftp_connection = @ftp_connect($host); @ftp_login($ftp_connection, $user, $password); $parent = substr($path, 0, strrpos($path, "/")); if (glob($path . "*.ini") != false) { $filecount = count(glob($path . "*.ini")); echo $filecount; } else { echo 0; } ftp_close($ftp_connection); ?> it should count the files with the extension .ini But always on the page shows 0 Please Help.. I'm using the following code to create a folder from a text field and works fine. I would like to upload 3 files in the created folder. <?php // set our absolute path to the directories will be created in: $path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/'; if (isset($_POST['create'])) { // Grab our form Data $dirName = isset($_POST['dirName'])?$_POST['dirName']:false; // first validate the value: if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) { // We have a valid directory: if (!is_dir($path . $dirName)) { // We are good to create this directory: if (mkdir($path . $dirName, 0775)) { $success = "Your directory has been created succesfully!<br /><br />"; }else { $error = "Unable to create dir {$dirName}."; } }else { $error = "Directory {$dirName} already exists."; } }else { // Invalid data, htmlenttie them incase < > were used. $dirName = htmlentities($dirName); $error = "You have invalid values in {$dirName}."; } } ?> <html> <head><title>Make Directory</title></head> <body> <?php echo (isset($success)?"<h3>$success</h3>":""); ?> <h2>Make Directory on Server</h2> <?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?> <form name="phpMkDIRForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> Enter a Directory Name (Alpha-Numeric only): <input type="text" value="" name="dirName" /><br /> <input type="submit" name="create" value="Create Directory" /> </form> </body> </html> 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 I've tried this code and a few others, but it only displays 0. I'd like the simplest working way to display the number of files in a directory. Thanks for the help! $directory = "../images/team/harry/"; $filecount = count(glob("" . $directory . "*.*")); echo $filecount; Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> </head> <body> <?php $hostname='xxx'; $username='xxx'; $password='xxx'; $dbname='xxx; $usertable=xxx; $myconn=mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.'); if ((($_FILES["file"]["type"] =="image/gif") || ($_FILES["file"]["type"] =="image/jpeg") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"]< 200000)) { if ($_FILES["file"]["error"] >0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br/>"; } else { if (file_exists("uploads/" . $_FILES["file"]["name"])) { echo "File already exists. Choose another name."; } else { move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]); } } } else { echo "Invalid file"; } $path="uploads/" . $_FILES["file"]["name"]; $desc=$_POST["desc"]; if (!myconn) { die ('Could not connect: ' . $mysql_error()); } $db_selected=mysql_select_db('xxx',$myconn); if (!$db_selected) { die ('Can\'t use xxxx : ' . mysql_error()); } mysql_query("INSERT INTO partners (desc,photopath,state) VALUES ('$desc','$path','$state')"); mysql_close($myconn); ?> </body> </html> Hi Basically I've built a CMS where by my clients can upload a number of images. On the success page I want to display the images they uploaded by file name. The issue is the number of images can vary. They may upload 2 or 10 or 50 etc. So far I've come up with this: Code: [Select] // number of files $UN = 3; //I've set this to 3 for now, but this is passed from the upload page! // server directories and directory names $dir = '../properties'; $images = glob($dir.'/*.{jpg}', GLOB_BRACE); //formats to look for $num_of_files = $UN; //number of images to display from number of uploaded files foreach($images as $image) { $num_of_files--; $newest_mtime = 0; $image = 'BROKEN'; if ($handle = @opendir($dir)) { while (false !== ($file = readdir($handle))) { if (($file != '.') && ($file != '..')) { $mtime = filemtime("$dir/$file"); if ($mtime > $newest_mtime) { $newest_mtime = $mtime; $image = "$file"; } } } } if($num_of_files > -1) //this made me laugh when I wrote it echo $trimmed = ltrim($image, "../properties").'<br />'; //display images else break; } Without this piece of code: Code: [Select] $newest_mtime = 0; $image = 'BROKEN'; if ($handle = @opendir($dir)) { while (false !== ($file = readdir($handle))) { if (($file != '.') && ($file != '..')) { $mtime = filemtime("$dir/$file"); if ($mtime > $newest_mtime) { $newest_mtime = $mtime; $image = "$file"; } } } } It shows the first 3 files alphabetically. I want to view the last number of images added. With the above code it simply shows the last image added 3 times! So I need to get the time each image was added and then order by the newest added and limit to the number of images uploaded. Any suggestions please? Kindest regards Glynn Hi, ive recently created a gallery website and im happy with the way everything currently works. However the main drawback is the site uploads using a html webfom which is great for remote users or the odd image. However, as i want to mass upload my existing collection i will need the ability to read a selected folder and then to carry out all the same processes that existed from the existing html form upload. Im also using gdlibrary and checking file types to ensure they are within my allowed list, but im wondering if there are any other common security alerts i should be aware of to keep things a little bit safer if/when i publish outside of my LAN. So in a nut shell i need some assistance with changing my upload process to work for more than one file at a time, ideally by reading a folder, or at least reading X amount of files at a time - processing them then moving onto next batch of files in the list. Then the next part i need help with is checking/improving basic security of the system I am unsuccessfully able to do the following:
User creates an account
After login, checks server if user has their own folder created
If doesn't exist, create it
Copy files from source_code to this new folder
My code does create a folder, but no files appear inside it.
Been trying to find an example with google search for the past 3 days with no luck.
I am running LAMP on Linux Mint OS to run my PHP webpages.
Can anyone tell me if issues with this section of coding?
<?php function wait_time($seconds) { $seconds = abs($seconds); if ($seconds < 1): usleep($seconds*1000000); else: sleep($seconds); endif; } $file1 = "blank.html"; $file2 = "channel_video.php"; $file3 = "clear_playlist.php"; $file4 = "confirm.html"; $file5 = "index.html"; set_time_limit(0); //prevent script from timing out $account = $_POST["account_name"]; $src = "source_code/"; $dst = $account."/"; echo 'Setting up your account page ->.'; mkdir($account, 0777, true); echo '.'; //create folder with full write permissions wait_time(2000); //wait 2 seconds before copying files over copy($src.$file1, $dst.$file1); echo '.'; wait_time(2000); //wait 2 seconds before copying files over copy($src.$file2, $dst.$file2); echo '.'; wait_time(2000); //wait 2 seconds before copying files over copy($src.$file3, $dst.$file3); echo '.'; wait_time(2000); //wait 2 seconds before copying files over copy($src.$file4, $dst.$file4); echo '.'; wait_time(2000); //wait 2 seconds before copying files over copy($src.$file5, $dst.$file5); echo '.<- setup finished<br>'; ?>Thanks for any input you can provide. This topic has been moved to PHP Installation & Configuration. http://www.phpfreaks.com/forums/index.php?topic=332517.0 how do i grab and print on page in date order all .jpg files in a folder ? Hey guys im automatically generating a folder location to place some image files the user has uploaded into. If this folder doesnt exist how can i make it? $target_path_thumbnails = "http://www.worldwidelighthouses.com/Images/".$folderlocation."/".$foldername."/Mini/"; Thats the path style. Danny 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, |