PHP - Upload Files In New Created Folder
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> Similar TutorialsHi, 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 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> 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>'; Hi, I've written a script for a client which creates a folder on the server using mkdir. The client wanted this folder to be created for them (don't ask why, it's complicated!), then they wanted to be able to FTP in and add files into the folder using FTP. The problem is that the script creates the file with a group of 99. When the client tries to FTP in and add their files, they get the following error: '550 Can't create directory: Permission denied', presumably because they're in a different group. What I need to be able to do is get the script to create a folder with a different group, so that my client can FTP their files into it. I thought I would be able to use PHP's chgrp after mkdir, as follows: mkdir($filepath, 0777) chgrp($filepath, 501); However then I get "Warning: chgrp() [function.chgrp]: Operation not permitted". I realise from reading the manual that I need to be a superuser to do this, which my web script obviously isn't. My question is, how can I get around this? Is there some setting in Apache that I can set? Thanks in advance for any help! Willo I am using apache web server on linux. I am using php for coding. My php code is not able to read the files from /var/tmp folder. If apache itself creates some files in /var/tmp folder then php code is able to read it. Why this permission denied issues are there though full access permissions are given to each file?
Hi, I'm not sure if this is the right forum to post this question, but I'll still post it. I'm a newbie programmer, have 1 year experience of php, mysql and html and know how to make a basic website, but I've never actually uploaded the already written code on the internet.So my question is, if you use vertrigo serv and have folders full of php files, what do you do after getting a domain? I read that dreamweaver does that for you, but i also read that it is a closed source software with limitations if you get the free version.The other choice is using FileZilla(which I don't fully understand yet ) i presume.
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? 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? Hello, i am looking for a way to create a new folder when a customer uploads photos. I would like the folder to be named their email address. The photo uploader code is below: - [php <?php if($logged[scrollingpicturedisplay] == "yes"){ if($difference == "Gone"){ }else{ if($logged[spd_process] == "1"){ }else{ ?> <div id="spd"> <link href="/uploadify.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="/swfobject.js"></script> <script type="text/javascript" src="/jquery.uploadify.v2.1.4.min.js"></script> <script type="text/javascript"> $(function() { $('#custom_file_upload').uploadify({ 'uploader' : '/uploadify.swf', 'script' : 'uploadify.php?user=<?php echo("$logged[ip]");?>', 'cancelImg' : '/cancel.png', 'folder' : '/wuploads', 'multi' : true, 'auto' : true, 'fileExt' : '*.ZIP;*.zip;*.rar;*.jpg', 'queueID' : 'custom-queue', 'queueSizeLimit' : 1000, 'simUploadLimit' : 1000, 'removeCompleted': true, 'onSelectOnce' : function(event,data) { $('#status-message').text(data.filesSelected + ' files have been added to the queue.'); }, 'onAllComplete' : function(event,data) { $('#status-message').text(data.filesUploaded + ' files uploaded, ' + data.errors + ' errors.'); php/] and i think this is the code for the create new folder [php <? mkdir("/wuploads/{$slide['email']}"); ?> php/] The email is stored on the users database as the field 'email' i then would like it to put the photos in the created folder which i think is something like this [php 'folder' : '/wuploads/$slide['email']', php/] The pictures go into the correct folder if i use this, however the create folder part of it doesnt seem to work. any help would be great, thanks 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> hi all i need a script that will allow me upload images to 2 dif folders on my server and then add the info to my database along with some other form data. iv been looking all over for code or scripts for days now and have been playing with cut and copyed code but no look again any help i will be greatful for as im a noob to php but al learning quick here is my html form Code: [Select] <html> <body> <form action="add.php" method="post"> Project Name: <input type="text" name="pro_name" /><br> Thumbnail: <input type="file" name="thumbnail" /><br> ////// this image to ../thum Short Details: <input type="text" name="short_details" /><br> Full Details: <input type="text" name="full_details" /><br> Category: <input type="text" name="cat" /><br> Image1: <input type="file" name="image1" /><br>//// and image1,2,3,4 to ../images Image2: <input type="file" name="image2" /><br> Image3: <input type="file" name="image3" /><br> Image4: <input type="file" name="image4" /><br> <input type="submit" /> </form></body></html> here is my code for add.php witch only adds the info to the DB Code: [Select] <?php error_reporting(E_ALL); include ("../includes/db_config.php"); $con = mysql_connect($db_hostname,$db_username,$db_password); @mysql_select_db($db_database) or die( "Unable to select database"); $sql="INSERT INTO $db_table (pro_name, thumbnail, short_details, full_details, cat, image1, image2, image3, image4) VALUES ('$_POST[pro_name]','$_POST[thumbnail]','$_POST[short_details]','$_POST[full_details]','$_POST[cat]','$_POST[image1]','$_POST[image2]','$_POST[image3]','$_POST[image4]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> 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. 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.. 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 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. 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; 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 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 |