move_uploaded_file and the copy - php

I am trying to upload a tmp file and then copy it. But it is not appearing in the second folder, is there an overlay or something I have to watch?
$uploadPath = '/.../..../image/';
$uploadPathpreview = '/.../..../blog/';
if ($counter == 0){
$preview_file = $uploadPath . DS . 'preview_' . date("Ymd-Hi-") . $img_name;
$preview_file_save = $uploadPathpreview . DS . 'preview_' . date("Ymd-Hi-") . $img_name;
if(move_uploaded_file($tmp_name, $preview_file)){
$tmp = $preview_file;
$new = $preview_file_save;
}
copy($tmp,$new);
The file in image exists by the way. And I tried it without the if()

Related

Laravel 8 - Upload storage path changed, how to show old files?

In laravel 8, I updated the storage path for image uploads. It was app/violations/filename.jpeg
if( $request->hasfile('violationStatement') )
{
$file = $request->file('violationStatement');
$extension = $file->getClientOriginalExtension();
$filename = $violation->plateNumber . '-' . $violation->violationType . '.' . $extension;
$file->move('app/violations/', $filename);
$violation->violationStatement = $filename;
}
And it was updated to app/violations/speeding/Toyota/XXX-1234/11-June-2022/11-26 AM/filename.jpeg
if( $request->hasfile('violationStatement') )
{
$file = $request->file('violationStatement');
$extension = $file->getClientOriginalExtension();
$filename = 'violation-statement' . '-' . $violation->plateNumber . '-' . $violation->violationType . '.' . $extension;
$file->move('app/violations/' .
$violation->violationType . '/' .
$violation->carModel . '/' .
$violation->plateNumber . '/' .
Carbon::parse($violation->violationDateTime)->format('d-M-Y/H-i A'), $filename);
$violation->violationStatement = $filename;
}
The images are displayed in datatables, so obviously I'll have to change the image src to the new URL. When I do so, how can I also display the old images of the old directory?

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;
}

Warning: copy() [function.copy]: Filename cannot be empty

I'm uploading a .PDF and .ZIP file via a HTML form then passing it to my PHP script where the file is moved from the temp folder and placed in a specified folder. Now this works great on files under 2mb, anything over I will get the following error message:
Warning: copy() [function.copy]: Filename cannot be empty
The filename isn't empty and the code works fine for files under 2mb in size.
I checked my php.ini file in /etc/ folder (im running centos6.4) and in its config I have
upload_max_filesize = 50M
I'm thinking this is still a PHP config issue thats causing the error on files over 2mb, is there any other config I need to be looking at?
<?php
session_start();
$ref = $_POST['doc_ref'];
$rev = $_POST['doc_rev'];
$owner = $_POST['doc_owner'];
$contract = $_POST['contract'];
$cat = $_POST['cat'];
$type = $_POST['type'];
$pdf = $_FILES['pdf'];
$zip = $_FILES['zip'];
$pdf_name = $_FILES['pdf']['name'];
$content = $_POST['doc_content'];
$userid = $_SESSION['users_id'];
date_default_timezone_set('UTC');
$date = date_create();
// get the pdf from the form then remove the extension
$title = $_FILES["pdf"]["name"];
$title = pathinfo($title,PATHINFO_FILENAME);
$sth = "SELECT * FROM `contracts` WHERE `contracts_id`='$contract'";
$result = $conn->query($sth);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$contract_name = $row['contracts_name'];
$contract_prefix = $row['prefix'];
}
if ($contract_prefix)
{
if ($type === '1')
{
$zippath = "zips/" . $contract_prefix . "/" . $contract_name . "/Forms/";
$arcpath = "arc/" . $contract_prefix . "/" . $contract_name . "/Forms/";
$pdfpath = "pdfs/" . $contract_prefix . "/" . $contract_name . "/Forms/";
}elseif ($type === '2')
{
$zippath = "zips/" . $contract_prefix . "/" . $contract_name . "/Work Instructions And Process Flows/";
$arcpath = "arc/" . $contract_prefix . "/" . $contract_name . "/Work Instructions And Process Flows/";
$pdfpath = "pdfs/" . $contract_prefix . "/" . $contract_name . "/Work Instructions And Process Flows/";
}
}else
{
if ($type === '1')
{
$zippath = "zips/" . $contract_name . "/Forms/";
$arcpath = "arc/" . $contract_name . "/Forms/";
$pdfpath = "pdfs/" . $contract_name . "/Forms/";
}elseif ($type === '2')
{
$zippath = "zips/" . $contract_name . "/Work Instructions And Process Flows/";
$arcpath = "arc/" . $contract_name . "/Work Instructions And Process Flows/";
$pdfpath = "pdfs/" . $contract_name . "/Work Instructions And Process Flows/";
}
}
$pdfpath = $pdfpath . $_FILES["pdf"]["name"];
$zippath = $zippath . $_FILES["zip"]["name"];
// create archpath to store for later use
$arcpathfinal = $arcpath;
// append the current revision to the start of the zip files name for the arc
$arcpath = $arcpath . "Revision " . $rev . " - " . $_FILES["zip"]["name"];
//check the uploaded file is in PDF format and then move to correct directory
$allowed = array('pdf');
$pdf = $_FILES['pdf']['name'];
$ext = pathinfo($pdf, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'The file type must be a PDF!';
}else
{
// move zip and pdf into correct folders
move_uploaded_file($_FILES["pdf"]["tmp_name"], $pdfpath);
move_uploaded_file($_FILES["zip"]["tmp_name"], $zippath);
}
// make a copy of zip file into arc folder
copy($zippath, $arcpath);
//INSERTING INTO DATABASE CODE HERE
UPDATE
Ok I have been doing a bit of testing, the $_FILES array seems to be empty when the filesize is over 2MB, under 2MB the array returns the name, type, tmp_name, error, size as expected.
What would the reason be the $_FILES is empty with files over 2MB. Yes my upload_max_filesize is set higher than the file size and my post_max_size is set higher than my upload_max_filesize. Yes I have restarted Apache after making changes to the php.ini file
http://www.php.net/manual/en/ini.core.php#ini.post-max-size
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize.

Changing the filename of the uploaded file from 'filename' to 'filename(2)' if the uploaded file already exists in the destination folder

I'm currently getting to know more with uploadify, which by the way is what I'm using on my Wordpress plugin. I got the uploading of file correctly; it's job is to upload single .pdf files only. When I tried uploading the same file twice and checked the folder where the uploaded files will be stored, I only have a single file. I guess it's being overwritten knowing the file already exists on the folder. What bugs me is that how will I change the filename of the second uploaded file(the same file) such that it will result into 'filename(2)', 'filename(3)' and so on.
Here's my code, enlighten me on where should I start configuring on my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
$newTargetFile = $targetFolder.$name;
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
// i think somewhere here , will i put something, but what's that something?
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Change this:
$newTargetFile = $targetFolder.$name;
To this:
$i = 2;
list( $filename, $ext) = explode( '.', $name);
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$i . ')' . '.' . $ext;
}
Try this:
<?php
function get_dup_file_name($file_name) {
$suffix = 0;
while (file_exists($file_name . ($suffix == 0 ? "" : "(" . $suffix . ")"))) {
$suffix++;
}
return $file_name . ($suffix == 0 ? "" : "(" . $suffix . ")");
}
?>

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