Reputation: 51
My problem recently arose when I tried to change save a picture to a location with a different name. eg. saving a picture called hello.jpg to a location called /sets/1/09092014-1.jpg
Here is my code:
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$today = date("dmY");
$Title = $today."-".$x.".jpg";
$x ++;
$url = "/Sets/".$desired_dir."/".$Title;
$query = "INSERT INTO photo(name, url, album) VALUES('$Title', '$url', '$set')";
$result = mysql_query($query) OR DIE(mysql_error());
if($file_size > 10485760){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
if(is_dir("Sets/"."$desired_dir")==false){
mkdir("Sets/"."$desired_dir", 0700);
}
if(is_dir("Sets/"."$desired_dir/".$Title)==false){
rename ($file_tmp , $Title );
move_uploaded_file($file_tmp, "/Sets/$desired_dir/$file_tmp");
}else{
}
not including the DB stuff at the top.
I spent a while on this, and found that i may need to use the rename() method to rename the file before i save it, which I tried, but once again it didnt work.
When run, it adds the info to the database, creates the folder to be put in if not present, but then does not add the files.
Thanks, Waq
Upvotes: 0
Views: 101
Reputation: 1071
According to your explanation you should not need to use $_SERVER["DOCUMENTE_ROOT"] at all. You just need to pay attention to file structure and your code. Here is corrected code with comments:
if(empty($errors)==true){
// $desired_dir didn't need parenthesis, buts its ok to use them
// Remember directories and file names are case sensitive: Sets is != to sets
if(is_dir("Sets/".$desired_dir)==false){
// If your server is picky you can try 0755 here and change it lower later
mkdir("Sets/".$desired_dir, 0700);
}
// ERROR your if test is supplying a file but you were testing for directory
// $Title is a file not a directory
if(is_file("Sets/".$desired_dir."/".$Title)==false){
rename ($file_tmp,$Title);
// You just renamed $file_tmp so change the blow code to use the right file
// Because of the rename $file_tmp no longer exists
move_uploaded_file($Title,"Sets/$desired_dir/$Title");
}else{
// It already exists, handle it
}
Upvotes: 1