auto increment number within filename - php

My users can upload profile pictures, one by one, but as often as they want.
Let's assume user 1 uploads an image, this code will store it to my uploads-folder:
<?php
$fileData = pathinfo(basename($_FILES["fileToUpload"]["name"]));
$fileName = 'user_id_#1#_profilepic_#' . uniqid() . '#.' . $fileData['extension'];
$target_path = "uploads/" . $fileName;
while(file_exists($target_path)) {
$fileName = 'user_id_#1#_profilepic_#' . uniqid() . '#.' . $fileData['extension'];
$target_path = ($_SERVER['DOCUMENT_ROOT'] . "uploads/" . $fileName);
}
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_path)) {
echo "The image was successfully uploaded. <a href='index.php'>Add another image</a>";
}
else {
echo "There was an error uploading the file, please try again!";
}
?>
This uniqid() needs to be replaced, because it's a nightmare to find the images later on in the right order.
I want the images - after uploading - to look like this:
user_id_#1#_profilepic_#1#.jpg
user_id_#1#_profilepic_#2#.jpg
user_id_#1#_profilepic_#3#.png
user_id_#1#_profilepic_#4#.gif
user_id_#1#_profilepic_#5#.jpg
and so on...
How can I do this? I don't have any ideas so far.

You can increment by file number in your directory (not recommended if your user can delete his pictures) :
$total_files = count(glob("./*",GLOB_BRACE)); // count files in directory
echo $total_files;
OR :
use a text file where you record a number.
For exemple :
You user upload a file :
Get the current number in the text file -> add +1 and rename the file with this number -> record the new number in the txt file.
The best way should be a unique ID from database record but you maybe not use a DB.
I hope that help you.
Have a nice day !

Related

Upload images with random name and also delete older image from the directory

I am trying to upload an image with a random name, also when I update the image, I want the previous image to be deleted.
Code below:
$banner=$_FILES ['banner']['name'];
$upload="../image/banner/";
$target_file = $upload.basename($_FILES["banner"]["name"]);
$imagefiletype= pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["banner"]["tmp_name"], $target_file );
Any help will be appreciated.
When update your new images at that time first store old image name in variable. after update true then delete old image in your directory using "unlink" function.
$old_image = "xyz" // store old image name
after update query success
unlink('../image/banner/'.$old_image); // delete old image in your directory
You can do it like this.
$path = 'image/folder/'; $unique_name=time().uniqid(rand());
$File_with_location = $path . $unique_name . '.' . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
$filename = $_FILES["img"]["tmp_name"];
move_uploaded_file($filename, $File_with_location);
for deleting old image you can use this
$path = './root/home/folder/file.jpg';
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}

Detecting if user is uploading the same image

I have a form that contains an image upload and an input text box. The user will be able to upload an image and enter text without refreshing the page using Ajax. The image will be relayed to PHP and PHP will handle what to do with the image. My problem is that for the first time the user uploads an image, it'll be checked if the same image name is on the server or not. If it is, the image name will get a uniqid() and then will be uploaded. But what if the user changes the data in the text box field, but keeps the image? Then that image will be uploaded again with a uniqid() since it's already on the server. I've tried solving this using my current code for the image handling:
PHP
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
if (isset($_SESSION["size"]))
{
$prevSize = $_SESSION["size"];
if (filesize($prevSize) != filesize($size))
{
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
}
}
else
{
$_SESSION["size"] = $size;
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
}
move_uploaded_file($tempName, $target_file);
Unfortunately, this code isn't working like I want it to. If I upload the same image twice in a row, in the same session, it doesn't override my previous image. Instead, it puts it on the server with a uniqid name. What am I doing wrong? And if there's a better way in solving this, I'd love to know!
What you can do is whenever someone uploads an image, store a hash of the image, encrypt it and store it in the database on the image row.
From now on, whenever someone uploads an image run a query like this:
SELECT COUNT(*) FROM images WHERE hash = $hash then in an if statement check if the returned value is bigger than 0, if it is, do what you need to do without re-uploading the image, and if it is 0, then upload your image and proceed
I chose a user avatar upload for this example. I'm not sure what your image is, but the workflow should be similar. No duplicate avatars will be copied to the image path.
function get_avatar_filename($filename) {
// only generate an avatar filename if the mimetype matches
switch (mime_content_type($filename)) {
case 'image/jpeg':
return sprintf('%s.jpg', hash_file('md5', $filename));
case 'image/gif':
return sprintf('%s.gif', hash_file('md5', $filename));
case 'image/png':
return sprintf('%s.png', hash_file('md5', $filename));
// otherwise the user uploaded a non-supported image
// return the default image
default:
return 'default-avatar.jpg';
}
}
function upload_avatar($avatarPath, $filename) {
// get the avatar filename
$f = get_avatar_filename($filename);
// copy the file to $avarPath only if the file doesn't already exist
if (!file_exists("{$avatarPath}/{$f}")) {
move_uploaded_file($filename, "{$avatarPath}/{$f}");
}
// return the avatar filename
return $f;
}
Now you can use these functions when you process the user form submission
// process user form submission ...
// ...
$filename = upload_avatar(
$_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/",
$_FILES['user_avatar']['tmp_name']
);
// save the avatar location for the user ...
// or whatever
$user->setAvatar($filename);
$user->save();
If the user uploads a non-supported image type, they will just be assigned default-avatar.jpg which is a file that should exist in your images directory.

How do I get a File Extension in PHP if I only have the File Name?

I have the path to an image file /files/uploads/1 but as you can see, I don't have an extension so I can't display the image. How can I get the extension of the file so I can display it? Thanks!
EDIT: Here is come code I have tried. BMP, PNG, JPG, JPEG and GIF are the only possible extensions, but $path ends up never getting assigned a value.
$exts = array('bmp','png','jpg','jpeg','gif');
foreach ($exts as $ext) {
if (file_exists("/files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
Personally, I had a problem where I had an unnecessary slash (/) before my path in the file_exists check, but the solution to the question is still the same.
$exts = array('bmp','png','jpg','jpeg','gif','swf','psd','tiff','jpc','jp2','jpx','jb2','swc','iff','wbmp','xbm','ico');
foreach ($exts as $ext) {
if (file_exists("files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
You don't need a file extension to show an image.
<img src="/files/uploads/1">
Will show the image. It's the same way the placehold.it images work
<img src="http://placehold.it/350x150">
First of all , I think when you get the file name for the image that means no need to add extension , so you have the file name and image folder
it should simply look like this :
$fullpath = ('uploadword/'.$filename);
// then call it
<img src='".$fullpath."'>
The normal scenario to upload all the images in specific folder then get the filename and save it in data base
move_uploaded_file($file_tmp,"upload/".$filename);
Some professional make it more sophisticated to make filename unique ,because they expected some duplicated values and many reasons , here is one simple technique :
$anynameorfunction = "";// random number etc...
$newname = $anynameorfunction.$filename;
move_uploaded_file($file_tmp,"upload/".$newname);
So, when they call it again it should be simple like this
$fullpath = ('uploadword/'.$newname);
// then call it
<img src='".$newname."'>
This is in very simple way and i wish you get what i mean

Upload the same file into multiple folders

I have an uploading form, and when i select the file,i need it to be uploaded in multiple folders.Any ideas how to do that? I've tried with a loop like the following one:
foreach($_POST['check'] as $check){
move_uploaded_file($_FILES['doc']['tmp_name'], $target_path);
chmod($target_path,0777);
}
But it only upload once.Any ideas please?
After uploading, copy the file from the target path to the other paths with copy().
foreach($_POST['check'] as $check){
move_uploaded_file($_FILES['doc']['tmp_name'], $target_path);
chmod($target_path,0777);
// and now...
copy($target_path, $target_path_2);
copy($target_path, $target_path_3);
// etc...
}
By the way, setting 0777 for permissions generally is unnecessary and a bad idea. You want anyone to upload files and let any user execute them? That's the way to start giving anyone full control over your machine.
Also, are you sure that you need the file on multiple places? Why not have one common storage folder and create symbolic links to it? But that depends on your setup, of course.
Upload once and then just copy() it.
$i = 0;
foreach($_POST['check'] as $check){
$basePath = "/var/www/html/more/phpexm/";
$target_path = $basePath . $check;
if (!file_exists($target_path)){
mkdir($target_path, 0777);
}
if ($i == 0){
$sFileNameTmp = $_FILES['doc']['tmp_name'];
$sFileName = $_FILES['doc']['name'];
move_uploaded_file($sFileNameTmp, $target_path . '/' . $sFileName);
$sFirstFileUploaded = $target_path;
}
else{
copy ($sFirstFileUploaded . '/' . $sFileName, $target_path . '/' . $sFileName);
}
$i++;
}

Rename File before Storing in Server PHP

I need to know code how to rename file before it gets uploaded to my server in php script.Ill post the php code of mine.
I need it because I am uploading an image from phone and I don't want it to be overwritten.
Can I achieve that?
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
For renaming file in Android, you can do :
String file_path = <file path off your existing file you want to rename>
File from = new File(file_path,"from.txt");
File to = new File(file_path,"to.txt");
from.renameTo(to);
This code will work for both file stored in internal or external storage. Just for writing to external storage remember you need to have android.permission.WRITE_EXTERNAL_STORAGE to be added to your Android manifest.
write your code like below.
$filename = $_FILES['upload_file']['name'];
$newname = 'alteredtext'.$filename; // you can also generate random number and concat on start.
$tmp_path = $_FILES['upload_file']['tmp_name'];
if(move_uploaded_file($mp_path, $newname)) {
echo "success";
} else{
echo "fail";
}
You don't need to use the name passed in the $_FILES array when moving the file. You can create any name you want (assuming the path is valid) and pass it as the second argument of move_uploaded_file. If you want a semi-random name, you could generate a random number and then hash it or something to create the filename.
If you want to check first, if the file exists, then rename it to have a numeric suffix, you could do this:
<?php
$base_path = "uploads/";
$file_path = $base_path . basename( $_FILES['uploaded_file']['name']);
if(file_exists($file_path)) {
$ctr = 0;
do { // increment an index to append to the filepath
$ctr++;
$file_path = $base_path . basename( $_FILES['uploaded_file']['name']) . "_$ctr";
} while(file_exists($file_path));
}
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
The above snippet will keep incrementing until it finds a filename that doesn't exist. Of course, you'd want to add some bounds and error checking, while the above snippet demonstrates the concept, it isn't entirely production ready.

Categories