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
48 2620
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: - Loop through the directory's files using readdir(),
- Determine whether you are at the end of the directory (I'll let you figure this out as a little brain-workout),
- find the number in the files name,
- increment the number to use as your next file name.
- mark.
ok thanx markus....once ive gotta tester ill come back for more advice......thanks again
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 -
<?php
-
if ($handle = opendir('.')) {
-
while (false !== ($file = readdir($handle))) {
-
if ($file != "." && $file != "..") {
-
echo "$file\n";
-
}
-
}
-
closedir($handle);
-
}
-
?>
-
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
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
Assuming your files are in the format x.jpg ( x being a number), you can explode() the file name using '.jpg' as your needle. -
$file = "12.jpg";
-
-
$file = explode(".jpg", $file);
-
-
// $file is now an array.
-
// $file[0] holds the number 12
-
so to add the extra numbers ontop would i use?
$i=1;
$file[0].$i++
Something like below: -
-
$num;
-
-
while( /* read directory */ )
-
{
-
// Do explode.
-
$num = $file[0];
-
}
-
-
// Loop has ended. Increment $num by 1 for new number.
-
++$num;
-
-
ahhhhhh i see what you are getting at......
so lastly could i use ++$num like this?
(rename($pathA.$filename, $pathB.++$num.'.jpg')
@anfetienne
Sure, but be careful: ++ increments the variable, so multiple calls to ++$num may confuse you on the output. -
-
$i = 9;
-
-
echo ++$i; // ouput: 10.
-
echo ++$i; // output: 11.
-
-
would you recommend me using echo to make sure that ++$num outputs as it should?
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. -
<?
-
$path="upload/test/";
-
$num;
-
-
if ($handle = opendir($path)) {
-
while (false !== ($file = readdir($handle))) {
-
if ($file != "." && $file != "..") {
-
-
-
$file = explode(".jpg", $file);
-
$num = $file[0];
-
-
}
-
}
-
-
}
-
closedir($handle);
-
-
++$num;
-
-
echo $num;
-
?>
-
any ideas where ive gone wrong anyone?
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: -
<?php
-
$name = microtime(true) . mt_rand(1,999) . ".jpg";
-
?>
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)
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?
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
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 -
"SELECT * FROM imgUpload WHERE tempID='{$random_digit}'"
-
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
@anfetienne
What data type is tempID? If it's an integer, you cannot use quotes.
ok so i should set it to text.....thanks
@anfetienne
No, you should just remove the quotes from around the variable in your SQL.
ok so
"SELECT * FROM imgUpload WHERE tempID='{$random_digit}'"
becomes
"SELECT * FROM imgUpload WHERE tempID={$random_digit}"
Sir i think we can use quotes even if data type is interger.
we can write like this -
SELECT * FROM `table` WHERE abc='1'
-
even if abc has interger data type
am i right?
that depends on the database driver. best practice is to quote it accordingly.
if you're using Prepared Statements the quoting is done internally.
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
is there any error number given? you could look this up to get an idea what kind of error it is.
What is the table structure?
two columns .... tempID and lastDigit
it's really simple
what data type have these columns? (like VARCHAR, INT(5), …)
tempID INT(15), lastDigit INT(5)
has there been a MySQL Error Number?
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
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"
if you want to overwrite data, use the UPDATE keyword.
i have...... - $query="
-
-
UPDATE imgUpload SET
-
-
lastDigit='{$i}',
-
-
WHERE tempID='$random_digit'";
-
-
}
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}' "
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.
#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
1064 is a syntax error like parenthesis or quotation mark mismatch.
@anfetienne
Can you show how you're doing this via PHP.
-
$username="tempsUser";
-
$password="auction";
-
$database="auctionTemps";
-
-
-
-
// OPEN CONNECTION --->
-
mysql_connect(localhost,$username,$password);
-
-
@mysql_select_db($database) or die( "Unable to select database");
-
-
// Select column 1 from table name where column name = $your_var.
-
-
// If mysql_query returns false, we'll die with the error.
-
$result = mysql_query("SELECT * FROM imgUpload WHERE tempID = {$random_digit}");
-
-
// If a there is a match
-
if ( mysql_num_rows( $result ) > 0 )
-
{
-
$row = mysql_fetch_array( $result );
-
-
//fill in details about the path
-
$path="upload/imgtemp/m/$random_digit/";
-
$pathA="upload/$random_digit/images/";
-
-
//variable used for the name of each file
-
$i=$row['lastDigit'];
-
-
$od = opendir($path);
-
while (false !== ($filename = readdir($od)))
-
{
-
//you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
-
if($filename != '.' && $filename != '..' && !is_dir($path.$filename))
-
{
-
//we give files a name - here we use increasing numbers for jpg files:
-
if(rename($path.$filename, $pathA.$i++.'.jpg'))
-
echo 'Renamed file '.$filename.'<br />';
-
}
-
}
-
-
closedir($od);
-
-
-
//fill in details about the path
-
$pathT="upload/imgtemp/t/$random_digit/";
-
$pathF="upload/$random_digit/images/";
-
//variable used for the name of each file
-
$i=$row['lastDigit'];
-
-
$odT = opendir($pathT);
-
while (false !== ($filename = readdir($odT)))
-
{
-
//you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
-
if($filename != '.' && $filename != '..' && !is_dir($pathT.$filename))
-
{
-
//we give files a name - here we use increasing numbers for jpg files:
-
if(rename($pathT.$filename, $pathF.$i++.'b.jpg'))
-
echo 'Renamed file '.$filename.'<br />';
-
-
-
}
-
}
-
closedir($odT);
-
-
-
-
$query="
-
-
UPDATE imgUpload SET
-
-
lastDigit='{$i}',
-
-
WHERE tempID= '{$random_digit}' ";
-
-
}
-
-
else
-
{
-
//fill in details about the path
-
$path="upload/imgtemp/m/$random_digit/";
-
$pathA="upload/$random_digit/images/";
-
//variable used for the name of each file
-
$nw=1;
-
-
$od = opendir($path);
-
while (false !== ($filename = readdir($od)))
-
{
-
//you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
-
if($filename != '.' && $filename != '..' && !is_dir($path.$filename))
-
{
-
//we give files a name - here we use increasing numbers for jpg files:
-
if(rename($path.$filename, $pathA.$nw++.'.jpg'))
-
echo 'Renamed file '.$filename.'<br />';
-
}
-
}
-
-
closedir($od);
-
-
-
//fill in details about the path
-
$pathT="upload/imgtemp/t/$random_digit/";
-
$pathF="upload/$random_digit/images/";
-
//variable used for the name of each file
-
$nw=1;
-
-
$odT = opendir($pathT);
-
while (false !== ($filename = readdir($odT)))
-
{
-
//you can add any type of filenames you wish to skip (for instance Thumbs.db on windows)
-
if($filename != '.' && $filename != '..' && !is_dir($pathT.$filename))
-
{
-
//we give files a name - here we use increasing numbers for jpg files:
-
if(rename($pathT.$filename, $pathF.$nw++.'b.jpg'))
-
echo 'Renamed file '.$filename.'<br />';
-
}
-
}
-
closedir($odT);
-
-
$query="INSERT imgUpload (tempID,lastDigit)
-
-
VALUES(
-
'$random_digit',
-
'$nw')";
-
-
}
-
-
//////----->
-
$result=mysql_query($query) or die("Error in query:".mysql_error());
-
//if ($result)
-
//echo mysql_affected_rows()." row inserted into the database effectively.";
-
-
// CLOSE CONNECTION --->
-
mysql_close();
-
-
///////////////////////////////////////////////////////////////////////////////////
-
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?
just like to say thank you for the help......always appreciated
yeah not been too well.....only just recovered.....thanks again though
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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....
|
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...
|
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...
|
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...
|
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,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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$) {
}
...
|
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...
|
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
|
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...
|
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...
|
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...
| |