I'm using the mailReader script found here: https://github.com/stuporglue/mailreader
I am trying to copy the file(s) after upload to another folder.
The file(s) upload correctly to the folder where the script resides.
When I try to run a copy command, the filename variable is empty.
Here is the portion of the code I am working with: The last three lines are what I added.
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I receive confirmation by email that the file(s) are uploaded, then another email with the error message.
Warning: copy(/attachments/W7652222-546/1453406138_residential-print_from_td.pdf): failed to open stream: No such file or directory in /home/myhost/public_html/mailreader/mailReader.php on line 224
224 being the line number of my added code.
The source filename is missing from in front of /attachments...
Anyone have any thoughts?
$name is defined in the while loop and may not be accessible on the upper scopes my suggestion is to change your code to this:
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
$name = '';
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I hope this solves your problem
I ended up defining a constant of email_id in the private function saveToDb, then running a script after everything else is finished to query the table using the email_id and looping through the records moving the files.
Related
I'm trying to make a "send email" form which uploads files to a folder before the email is sent. The path to the files are then shown in the email, but if the files DO exist i don't want them to be overwritten, but i want to have a number added.
I have composed this tiny code, but it doesn't work!
The error says:
Parse error: syntax error, unexpected '$name_of_uploaded_file' (T_VARIABLE) in /customers/8/5/6/HOMEPAGE/httpd.www/php/mailtest2.php on line 49
The script below now upload a file if the file does not exist. If the file does exist nothing happens. The script ends at it should.
The script have been modified to what caused it not to ad "_1" to filename and save file in folder. Now it saves the file in folder and comes up with error: Error while copying the uploaded file
Can someone please explain to me what i do wrong?
Now all code is shown to debug this:
<?php
//Uploaded file 1
//Settings
$max_allowed_file_size = 2000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "pdf");
error_reporting(E_ALL);
//Upload folder
//name also used later on mail
$name = $_POST['name'];
$d = date('d.m.y');
$varfoldername = "../receivedfiles/$name$d/";
if(!is_dir($varfoldername)) {
mkdir($varfoldername , 0777 , true);
}
$upload_folder = $varfoldername;
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//Validations
//----- Check if files exists and adds _X to it -----
$original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME);
$extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION);
$FileCounter = 0;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(move_uploaded_file ( $tmp_path,$path_of_uploaded_file ))
{
die("Error while copying the uploaded file");
}
}
//Validate size requirements
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
if($size_of_uploaded_file > $max_allowed_file_size )
{
die("Fejl: Filen er for stor");
}
//------ Validate the file extension -----
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
die("The uploaded file is not supported file type. \n Send venligst filer af følgende type: .implode(',',$allowed_extensions)");
}
$email = $_POST['email'];
$phone = $_POST['phone'];
$call = $_POST['call'];
$company = $_POST['company'];
$type = $_POST['type'];
$adress = $_POST['adress'];
$hesteid = $_POST['hesteid'];
$hestenavn = $_POST['hestenavn'];
$message = $_POST['message'];
$areacode = $_POST['areacode'];
$land = $_POST['land'];
$formcontent=" Fra: $company \n Navn: $name \n Adresse: $adress , $areacode \n Land: $land \n Telefon: $phone \n Ringes op: $call \n Type: $type \n Hoppens navn og ID: $hestenavn , $hesteid \n Besked: \n $message \n Vedhæftede filer: \n $path_of_uploaded_file";
$recipient = "simon#secret.dk";
$subject = "Besked fra hjemmesiden";
$mailheader = "Fra: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header('Location: thank_you.shtml');
?>
You need to use the . character to concatenate (stick together) different PHP variables, so:
while (file_exists($varfoldername$name_of_uploaded_file ))
will return you a parse error, because you need to tell PHP you want to string the two variables together, so instead use the . and write:
while (file_exists($varfoldername.$name_of_uploaded_file))
You may also need to add a / directory seperator between the two variables, but that's an issue not directly related to your current problem. But it's useful to print $varfoldername.$name_of_uploaded_file and see if it is the correct filepath layout (has all the / etc. )
Further Work
Hi again I just modified the question. Found two stupid bugs. Now the script runs without error but doesn't add "_1" to the filename. – Simon Jensen
Rearrange your code as such:
$FileCounter = 0;
$original_name_of_file = $name_of_uploaded_file;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
What happened here:
PHP in the while loop is overwriting the $name_of_uploaded_file so that if you have a file_1.txt then the next file name in the loop will be file_1.txt_2.txt and you can see this overwrite is far from perfect, instead you need to save the Original file, and then overwrite the original concatenated with the increment value and then the .txt .
Your original value of $name_of_uploaded_file is not defined.
$FileCounter for clarity is incremented before being written into the string.
Your code of $FileCounter++ will not work because you have defined $FileCounter as a string by setting it in quote marks. I have removed the quotes so it is now identified by PHP as an integer.
Your file_exists call should not be in quotes as this is causing PHP extra, and needless work, and also will often confuse you as well as your IDE. The quotes in effect do:
PHP Logic: I found a quote, I will start a string structure, oh, this
part looks like a variable, I will stop the string structure, then
concatenate this variable value into the string strucuture, then
continue the string, oh, another variable, I will stop the string
structure, and then concatenate the second variable into this string,
then continue. I found another quote so string finished.
Which is a far larger load of work than clearly and concisely defining two variables concatenated with a . .
Complete Code:
$name = $_POST['name'];
$d = date('d.m.y');
/***
Ideally folders should NEVER be relative, always base them from the PHP server
root such as (example only), using $_SERVER['DOCUMENT_ROOT']:
$varfoldername = $_SERVER['DOCUMENT_ROOT']."/data/uploads/receivedfiles/".$name.$d."/";
***/
$varfoldername = "../receivedfiles/".$name.$d."/";
$upload_folder = $varfoldername;
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
$original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME);
$extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION);
$FileCounter = 0;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
/***
Now $name_of_uploaded_file will have the numerical appendage as needed.
***/
if(move_uploaded_file( $tmp_path , $varfoldername.$name_of_uploaded_file )){
print "file uploaded!";
}
IMPORTANT
Do not use copy, instead use PHP Move_upload_file :
if(!copy($tmp_path,$path_of_uploaded_file)){ ...
Becomes
if(move_uploaded_file ( $tmp_path , $path_of_uploaded_file )){ ...
There is not much need for using this long method when you could make a re-usable object out of it.
interface FileUploaderInterface
{
public function upload($path);
}
class FileUploader implements FileUploaderInterface
{
protected $File;
public function __construct($file)
{
$this->File = $file;
return $this;
}
public function upload($path)
{
if(file_exists($path.$this->File['name']))
{
$this->File["tmp_name"] = $this->File["name"] . '-' . time();
move_uploaded_file($this->File, $path . $this->File["name"]);
return false;
}
else
{
move_uploaded_file($this->File, $path . $this->File["name"]);
return true;
}
}
}
Can be used simply by using the require_once() and then this code:
$obj = new FileUploader($_FILES["fileToUpload"]);
if(!$obj->upload(dirname(__FILE__) . '/example/path/ect')) {
echo "File existed, we added the time onto the name";
}
PHP documentation says:
while (file_exists($varfoldername . $name_of_uploaded_file ))
Maybe you need a $varfoldername . '/' . $name_of_uploaded_file - best is if you could give us a var_dump of these two variables.
Running Apache 2.2 with PHP 5.3 on Windows 8. Trying to get the PHP class ImapMailbox to download attachments, but each time I getMail(), the attachments value is empty on every email that has attachments.
All the rest of the email info is downloaded correctly.
I've looked through the class code but can't identify where the problem might be.
Here is my current code:
$mailbox = new ImapMailbox('{testsite.com:110/pop3/novalidate-cert}INBOX', 'testemail#testsite.com', 'MyPaSs', ATTACH_DIR, 'utf-8');
$mails = array();
foreach($mailbox->searchMailbox('SUBJECT "test attach" SINCE "' . date('m/d/Y', strtotime('-1 week')) . '"') as $mailId) {
$mail = $mailbox->getMail($mailId);
$mails[] = $mail;
}
After dumping the $data var in getMail(), it appears there are attachments in winmail.dat format. The code cannot get to these because no attachmentId value is being assigned due to an empty 'ifid' value. Decoding the winmail.dat attachments can be done, but only if they are detected and written to file.
Any ideas how create a workaround in the ImapMailbox code for this?
Here is what I wrote that fixes this problem.
At the beginning of initMailPart() method, add the following:
static $altAttachmentId = 0;
At the end of the IF block for if($this->attachmentsDir) { add the following where the closing } bracket is:
} elseif (!empty($params['fileName']) || !empty($params['filename']) || !empty($params['name'])) { // Process attachments that are not inline.
// Check if need to decode TNEF (Winmail.dat) file.
if ($partStructure->ifsubtype && $partStructure->subtype == 'MS-TNEF') {
require_once 'path_to_your/tnef_decoder.php';
$Tnef = new tnef_decoder;
$un_tnef = $Tnef->decompress($data);
$attached_files = array();
foreach ($un_tnef as $f) {
if (!empty($f['name']) && !empty($f['stream'])) {
$attachment = new IncomingMailAttachment();
$attachment->id = $altAttachmentId;
$attachment->name = $f['name'];
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $f['name']);
$mail->addAttachment($attachment);
if (file_exists($attachment->filePath) && md5($f['stream']) != md5_file($attachment->filePath)) {
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $mail->id . '_' . $altAttachmentId . '_' . $f['name']);
}
file_put_contents($attachment->filePath, $f['stream']);
$altAttachmentId++;
}
}
} else {
if (!empty($params['filename'])) {
$fileName = $params['filename']; // Account for random camel-case mistake on element.
} elseif (!empty($params['fileName'])) {
$fileName = $params['fileName'];
} else {
$fileName = $params['name'];
}
$attachment = new IncomingMailAttachment();
$attachment->id = $altAttachmentId;
$attachment->name = $fileName;
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $mail->id . '_' . $altAttachmentId . '_' . $fileName);
$mail->addAttachment($attachment);
file_put_contents($attachment->filePath, $data);
$altAttachmentId++;
}
}
Note that you must include the tnef_decoder.php file found in the Roundcube Webmail package for the TNEF decoding to work. I got inspiration for the TNEF solution here.
This modification will process all TNEF encoded files in a Winmail.dat file and any other attachment that is not attached inline. Watch your memory usage on large files.
It also won't overwrite existing files that are the same name if they are not exactly the same.
I wonder whether someone may be able to help me please.
I'm using Aurigma's Image uploader software to allow users to upload images for locations they visit. The information is saved via the script shown below:
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';
require_once 'Includes/gallery_helper.php';
require_once 'ImageUploaderPHP/UploadHandler.class.php';
/**
* FileUploaded callback function
* #param $uploadedFile UploadedFile
*/
function onFileUploaded($uploadedFile) {
$packageFields = $uploadedFile->getPackage()->getPackageFields();
$username=$packageFields["username"];
$locationid=$packageFields["locationid"];
global $galleryPath;
$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
$absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;
if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
}
$locationfolder = $_POST['locationid'];
$locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
$dirName = $_POST['folder'];
$dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
if (!is_dir($absGalleryPath . $dirName)) {
mkdir($absGalleryPath . $dirName, 0777);
}
$path = rtrim($dirName, '/\\') . '/';
$originalFileName = $uploadedFile->getSourceName();
$files = $uploadedFile->getConvertedFiles();
// save converter 1
$sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
$sourceFile = $files[0];
/* #var $sourceFile ConvertedFile */
if ($sourceFile) {
$sourceFile->moveTo($absGalleryPath . $sourceFileName);
}
// save converter 2
$thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
$thumbnailFile = $files[1];
/* #var $thumbnailFile ConvertedFile */
if ($thumbnailFile) {
$thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
}
//Load XML file which will keep information about files (image dimensions, description, etc).
//XML is used solely for brevity. In real-life application most likely you will use database instead.
$descriptions = new DOMDocument('1.0', 'utf-8');
$descriptions->load($absGalleryPath . 'files.xml');
//Save file info.
$xmlFile = $descriptions->createElement('file');
$xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
$xmlFile->setAttribute('source', $sourceFileName);
$xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
$xmlFile->setAttribute('originalname', $originalFileName);
$xmlFile->setAttribute('thumbnail', $thumbnailFileName);
$xmlFile->setAttribute('description', $uploadedFile->getDescription());
//Add additional fields
$xmlFile->setAttribute('username', $username);
$xmlFile->setAttribute('locationid', $locationid);
$xmlFile->setAttribute('folder', $dirName);
$descriptions->documentElement->appendChild($xmlFile);
$descriptions->save($absGalleryPath . 'files.xml');
}
$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>
In additon to the original script I've added code that creates a folder, with it's name based on the current 'locationid'. This is shown below.
$locationfolder = $_POST['locationid'];
$locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $locationfolder);
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
What I like to incorporate, is a check that looks to see whether there is a folder already setup with the current 'locationid' value, if not create the folder. I'm ceratianly no expert in PHP, but I know that to check to see whether a file exists, the if(file exists....) can be used, but I just wondered whether someone could tell me please how I can implement this check for the folder name?
Many thanks
Chris
I think is_dir() is what you are looking for.
UPDATE:
The code you have:
if (!is_dir($absGalleryPath . $locationfolder)) {
mkdir($absGalleryPath . $locationfolder, 0777);
}
Does exactly what you want. It checks for the folder and if it does not exist then it creates one for you (with CHMOD 777). Don't see what your question is then...
I wonder whether someone could help me please.
I'm using Image Uploader from Aurigma, and to save the uploaded images, I've put this script together.
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';
require_once 'Includes/gallery_helper.php';
require_once 'ImageUploaderPHP/UploadHandler.class.php';
/**
* FileUploaded callback function
* #param $uploadedFile UploadedFile
*/
function onFileUploaded($uploadedFile) {
$packageFields = $uploadedFile->getPackage()->getPackageFields();
$userid = $packageFields["userid"];
$locationid= $packageFields["locationid"];
global $galleryPath;
$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
$absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;
if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
}
$dirName = $_POST['folder'];
$dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
if (!is_dir($absGalleryPath . $dirName)) {
mkdir($absGalleryPath . $dirName, 0777);
}
$path = rtrim($dirName, '/\\') . '/';
$originalFileName = $uploadedFile->getSourceName();
$files = $uploadedFile->getConvertedFiles();
// save converter 1
$sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
$sourceFile = $files[0];
/* #var $sourceFile ConvertedFile */
if ($sourceFile) {
$sourceFile->moveTo($absGalleryPath . $sourceFileName);
}
// save converter 2
$thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
$thumbnailFile = $files[1];
/* #var $thumbnailFile ConvertedFile */
if ($thumbnailFile) {
$thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
}
//Load XML file which will keep information about files (image dimensions, description, etc).
//XML is used solely for brevity. In real-life application most likely you will use database instead.
$descriptions = new DOMDocument('1.0', 'utf-8');
$descriptions->load($absGalleryPath . 'files.xml');
//Save file info.
$xmlFile = $descriptions->createElement('file');
$xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
$xmlFile->setAttribute('source', $sourceFileName);
$xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
$xmlFile->setAttribute('originalname', $originalFileName);
$xmlFile->setAttribute('thumbnail', $thumbnailFileName);
$xmlFile->setAttribute('description', $uploadedFile->getDescription());
//Add additional fields
$xmlFile->setAttribute('userid', $userid);
$xmlFile->setAttribute('locationid', $locationid);
$xmlFile->setAttribute('folder', $dirName);
$descriptions->documentElement->appendChild($xmlFile);
$descriptions->save($absGalleryPath . 'files.xml');
}
$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>
What I'd like to do is replace the files element of the filename and replace it with the username, so each saved folder and associated files can be indentified to each user.
I've added a username text field to the form which this script saves from
I think I'm right in saying that this is line that needs to change $descriptions->save($absGalleryPath . 'files.xml');.
So amongst many attempts I've tried changing this to $descriptions->save($absGalleryPath . '$username.xml, $descriptions->save($absGalleryPath . $username '.xml, but none of these have worked, so I'm not quite sure what I need to change.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
Many thanks
'$username.xml' will be interpreted as $username.xml, you need to use "$username.xml". Single quotes "disable" the variable use inside strings.
What you are tryiing can be a bad idea, as you are making so a username can't contain 'special characters' like "/". Perhaps is not a problem if you aready have a rule that stop "/" being part of a username.
I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'