Hi: I'm trying to use get_next_file dreamincode snippet to prevent an overwrite of an uploaded file.
I have a script "save_html_output_2_2.php5" which combines the code to prevent overwrite with code to upload file contents. Instructions for the snippet say that I only have to pass the directory and file name to the function.
Here is the code for "save_html_output_2_2.php5" script:
CODE
<?php
function get_next_filename($directory, $filename) {
if(!file_exists($dir . $filename)) {
return $filename;
}
$x = 0;
$fex = explode(".", $filename);
$newfile = $fex[0] . "({$x})" . "." . $fex[1];
while(file_exists($dir . $newfile)) {
$x++;
$newfile = $fex[0] . "({$x})" . "." . $fex[1];
}
return $newfile;
}
get_next_filename("http://www.headacheanalysis.com/practice", "saved_test.html");
ob_start();
$content=file_get_contents('http://www.headacheanalysis.com/patient_query_lastinsert_KPC_1.php5');
// Save the test result to a file
$fn = "saved_test.html";
$fh = fopen($fn, 'w') or die("can't open file");
if(file_put_contents("saved_test.html", $content)) {
echo "Success";
}
else {
echo "Failed to save file";
}
echo $content;
fclose($fh);
ob_end_clean();
?>
If the file to be uploaded, "saved_test.htm" does not exist on the server the above code successfully uploads it on the first call. However, if the uploaded file exists, the portion of dreamincode snippett does not rename the uploaded file with an extension, and the new version of the file is not uploaded.
I have tried running the dreamincode snippet file by itself after the uploaded file "save_test.html" has been uploaded and it fails to add an extension to the uploaded file.
Here is the snippet code modified to check for file "save_test.html" on server.
Need help in figuring out what I'm doing wrong.
Many thanks.
Here is the snippet get_next_file code.
CODE
<?php
//get net file snippett
function get_next_filename($directory, $filename) {
if(!file_exists($dir . $filename)) {
return $filename;
}
$x = 0;
$fex = explode(".", $filename);
$newfile = $fex[0] . "({$x})" . "." . $fex[1];
while(file_exists($dir . $newfile)) {
$x++;
$newfile = $fex[0] . "({$x})" . "." . $fex[1];
}
return $newfile;
}
get_next_filename("http://www.headacheanalysis.com/practice", "saved_test.html");
?>