Rename File before Storing in Server PHP - 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.

Related

How to copy an image from one folder to other in php

I have a image named xyz. Besides this file named xyz has unknown extension viz jpg,jpeg, png, gif etc. I want to copy this file from one folder named advertisers/images to other folder publishers/images in my website cpanl. How to do this with php. Thanks in advance.
You can use copy function:
$srcfile = 'source_path/xyz.jpg';
$dstfile = 'destination_path/xyz.jpg';
copy($srcfile, $dstfile);
You should write your code same as below:
<?php
$imagePath = "../Images/somepic.jpg";
$newPath = "../Uploads/";
$ext = '.jpg';
$newName = $newPath."a".$ext;
$copied = copy($imagePath , $newName);
if ((!$copied))
{
echo "Error : Not Copied";
}
else
{
echo "Copied Successful";
}
?>
Use copy() function
copy('advertisers/images/xyz.png','publishers/
images/xyz.png');
Change the file extension, whatever it is.
If you don't know the extension, go with the wildcard. It will give you the array of all the files matching with the wildcard.
$files = glob('advertisers/images/xyz.*');
foreach ($files as $file) {
copy($file,'publishers/images/'.$file);
}

How to increment a value without any for loop but based on number of times the file is run in PHP

I have a script which, when it runs, creates a new file in some directory. While creating a new file it checks if the file exists:
If it exists it should append 1 to the file name
If another file has same name it should increment and append 2.
$filecount = 0;
if (! file_exists ( SOME_DIR . $fileName )) {
echo "not there";
//so save normally
} else {
echo "there";
$fileName = $fileName."_" .$file_count++.".txt";
// save with number at the end
}
Currently, when the file is run multiple times it is only saving with number for the first time, as the variable $filecount is again set to 0.
Is there any work around to increment filename when its name is repeated?
You can do like this
<?php
define('SOME_DIR', '');
$fileName = 'file';
if (! file_exists ( SOME_DIR . $fileName.'.txt' )) {
echo "not there";
//so save normally
}
else{
$files = glob(SOME_DIR.$fileName.'_*.txt');
$counter = count($files)+1;
echo "there";
$fileName = $fileName."_" .$counter.".txt";
echo $fileName;
// save with number at the end
}
Tested, working well for me
You need to store somewhere the number of runs of your script. If you are already writing files I would use an plain text file to store the number of runs.
Other options is to use a timestamp as file name deduplicator.
define('SOME_DIR', __DIR__ . '/');
$basename = 'test.txt';
$path = SOME_DIR . $basename;
// Consider clearing stat cache before using `file_exists` and similar
// functions that run `stat`, or `lstat` system calls under the hood.
clearstatcache(true, $path);
if (file_exists($path)) {
$filename = pathinfo($basename, PATHINFO_FILENAME);
$ext = pathinfo($basename, PATHINFO_EXTENSION);
$files = glob(SOME_DIR . "${filename}_[0-9]*.${ext}", GLOB_BRACE);
$basename = sprintf(
'%s_%d.%s',
$filename,
(count($files) + 1),
$ext
);
$path = SOME_DIR . $basename;
}
// Replace with your logic
touch($path);

auto increment number within filename

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 !

Php file upload strange behaviour, occasionally upload is empty

I use this script to upload files via POST from my android app to my server. 95% of the time it works ok, but sometimes the upload folder of my clients is empty. The file is sent definitely, because I get the name and phone numbers (without a file selected the app will not pass any data), but the uploaded file is not written to disk on the server. I am not an expert in php, maybe I have missed something:
My upload php script:
$file_path = "uploads/{$_POST['name']}/";
if (!file_exists("uploads/{$_POST['name']}")) {
mkdir("uploads/{$_POST['name']}", 0777, true);
} else {
echo 'folder already exists!';
}
$newfile = $_POST['name'] . "_" . date('m-d_H-i-s') . '.zip';
$filename = $file_path . $newfile;
if(!file_exists($filename)) {
if(move_uploaded_file($_FILES['zipFile']['tmp_name'], $filename)) {
echo "success";
}
} else {
echo 'file already exists';
}

failure to upload multiple images using move_upload_file

I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path

Categories