I have this script:
UPLOAD MULTIPLE FILES - PIECE OF CODE
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 0) {
}
else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
$dest = $path . $uniq_name; //FULL DESTINATION
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
$count++;
}
}
}
Please tell me how to insert into my mysql database all the photo names, in the PHOTOS field, separated by a comma.
When I'm writing the 2 lines code:
$a = "INSERT INTO dbu.dbu_data(photos) VALUES ('$uniq_name')";
mysql_query($a);
IT INSERTS A TABLE ROW FOR EACH PHOTO THAT WAS UPLOADED AND I DON'T WANT THAT.
$delimiter = ",";
$str = '';
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 0) {
// surely your move logic needs to go here
} else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
$dest = $path . $uniq_name; //FULL DESTINATION
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
$count++;
if (strlen($str)) {
$str .= $delimiter;
}
$str .= $dest;
}
}
}
if (strlen($str)){
$a = "INSERT INTO dbu.dbu_data(photos) VALUES ('" . mysql_real_escape_string($str) . "')";
mysql_query($a);
}
Related
I have a folder containing several photos all in .jpg
The name they should all have is STYLE_COLOR-n.jpg for example K14700_7132-6.jpg because I made a script that deletes all the photos greater than -6.jpg.
My problem is that I have photos that are badly renamed, i.e. they have an underscore at the end instead of the dash like :
K14700_7132_6.jpg
Some also have a dash on both like this:
K14700-7132_6.jpg
And so my delete script doesn't work if the pictures don't all have the same rename...
Is it possible to automatically replace all the dashes and underscores that are bad to have this format on all my folder STYLE_COLOR-n.jpg?
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file)
{
if (!in_array($file,array(".","..")))
{
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
$underscore = explode("_", $filename);
// echo $underscore[0]."<br>"; //KA0710
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6)
{
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
}
else
{
}
}
}
echo "Deleted photos !";
?>
Sure, this is the part you'll add to that code:
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
Note - this will permanently rename files (that need it) so BEFORE you run this in production, please test for the old/new rename arguments just to be safe!
Here is the whole enchilada
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
if (!in_array($file,array(".",".."))) {
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
// first fix the format
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
$underscore = explode("_", $filename);
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6) {
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
} else {
}
}
}
echo "Deleted photos !";
?>
I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.
So i have more than one image to upload, each one being a new line in my mysql table:
I use this code for file input with name="profile"
if (isset($_FILES['profile']) === true) {
if (empty($_FILES['profile']['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png')
$file_name = $_FILES['profile']['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $_FILES['profile']['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, 1, $file_temp, $file_extn);
header('Location: galery.php');
exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
(change_image) function makes this MySql query
$sql = "UPDATE `art_$id` SET `path` = \"" . $file_path . "\" WHERE `row` = " . (int)$row;
But i want to repeat this code for profil1, profil2... and change accordingly the row (example : profil4 would change row 4 ), without having to repeat this code for each file='name'.
How would i go about that?
Irrespective of your form have "how many fields as of file and what they are named??" . Following code will upload them one by one ..Check it
$rowid=1;
foreach($_FILES as $key=>$image_uploaded)
{
if (isset($image_uploaded[$key]) === true) {
if (empty($image_uploaded[$key]['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png')
$file_name = $image_uploaded[$key]['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $image_uploaded[$key]['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, $rowid++, $file_temp, $file_extn);
//change as you need
header('Location: galery.php');
exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
}
Thanks for your answer, as i have a specific submit button for each form and don't wont to validate all forms at once i used this code :
for ($row = 1; $row <= 9; $row++) {
if (isset($_FILES["profile" . $row]) === true) {
if (empty($_FILES["profile" . $row]['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png');
$file_name = $_FILES["profile" . $row]['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $_FILES["profile" . $row]['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, $row, $file_temp, $file_extn);
//header('Location: galery.php');
//exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
}
}
}
}
And for file input i use name="profile1",name="profile2",....,name="profile9"(for this case).
Here is the the code which will add 1,2,3 at end of the image file name
Bellow function will check the file exist in dir or not and return new file name now you can use the function before change_image function call and get new file name and pass new name in change_image for save.
function getFileName($fileName, $file_extn){
$fileNameWithoutExt = pathinfo($fileName, PATHINFO_FILENAME);
$i = 1;
while(!file_exists('image/art/' . $fileName)){
$fileName = $fileNameWithoutExt . $i . "." . $file_extn;
$i++;
}
return $fileName;
}
I am uploading multiple images from a single input and rename all uploaded files. My problem is; I need to display all uploaded images with separate variables
For example:
If user upload 3 images, i need to echo as
$upload1 = 1st file name
$upload2 = 2nd file name
$upload3 = 3rd file anme
No of images uploaded (upload number of file)
Here is my current code:
<?php
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
print_r($errors);
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key+1) . " = $row[0];";
eval ($codestr);
} else {
$codestr = '$file' . ($key+1) . " = NULL;";
eval ($codestr);
}
}
}
echo $file1;
echo $file2;
echo $file3;
echo $file4;
echo $file5;
?>
I tried this and I get the error
Parse error: syntax error, unexpected 'png' (T_STRING) in C:\Users\logon\Documents\NetBeansProjects\upload file rename single and multiple\multiple file rename\method 2\process.php(43) : eval()'d code on line 1
What am I doing wrong? can some one help me
I think the " = $row[0];" on line 42 might not do what you want it to do. Because of the double quotes, the value of the variable $row[0] will be printed in the code.
The code running through the eval will look something like this:
$file0 = FILENAME.png;
Instead of this:
$file0 = $row[0];
To solve the problem you could simply turn line 42 into the following:
$codestr = '$file' . ($key+1) . ' = $row[0];';
More information about the difference between single and double quotes: http://php.net/manual/en/language.types.string.php
Edit: For the correct names of the files you could change $_FILES['files']['name'][$key] to $file_name . $sExt. Hope it helps!
I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!
PHP
$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$actual_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Here's a minor modification that I think should do what you want:
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Inspired from #Jason answer, i created a function which i deemed shorter and more readable filename format.
function newName($path, $filename) {
$res = "$path/$filename";
if (!file_exists($res)) return $res;
$fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Example:
$name = "foo.bar";
$path = 'C:/Users/hp/Desktop/ikreports';
for ($i=1; $i<=10; $i++) {
$newName = newName($path, $name);
file_put_contents($newName, 'asdf');
}
New version (2022):
function newName2($fullpath) {
$path = dirname($fullpath);
if (!file_exists($fullpath)) return $fullpath;
$fnameNoExt = pathinfo($fullpath,PATHINFO_FILENAME);
$ext = pathinfo($fullpath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Usage:
for ($i=1; $i<=10; $i++) {
$newName = newName2($fullpath);
file_put_contents($newName, 'asdf');
}
There are several ways for renaming image in PHP before uploading to the server.
appending timestamp, unique id, image dimensions plus random number etc.You can see them all here
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
function rename_appending_unique_id($source, $tempfile){
$target_path ='uploads-unique-id/'.$source;
while(file_exists($target_path)){
$fileName = uniqid().'-'.$source;
$target_path = ('uploads-unique-id/'.$fileName);
}
move_uploaded_file($tempfile, $target_path);
}
if(isset($_FILES['upload']['name'])){
$sourcefile= $_FILES['upload']['name'];
tempfile= $_FILES['upload']['tmp_name'];
rename_appending_unique_id($sourcefile, $tempfile);
}
Check more image renaming tactics
I checked SO and found a nice C# answer here, so I ported it for PHP:
['extension' => $extension] = pathinfo($filePath);
$count = 0;
while (file_exists($filePath) === true) {
if ($count === 0) {
$filePath = str_replace($extension, '[' . ++$count . ']' . ".$extension", $filePath);
} else {
$filePath = str_replace("[$count].$extension", '[' . ++$count . ']' . ".$extension", $filePath);
}
}