when echoing renamed file its showing single character - php

I am slowly working on a image uploader, and wondering why when echoing my renamed files, its giving me a single character instead of the whole thing.
Any reason it would be doing that?
It does tho, successfully upload the image as a phil_546d196082606.jpg with a different number for each image
Here is my code
<?php
if (isset($_POST['addpart'])) {
$image = $_FILES['images']['tmp_name'];
$name = $_POST['username'];
$i = 0;
foreach ($image as $key) {
$fileData = pathinfo(basename($_FILES["images"]["name"][$i]));
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . $fileName);
copy("image/" . $fileName, "image_thumbnail/" . $fileName);
$i++;
}
echo 'Uploaded<br>';
$fileName1 = $fileName[0];
$fileName2 = $fileName[1];
$fileName3 = $fileName[2];
echo 'Main Image - '.$fileName1.'<br>';
echo 'Extra Image 1 - '.$fileName2.'<br>';
echo 'Extra Image 2 - '.$fileName3.'<br>';
echo '<hr>';
}
?>

$filename is a string and strings in php are arrays where each letter has an index $filename[o] is the first letter and so on.Use
$filename[]=$name .'_'. uniqid() . '.' . $fileData['extension'];

Try the below block of code
$fileName[] = $name .'_'. uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . end($fileName));
copy("image/" . end($fileName), "image_thumbnail/" . end($fileName));

$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
Filename is the string. It is : $name . number.
Like philip12345.
So if we have:
philip
012345
$fileName[0] = p
$fileName[1] = h
Also you overwrite filename in each loop. Try to save it to an array and print it, here is some code:
$fileNames = array();
foreach ($image as $key)
{
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
fileNames[$i] = $fileName;
}
echo $fileNames[0];
echo $fileNames[1];
echo $fileNames[2];
You could also use a foreach loop to go over the array with the filenames and print each element, this is cool because it will works with any number of images, not just 3:
foreach ($fileNames AS $key2)
{
echo ($key2);
}

Related

How to copy image from DB to new path

I'm trying to copy an image using the path which is stored in my DB. I tried this but it throws "Array To String Conversion" error. I've never dealt with this before. Here's my code.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));
You're attempting to convert an array from explode('.', $img_name); to a string in the final line.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name); // This is an array like ['image_name', 'ext]
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext[count($ext)-1])
); // You'll need to address the last item in the array by its index like this
That said, pathinfo(...) is the safer option here.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext
);
I think its a simple problem of using explode as it will return an array of strings based on the dividing parameter.
I'm not too savvy with OOP but I can suggest using str_replace or trim to remove the '.'s in the $img_name variable.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = str_replace('.',"",$img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));

Stored image in database doesn't show on page

Image is stored in database (as varchar(255)), but on page isn't shown.
This is code that stored image, and put's image in folder:
if (isset($_FILES["image"])) {
$title = date("dmyHms") . "_" . $_FILES["image"]["name"];
$path = "img/profile/" . $_POST["id"] . "_" . $title;
move_uploaded_file($_FILES["image"]["tmp_name"], $path);
}
And this is to display image:
foreach ($conn->results() as $conn):
$img = $_SERVER["CONTEXT_DOCUMENT_ROOT"] . $path . "img/profile" . $conn->id . "_" . $conn->image;
if (file_exists($img)) {
$image = $path . "img/profile/" . $conn->id . "_" . $conn->image;
} else {
$image = $path . "img/noimage.png";
}
<?php endforeach; ?>
When I print_r $img, it shows right path to image and still image is not displayed.
Display:
<?php echo $image; ?>
Where did you echoing your image? If it is inside foreach, you need to change your code little bit...
$image = '<img src="'.$path . "img/profile/" . $conn->id . "_" . $conn->image . '" />';
Hope, will work perfectly for you.... TQ
The following line is not correct:
foreach ($conn->results() as $conn):
Don't overwrite $conn. Change the variable to something different like $result

PHP rename fails but file_exists is true

I'm trying to rename all files in a folder, I want the last character before the extension to be removed.
This is the code I'm using:
$sql = 'SELECT * FROM tblphotoseries WHERE photoSerieID = ' . mysql_real_escape_string($photoSerieID) . ' AND FKuID = ' . $_SESSION['uID'];
if($series = GetFromDB($sql)){
foreach ($series as $serie){
$path = '../uploads/' . $serie["FKcatID"] . '/' . $_SESSION['uCode'] . '/' . $serie["seriesCode"] . '';
}
$files = scandir($path);
foreach($files as $file) {
if($file != ".." && $file != "."){
$new_name = explode(".", $file);
$ext = $new_name[1];
$new_name = $new_name[0];
$new_name[strlen($new_name) - 1] = "";
$new_name = $new_name . "." . $ext;
$new_name = (string)$new_name;
echo $file . " -> " . $new_name . "\n\r";
clearstatcache();
if(file_exists($path . '/' . $file)){
echo "file_exists \n\r";
clearstatcache();
if(rename($path . '/' . $file, $path . '/' . $new_name)){
echo "rename successful \n\r";
}else{
echo "rename failed \n\r";
}
}
}
}
}
This outputs the following:
AA04a_.jpg -> AA04a.jpg
file_exists
rename failed
AA04b_.png -> AA04b.png
file_exists
rename failed
AA04c_.png -> AA04c.png
file_exists
rename failed
Can anyone spot what's going wrong here? Privileges are ok, I've tried chmod 0777 on the file before renaming as well, without success.
Thanks,
Rik
SOLVED:
$new_name[strlen($new_name) - 1] = "";
had to be replaced by
$new_name = substr_replace($new_name, '', strlen($new_name) - 1, 1);

Rename a file if already exists - php upload system

I this PHP code:
<?php
// Check for errors
if($_FILES['file_upload']['error'] > 0){
die('An error ocurred when uploading.');
}
if(!getimagesize($_FILES['file_upload']['tmp_name'])){
die('Please ensure you are uploading an image.');
}
// Check filesize
if($_FILES['file_upload']['size'] > 500000){
die('File uploaded exceeds maximum upload size.');
}
// Check if the file exists
if(file_exists('upload/' . $_FILES['file_upload']['name'])){
die('File with that name already exists.');
}
// Upload file
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], 'upload/' . $_FILES['file_upload']['name'])){
die('Error uploading file - check destination is writeable.');
}
die('File uploaded successfully.');
?>
and I need to act like a "windows" kind of treatment for existing files - I mean the if the file exists, i want it to be changed to the name of the file with the number 1 after it.
for example: myfile.jpg is already exists, so if you'll upload it again it will be myfile1.jpg, and if myfile1.jpg exists, it will be myfile11.jpg and so on...
how can i do it? i tried some loops but unfortunately without success.
You could do something like this:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
// add a suffix of '1' to the file name until it no longer conflicts
while(file_exists($name . '.' . $extension)) {
$name .= '1';
}
$basename = $name . '.' . $extension;
To avoid very long names, it would probably be neater to append a number, e.g. file1.jpg, file2.jpg etc:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$increment = ''; //start with no suffix
while(file_exists($name . $increment . '.' . $extension)) {
$increment++;
}
$basename = $name . $increment . '.' . $extension;
You uploaded a file called demo.png.
You tried to upload the same file demo.png and it got renamed to demo2.png.
When you try to upload demo.png for 3rd time, it gets renamed to demo1.png once again and replaces the file you upload in (2).
so you won't find demo3.png
For user6930268;
i think your code should be:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$dirname = pathinfo($_FILES['file_upload']['name'], PATHINFO_DIRNAME);
$dirname = $dirname. "/";
$increment = ''; //start with no suffix
while(file_exists($dirname . $name . $increment . '.' . $extension)) {
$increment++;
}
$basename = $name . $increment . '.' . $extension;
$resultFilePath = $dirname . $name . $increment . '.' . $extension);
Here is a my function i'm using. It will generate file (1).txt , file (2).txt , file ...
function getFilePathUnique($path) {
while ($this->location->fileExists($path)) {
$info = pathInfo($path);
//extract the current number of file
preg_match("/\([0-9]+\)$/",$info["filename"], $number);
$number = str_replace(["(" , ")"] , ["" , ""] , $number[0]);
//remove the old number
$info["filename"] = trim(preg_replace( "/\([0-9]+\)$/" , "" , $info["filename"] ));
//append new number
$info["filename"] .= " (" . (++$number) . ")";
//build path
$path = ($info["dirname"] != "." ? $info["dirname"]: "" ).
$info["filename"] . "." . $info["extension"];
}
return $path;
}

php check file name exist, rename the file

How do I check if file name exists, rename the file?
for example, I upload a image 1086_002.jpg if the file exists, rename the file as 1086_0021.jpg and save, if 1086_0021.jpg is exist, rename 1086_00211.jpg and save , if 1086_00211.jpg is exist, rename 1086_002111.jpg and save...
Here is my code, it only can do if 1086_002.jpg exist, rename the file as 1086_0021.jpg, maybe should do a foreach, but how?
//$fullpath = 'images/1086_002.jpg';
if(file_exists($fullpath)) {
$newpieces = explode(".", $fullpath);
$frontpath = str_replace('.'.end($newpieces),'',$fullpath);
$newpath = $frontpath.'1.'.end($newpieces);
}
file_put_contents($newpath, file_get_contents($_POST['upload']));
Try something like:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
Why not just append a timestamp onto the filename? Then you won't have to worry about arbitrarily long filenames for files which have been uploaded many times.
I hope this helps
$fullPath = "images/1086_002.jpg" ;
$fileInfo = pathinfo($fullPath);
list($prifix, $surfix) = explode("_",$fileInfo['filename']);
$x = intval($surfix);
$newFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $prifix. "_" . str_pad($x, 2,"0",STR_PAD_LEFT) . $fileInfo['extension'];
while(file_exists($newFile)) {
$x++;
$newFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $prifix. "_" . str_pad($x, 2,"0",STR_PAD_LEFT) . $fileInfo['extension'];
}
file_put_contents($newFile, file_get_contents($_POST['upload']));
I hope this Helps
Thanks
:)
I feel this would be better. It will help keep track of how many times a file with the same name was uploaded. It works in the same way like Windows OS renames files if it finds one with the same name.
How it works: If the media directory has a file named 002.jpg and you try to upload a file with the same name, it will be saved as 002(1).jpg Another attempt to upload the same file will save the new file as 002(2).jpg
Hope it helps.
$uploaded_filename_with_ext = $_FILES['uploaded_image']['name'];
$fullpath = 'media/' . $uploaded_filename_with_ext;
$file_info = pathinfo($fullpath);
$uploaded_filename = $file_info['filename'];
$count = 1;
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/' . $uploaded_filename
. '(' . $count++ . ')'
. '.' . $info['extension'];
}
$image->save($fullpath);
You can change your if statement to a while loop:
$newpath = $fullpath;
while(file_exists($newpath)) {
$newpieces = explode(".", $fullpath);
$frontpath = str_replace('.'.end($newpieces),'',$fullpath);
$newpath = $frontpath.'1.'.end($newpieces);
}
file_put_contents($newpath, file_get_contents($_POST['upload']));

Categories