PHP - Send All Files In Folder As Attachment
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. Similar TutorialsHi guys so for my website I want to add a feature where a user can upload a zipped folder and send that folder to another user through my Private message system, so I am wondering how this would work, would I need to upload the folder to my database, upload it to a separate folder and use some php code to display a download link to download it?
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 seem to be having a difficult time saving the attachments to a folder on the server, all the examples I see show it to the browser, what I need to do is copy the attachment to a separate folder and do some processing on it. So far everything I get, then ftp to my desktop appears corrupt. It works I just can't seem to unzip the zipped attachments, any ideas? My Code: (Not mine, I used examples from the web and put it into a function) function get_attachments($message_number){ global $connection; $structure = imap_fetchstructure($connection, $message_number); $attachments = array(); if(isset($structure->parts) && count($structure->parts)) { for($i = 0; $i < count($structure->parts); $i++) { $attachments[$i] = array( 'is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '' ); if($structure->parts[$i]->ifdparameters) { foreach($structure->parts[$i]->dparameters as $object) { if(strtolower($object->attribute) == 'filename') { $attachments[$i]['is_attachment'] = true; $attachments[$i]['filename'] = $object->value; } } } if($structure->parts[$i]->ifparameters) { foreach($structure->parts[$i]->parameters as $object) { if(strtolower($object->attribute) == 'name') { $attachments[$i]['is_attachment'] = true; $attachments[$i]['name'] = $object->value; } } } if($attachments[$i]['is_attachment']) { $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1); if($structure->parts[$i]->encoding == 3) { // 3 = BASE64 $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']); } elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']); } } } } return $attachments; } Calling Code: $a = get_attachments(6); $fp = fopen($a[1]['filename'], 'w'); fwrite($fp, $a); fclose($fp); Hi, I've created a basic form which uploads a document to my server. How do I generate an email with the uploaded document as an attachment? Here's the HTML: <form enctype="multipart/form-data" action="form1.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" /> </form> Here's the PHP: <?php $target_path = "uploads/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> Thanks in advance! hello, I did my first application of mailer php today, very nice, sending 2 pdf attachments, but for record keeping, I need a copy of the mail to go to another mail, but with out the attachments, how to accomplish this please?? here the code form html: Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Contact Form</title> <meta name="Generator" content="Alleycode HTML Editor"> <meta name="Description" content="Your description here..."> <meta name="Keywords" content="Your keywords here..."> </head> <body> <form method="post" action="sendmail2.php"> <p> <label>Name:</label> <br/> <input type="text" name="name" size="48" height="40"/> </p> <p> <label>Email:</label> <br/> <input type="text" name="email" size="48" height="40"/> </p> <p> <label>Child's Name:</label> <br/> <input type="text" name="childname" size="48" height="40"/> </p> <p> <label>Site:</label> <br/> <textarea name="site" rows="2" cols="45" overflow:hidden>xx.com.au</textarea> </p> <p> </p> <p> <label>Days:</label> <br/> <textarea name="days" rows="2" cols="45" overflow:hidden>Monday, Tuesday, Wednesday, Thursday, Friday</textarea> </p> <p> </p> <p> <input type="submit" value="Send"/> <a href="xx/form.html">clear</a></p> </form> </body> </html> sendmail2.php: <?php require("../phpmailer/class.phpmailer.php"); include("email.php"); $name = $_POST['name']; $childname = $_POST['childname']; $site = $_POST['site']; $days = $_POST['days']; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "xxx.com"; // SMTP servers $mail->Username = "xxx"; // SMTP username $mail->Password = "xxx"; // SMTP password $mail->AddAddress($_POST['email']); $mail->From = "xxx@ax.com.au"; $mail->FromName = "xxx_online"; $mail->Subject = "Message from Alouette"; $mail->IsHTML(true); $mail->Body = $message; $mail->AddAttachment("../attachs/x.pdf"); $mail->AddAttachment("../attachs/xd.pdf"); if($mail->Send()) { echo "Message sent! Thanks ! "; print('<a href="xu/mail/form.html">Reset and Back</a>'); } ?> email.php <?php $message = ' Hello '.$name.', <br/> we have received your interest in child care services for '.$childname.' from the '.$site.' website. <br/> <br/> '.$days.' <br/> <br/> Should you have any questions regarding the information on our enrolment form or services please do not hesitate to contactkkk <br/> <br/> <br/> Regards, <br/> <a href="mailto:x@x.com.au">x@nx.com.au</a> <a href="http://www.nx.com.au" target="_new">www.neo-it.com.au</a> <br/> <strong>Childcare Management Services</strong> <br/> <br/> ' ?> This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=314260.0 Interested to find out why this code doesn't seem to properly send the attachment.. it's driving my insane ? Code: [Select] <?php //define the receiver of the email $to = 'youraddress@example.com'; //define the subject of the email $subject = 'Test email with attachment'; //create a boundary string. It must be unique //so we use the MD5 algorithm to generate a random hash $random_hash = md5(date('r', time())); //define the headers we want passed. Note that they are separated with \r\n $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; //add boundary string and mime type specification $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; //read the atachment file contents into a string, //encode it with MIME base64, //and split it into smaller chunks $attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); //define the body of the message. ob_start(); //Turn on output buffering ?> --PHP-mixed-<?php echo $random_hash; ?> Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hello World!!! This is simple text email message. --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: 7bit <h2>Hello World!</h2> <p>This is something with <b>HTML</b> formatting.</p> --PHP-alt-<?php echo $random_hash; ?>-- --PHP-mixed-<?php echo $random_hash; ?> Content-Type: application/zip; name="attachment.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment <?php echo $attachment; ?> --PHP-mixed-<?php echo $random_hash; ?>-- <?php //copy current buffer contents into $message variable and delete current output buffer $message = ob_get_clean(); //send the email $mail_sent = @mail( $to, $subject, $message, $headers ); //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" echo $mail_sent ? "Mail sent" : "Mail failed"; ?> I'm trying to after submission
1. create a csv
2. insert record into db
3. send email that's created in form submission - $msg.
4. send email with attachment to only the email I specify (if possible)
if not attach it to the email that's created at submission.
I've search and search and found different methods but doesn't work with my code.
I kept 3 lines at the top but can't get them to work ... either I don't get an email after submission or don't get an attachement.
Can some one help?
<?php $random_hash = md5(date('r', time())); $csvString = "..."; // your entire csv as a string $attachment = chunk_split(base64_encode($csvString)); $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { "First Name Required"; } if(empty($_POST['lastName'])) { "Last Name Required"; } if(empty($error)) { $to = "$to"; $subject = 'The Form'; $headers = "MIME-Version: 1.0 \r\n"; $headers .= "Content-Type: text/html; \r\n" ; $msg .="<html> <head></head> <body> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td>This is the email sent.</td></tr> </table> </body> </html>"; include('con.php'); $con = mysqli_connect($host,$user,$pass,$dbName); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"thetable"); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'"; $result = mysqli_query($con,$sql); if(($result->num_rows)>= 1) { $theerror = "You exist"; } else { $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'"; $success = "Sent ... Insert it!!!"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } $result = @mail($to, $subject, $msg, $headers); } mysqli_close($con); { } } } ?> Edited by barkly, 27 October 2014 - 02:59 PM. I would like to store PDF file into mysql (this part works) and then send it as email attachment and it should be retrieved from mysql table. Here's the code I have for now, but what it gives me is 0bytes large PDF file Saving PDF to mysql (it works), because size of blob in mysql table is OK. $fp = fopen('generated.pdf', 'r'); $content = fread($fp,filesize('generated.pdf')); $content = addslashes($content); fclose($fp); $DB->Query('insert into pdf_files (pdf_file, name) values ("'.$content.'", "'.$name.'")'); And here's the mailing part <?php $query = "SELECT name, pdf_file FROM pdf_files $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array ( $result)) { $fileContent =$row['pdf_file']; $fileName=$row['name']; } $fileatt = $fileContent; // getting file $fileatt_type ="application/pdf"; //type of file $fileatt_name = "attachment.pdf"; // name $fileatt_size = $fileSize; $email_from = "dont@have.it"; // mail from $email_subject = "Testtt"; // subject $email_message = "Testtt.<br>"; $email_message .= "Testtt.<br>"; // Message $email_to = $mail_user; // users mail $headers = "From: ".$email_from; $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "Testtt.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n"; $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data .= "\n\n" . "--{$mime_boundary}--\n"; $ok = @mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "<font face=verdana size=2><center>Mail was sent</center>"; } else { die("Error!"); } ?> 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> 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.. 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 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'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> 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; 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 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 |