Question

I am currently working on this project which requires me to make a function which dinamically decides the directory name and then creates a simple .txt file in that directory.

my code is as follows: ($destinatario is a string)

     $diretorio="../messages/".$destinatario;
if (is_dir($diretorio)) {
    ;
}else{
    mkdir($diretorio);
}
$path=$diretorio."/".$data.",".$assunto.",".$remetente.".txt";
$handle=fopen($path,'w+');

fwrite($handle, $corpo);

fclose($handle);

nevermind the portuguese, but the bottom line is that it should create a .txt file using the naming guidelines i've provided. The funny thing is that when i do this, php creates this weird file whose filename is "01.09.2010 04" (with no extension at all) which amounts to the first few characters of the actual filename i'd like to create...

edit($data is actually the output from a call to date("d.m.Y H:i"))

Was it helpful?

Solution

Per comment by OP:

[$data is] actually the output of a call to date("d.m.Y H:i")

The problem is the : character. (Still, there may be other illegal characters in the other parts composing the final file name.)


EDIT
The essence of the problem and solution is in the comments to @tchen's answer. Keep in mind that colon is a valid file name character on (some? all?) *nix platforms but is invalid on Windows.

OTHER TIPS

Make sure there's no bad characters at the end of $data. Call trim() on it.

If it's data taken from a file, it may have a '\r' or '\n' at the end of it.

Not related, but make sure your if statements don't have unused conditions:

if (!is_dir($diretorio)) {
    mkdir($diretorio);
}

This will also get rid of that blank line with a single terminator ;, I'm sure that isn't right.

Some ideas:

  • have you tried not using commas in the filename?
  • Have you checked the return value if fopen and fwrite?

Just to try to isolate the problem

also you can simplify to:

if (!is_dir($diretorio)) {
  mkdir($diretorio);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top