473,383 Members | 1,874 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

upload file and rename

anfetienne
424 256MB
ive got an upload file form and it can have as many fields as a user wants to add images but say the user accidently pushes submit and the images upload (they are renamed as 1.jpg, 2.jpg, 3.jpg etc etc) but the user still wants to upload more images.....is it possible for php to read a directory and check what the filenames are and then renamed all extra images that are uploaded starting from the next digit?

so if there is already a 1.jpg and a 2.jpg once more pictures are uploaded it starts from 3.jpg and so forth....ive tried looking for something like this but dont know where to start.

thanks
Apr 4 '09 #1
48 2620
Markus
6,050 Expert 4TB
Here's something to get you started:

readdir() - read to documentation!
You'll probably also need to explode() the file name to get the name minus it's extension.

Theory:
  1. Loop through the directory's files using readdir(),
  2. Determine whether you are at the end of the directory (I'll let you figure this out as a little brain-workout),
  3. find the number in the files name,
  4. increment the number to use as your next file name.

- mark.
Apr 4 '09 #2
anfetienne
424 256MB
ok thanx markus....once ive gotta tester ill come back for more advice......thanks again
Apr 4 '09 #3
Markus
6,050 Expert 4TB
@anfetienne
No problem, anfetienne.

- mark.
Apr 4 '09 #4
anfetienne
424 256MB
ok ive got to the point where i can open a directory and list all files in the directory and strip off the .jpg......i used a similar code to rename files and move them.....i haven't finished building it as I am restructure all my coding to suit this. but based on what you showed me the cide i need to use for starters is this

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. if ($handle = opendir('.')) {
  3.     while (false !== ($file = readdir($handle))) {
  4.         if ($file != "." && $file != "..") {
  5.             echo "$file\n";
  6.         }
  7.     }
  8.     closedir($handle);
  9. }
  10. ?> 
  11.  
from here i have no idea on how to get the php to detect what number the last uploaded image is on and then how to get that into a variable
Apr 6 '09 #5
anfetienne
424 256MB
my guess was to try get it into an array so its read to the last value and then add onto that but that attempt failed.....i was nowhere close to it lol
Apr 6 '09 #6
Markus
6,050 Expert 4TB
Assuming your files are in the format x.jpg (x being a number), you can explode() the file name using '.jpg' as your needle.

Expand|Select|Wrap|Line Numbers
  1. $file = "12.jpg";
  2.  
  3. $file = explode(".jpg", $file);
  4.  
  5. // $file is now an array.
  6. // $file[0] holds the number 12
  7.  
Apr 6 '09 #7
anfetienne
424 256MB
so to add the extra numbers ontop would i use?

$i=1;

$file[0].$i++
Apr 6 '09 #8
Markus
6,050 Expert 4TB
Something like below:

Expand|Select|Wrap|Line Numbers
  1.  
  2. $num;
  3.  
  4. while( /* read directory */ )
  5. {
  6.     // Do explode.
  7.     $num = $file[0];
  8. }
  9.  
  10. // Loop has ended. Increment $num by 1 for new number.
  11. ++$num;
  12.  
  13.  
Apr 6 '09 #9
anfetienne
424 256MB
ahhhhhh i see what you are getting at......

so lastly could i use ++$num like this?

(rename($pathA.$filename, $pathB.++$num.'.jpg')
Apr 6 '09 #10
Markus
6,050 Expert 4TB
@anfetienne
Sure, but be careful: ++ increments the variable, so multiple calls to ++$num may confuse you on the output.

Expand|Select|Wrap|Line Numbers
  1.  
  2. $i = 9;
  3.  
  4. echo ++$i; // ouput: 10.
  5. echo ++$i; // output: 11.
  6.  
  7.  
Apr 6 '09 #11
anfetienne
424 256MB
would you recommend me using echo to make sure that ++$num outputs as it should?
Apr 6 '09 #12
anfetienne
424 256MB
this is the code i have made to test this....i add to images and it increments fine to show the number 3 but if i add anymore images it doesn't detect them and continue incrementing.

Expand|Select|Wrap|Line Numbers
  1. <?
  2. $path="upload/test/";
  3. $num;
  4.  
  5. if ($handle = opendir($path)) {
  6.    while (false !== ($file = readdir($handle))) {
  7.     if ($file != "." && $file != "..") {
  8.  
  9.  
  10.             $file = explode(".jpg", $file);
  11.             $num = $file[0];
  12.  
  13.        }
  14.    }
  15.  
  16. }
  17. closedir($handle);
  18.  
  19. ++$num;
  20.  
  21. echo $num;
  22. ?>
  23.  
Apr 7 '09 #13
anfetienne
424 256MB
any ideas where ive gone wrong anyone?
Apr 7 '09 #14
Atli
5,058 Expert 4TB
Hi.

Before you take this any further, let me offer an alternate solution (or two)...

First, if you want to name the files "1.jpg", "2.jpg", etc...
Rather than count the actual files, it would be much much easier to simply store the last used number in a file (or preferably, a database), so that you could just read that number and increment it.

The file_get_contents and file_put_contents can make that very easy.

Second...
Unless you actually have a good reason to do so, storing the images as "1.jpg", "2.jpg", etc... isn't all that efficient.
It requires that you go out of your way to count the images and make sure there are no collisions.

I would recommend using a timestamp instead, which would require minimal tampering with to ensure that there are no collisions.

PHP has the function time, or even better, microtime, which will give you the current UNIX timestamp in seconds or milliseconds, respectively.

So, to generate a unique name, you could simply do:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $name = microtime(true) . mt_rand(1,999) . ".jpg";
  3. ?>
Which would give you:
- 1239162720.1566.jpg

And even if you happen to have two requests processed at the very same millisecond, there is only 1:999 chance that you get a collision. (Which can easily be increased)
Apr 8 '09 #15
anfetienne
424 256MB
it has to be incremented as 1.jpg 2.jpg etc...

if using a database to store the last is an easier way to do this then i shall but how is it possible to store the last number into a database?

also how can i get readdir to only check for the last file within a directory?
Apr 8 '09 #16
anfetienne
424 256MB
ahhhh i guess i wouldn't need to get it to check the directory......if i get it to check the database against the corresponding ID and check the value that is there and go forth from there......

thanks for the idea atli....i will work on that now and get back to you with the results and my final code
Apr 8 '09 #17
anfetienne
424 256MB
i have worked on the coding and i got it to work the way i need it to using the database as suggested but i have a problem with the sql coding

i use this code to recall what i need it to from the database

Expand|Select|Wrap|Line Numbers
  1. "SELECT * FROM imgUpload WHERE tempID='{$random_digit}'"
  2.  
and i get this error

Error in query:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE tempID='1371669417'' at line 5
Apr 8 '09 #18
Markus
6,050 Expert 4TB
@anfetienne
What data type is tempID? If it's an integer, you cannot use quotes.
Apr 8 '09 #19
anfetienne
424 256MB
ok so i should set it to text.....thanks
Apr 8 '09 #20
Markus
6,050 Expert 4TB
@anfetienne
No, you should just remove the quotes from around the variable in your SQL.
Apr 8 '09 #21
anfetienne
424 256MB
ok so
"SELECT * FROM imgUpload WHERE tempID='{$random_digit}'"

becomes
"SELECT * FROM imgUpload WHERE tempID={$random_digit}"
Apr 8 '09 #22
Markus
6,050 Expert 4TB
@anfetienne
That's correct, anfetienne.

- mark.
Apr 8 '09 #23
anfetienne
424 256MB
thanks for the advice
Apr 8 '09 #24
waqasahmed996
160 100+
Sir i think we can use quotes even if data type is interger.

we can write like this

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM `table` WHERE abc='1'
  2.  
even if abc has interger data type

am i right?
Apr 9 '09 #25
Dormilich
8,658 Expert Mod 8TB
that depends on the database driver. best practice is to quote it accordingly.

if you're using Prepared Statements the quoting is done internally.
Apr 9 '09 #26
anfetienne
424 256MB
well i have tried

"SELECT * FROM imgUpload WHERE tempID= '{$random_digit}' "

"SELECT * FROM imgUpload WHERE tempID={$random_digit}"

and

"SELECT * FROM imgUpload WHERE tempID= $random_digit "

and i still get the same error message. it has completely got me stumped
Apr 9 '09 #27
Dormilich
8,658 Expert Mod 8TB
is there any error number given? you could look this up to get an idea what kind of error it is.
Apr 9 '09 #28
Markus
6,050 Expert 4TB
What is the table structure?
Apr 9 '09 #29
anfetienne
424 256MB
two columns .... tempID and lastDigit

it's really simple
Apr 9 '09 #30
Dormilich
8,658 Expert Mod 8TB
what data type have these columns? (like VARCHAR, INT(5), …)
Apr 9 '09 #31
anfetienne
424 256MB
tempID INT(15), lastDigit INT(5)
Apr 9 '09 #32
Dormilich
8,658 Expert Mod 8TB
has there been a MySQL Error Number?
Apr 9 '09 #33
anfetienne
424 256MB
it inserts data to the db perfectly fine but when it checks if there is already a row that has the tempID it comes up with that error message
Apr 9 '09 #34
anfetienne
424 256MB
no mysql error numbers just the message of "Error in query:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE tempID='1371669417'' at line 5"
Apr 9 '09 #35
Dormilich
8,658 Expert Mod 8TB
if you want to overwrite data, use the UPDATE keyword.
Apr 9 '09 #36
anfetienne
424 256MB
i have......

Expand|Select|Wrap|Line Numbers
  1. $query="
  2.  
  3. UPDATE imgUpload SET 
  4.  
  5.             lastDigit='{$i}', 
  6.  
  7.             WHERE tempID='$random_digit'";
  8.  
  9. }
Apr 9 '09 #37
Dormilich
8,658 Expert Mod 8TB
does it work now?
...
Apr 9 '09 #38
anfetienne
424 256MB
its always been there from the beginning......i've been getting the error even though i have used this......the only thing i can think of is im using the wrong sql to update a table that has only two columns i.e.

"SELECT * FROM imgUpload WHERE tempID= '{$random_digit}' "
Apr 9 '09 #39
Markus
6,050 Expert 4TB
Strange strange.

For some reason, PHP does not show the error number associated with the error (security reasons, maybe?).

Anyway, if you have phpMyAdmin installed, run the same query through it's SQL interface. It will give you the error number (eg #1064) and the error text.
Apr 9 '09 #40
anfetienne
424 256MB
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"SELECT * FROM imgUpload WHERE tempID= '{$random_digit}' "' at line 1
Apr 9 '09 #41
Dormilich
8,658 Expert Mod 8TB
1064 is a syntax error like parenthesis or quotation mark mismatch.
Apr 9 '09 #42
anfetienne
424 256MB
@anfetienne
as stated in a previous post of mine
Apr 9 '09 #43
Markus
6,050 Expert 4TB
@anfetienne
Can you show how you're doing this via PHP.
Apr 9 '09 #44
anfetienne
424 256MB
Expand|Select|Wrap|Line Numbers
  1. $username="tempsUser";
  2. $password="auction";
  3. $database="auctionTemps";
  4.  
  5.  
  6.  
  7. // OPEN CONNECTION ---> 
  8. mysql_connect(localhost,$username,$password);
  9.  
  10. @mysql_select_db($database) or die( "Unable to select database");
  11.  
  12. // Select column 1 from table name where column name = $your_var.
  13.  
  14. // If mysql_query returns false, we'll die with the error.
  15. $result = mysql_query("SELECT * FROM imgUpload WHERE tempID = {$random_digit}");
  16.  
  17. // If a there is a match
  18. if ( mysql_num_rows( $result ) > 0 )
  19. {
  20. $row = mysql_fetch_array( $result );
  21.  
  22. //fill in details about the path
  23. $path="upload/imgtemp/m/$random_digit/";
  24. $pathA="upload/$random_digit/images/";
  25.  
  26. //variable used for the name of each file
  27. $i=$row['lastDigit'];
  28.  
  29. $od = opendir($path);
  30. while (false !== ($filename = readdir($od)))
  31. {
  32.     //you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
  33.     if($filename != '.' && $filename != '..' && !is_dir($path.$filename))
  34.     {
  35.         //we give files a name - here we use increasing numbers for jpg files:
  36.         if(rename($path.$filename, $pathA.$i++.'.jpg'))
  37.         echo 'Renamed file '.$filename.'<br />';
  38.     }
  39. }
  40.  
  41. closedir($od);
  42.  
  43.  
  44. //fill in details about the path
  45. $pathT="upload/imgtemp/t/$random_digit/";
  46. $pathF="upload/$random_digit/images/";
  47. //variable used for the name of each file
  48. $i=$row['lastDigit'];
  49.  
  50. $odT = opendir($pathT);
  51. while (false !== ($filename = readdir($odT)))
  52. {
  53.     //you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
  54.     if($filename != '.' && $filename != '..' && !is_dir($pathT.$filename))
  55.     {
  56.         //we give files a name - here we use increasing numbers for jpg files:
  57.         if(rename($pathT.$filename, $pathF.$i++.'b.jpg'))
  58.         echo 'Renamed file '.$filename.'<br />';
  59.  
  60.  
  61.     }
  62. }
  63. closedir($odT);
  64.  
  65.  
  66.  
  67. $query="
  68.  
  69. UPDATE imgUpload SET 
  70.  
  71.             lastDigit='{$i}', 
  72.  
  73.             WHERE tempID= '{$random_digit}' ";
  74.  
  75. }
  76.  
  77. else
  78. {
  79. //fill in details about the path
  80. $path="upload/imgtemp/m/$random_digit/";
  81. $pathA="upload/$random_digit/images/";
  82. //variable used for the name of each file
  83. $nw=1;
  84.  
  85. $od = opendir($path);
  86. while (false !== ($filename = readdir($od)))
  87. {
  88.     //you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
  89.     if($filename != '.' && $filename != '..' && !is_dir($path.$filename))
  90.     {
  91.         //we give files a name - here we use increasing numbers for jpg files:
  92.         if(rename($path.$filename, $pathA.$nw++.'.jpg'))
  93.         echo 'Renamed file '.$filename.'<br />';
  94.     }
  95. }
  96.  
  97. closedir($od);
  98.  
  99.  
  100. //fill in details about the path
  101. $pathT="upload/imgtemp/t/$random_digit/";
  102. $pathF="upload/$random_digit/images/";
  103. //variable used for the name of each file
  104. $nw=1;
  105.  
  106. $odT = opendir($pathT);
  107. while (false !== ($filename = readdir($odT)))
  108. {
  109.     //you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
  110.     if($filename != '.' && $filename != '..' && !is_dir($pathT.$filename))
  111.     {
  112.         //we give files a name - here we use increasing numbers for jpg files:
  113.         if(rename($pathT.$filename, $pathF.$nw++.'b.jpg'))
  114.         echo 'Renamed file '.$filename.'<br />';
  115.     }
  116. }
  117. closedir($odT);
  118.  
  119. $query="INSERT imgUpload (tempID,lastDigit)
  120.  
  121.         VALUES(    
  122.             '$random_digit',
  123.             '$nw')";
  124.  
  125. }
  126.  
  127. //////-----> 
  128. $result=mysql_query($query) or die("Error in query:".mysql_error()); 
  129. //if ($result) 
  130.     //echo mysql_affected_rows()." row inserted into the database effectively."; 
  131.  
  132. //  CLOSE CONNECTION ---> 
  133. mysql_close(); 
  134.  
  135. /////////////////////////////////////////////////////////////////////////////////// 
  136.  
Apr 9 '09 #45
Markus
6,050 Expert 4TB
There shouldn't be a comma on line 71 :D

Is that what is giving the error, or the query at the beginning of the file?
Apr 9 '09 #46
anfetienne
424 256MB
just like to say thank you for the help......always appreciated
Apr 21 '09 #47
Markus
6,050 Expert 4TB
@anfetienne
You have returned.

You're welcome.

- mark.
Apr 21 '09 #48
anfetienne
424 256MB
yeah not been too well.....only just recovered.....thanks again though
Apr 21 '09 #49

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Stephane | last post by:
Hello, I need to allow an end user to upload video files on a server and in the same time to put the file name and a few infos in a database. It must be very simple for the end user, and...
1
by: Amy Kimber | last post by:
Hello all, ok, I have a file upload secton to my site, two pages, one with a form and one that does the uploading.... some files upload fine, other don't an exe of 300k will upload, but a...
3
by: Amy Kimber | last post by:
Hello, I have a file upload page, and I've had it working fine, it was beautiful :-) Anyway, the powers that be moved hosts... and it doesn't work now. The file name is correct, the directory...
3
by: dave | last post by:
Hello there, I am at my wit's end ! I have used the following script succesfully to upload an image to my web space. But what I really want to be able to do is to update an existing record in a...
2
by: Simon | last post by:
I'm following microsoft's guide on how to upload files. I want to upload AND rename the file... Anyone have some tips for how to do that? Thanks ------ If Not File1.PostedFile Is Nothing And...
4
by: Matt Jensen | last post by:
Howdy I've got a rather strange issue occuring. I used forms based .NET authentication, although I'm also setting some session variables when people login. However, I've found when people use...
0
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted...
2
by: will.smothers | last post by:
All, I have two Windows Server 2003 boxes running IIS 6.0 webservers that host our proxy pac file. These two servers are behind a network load- balancer and house our corporation's Proxy PAC file....
1
by: ogo796 | last post by:
hi everyone i upload files everyday to the server using a php coded program , it works from other computers but not on the others. Could this be a problem with http headers of specific computers...
1
by: achotto | last post by:
hi, i try to upload a multiple image files. after that i will rename the files name. the problem is when i upload a 2 or more same files name exp-goal.jpg, it will return "files already exist". ok...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.