Goodafternoon, I made this script but I can't get where I'm wrong, it didn't save the PDF as I tried to program.
Thank you if there's any suggestion.
I know the problem is in the logic inside: function file_newname but I don't know where exactly.
Thank you in advance.
<?php
require('fpdf.php');
class PDF extends FPDF{
function Header(){
$this->Image('img/oet.png',10,6,30);
$this->SetFont('Helvetica','B',25);
$this->Cell(55);
$this->Cell(100,10,"TITLE",0,0,'C');
$this->SetFont('Helvetica','B',18);
$this->Ln(10);
$this->Cell(55);
$this->Cell(100,10,"SUBTITLE",0,0,'C');
$this->Ln(20);
}
function Footer(){
$this->SetY(-15);
$this->SetFont('Times','I',8);
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
function file_newname($filename){
if($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
}else{
$name = $filename;
}
$newpath = 'docs/'.$filename;
$counter = 0;
while (file_exists("docs/")) {
$filename = $name .'_'. $counter . $ext;
$newpath = "docs/".$filename;
$counter++;
}
$this->Output("docs/".$filename);
}
}
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
for($i=1;$i<=10;$i++){
$pdf->Cell(0,10,'Printing line number '.$i,0,1);
}
$pdf->Output();
$pdf->file_newname(date("Ymd").".pdf");
?>
You are delcaring your new filename after you attempt to output. Use this:
$filename = $pdf->file_newname(date("Ymd").".pdf");
$pdf->Output($filename, 'F');
Don't recall exactly what the F flag does in the output command, but that's how I have it in my scripts.
Here is the right solution:
function file_newname($filename){
if($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
}else{
$name = $filename;
}
$newpath = 'documenti/'.$filename;
$counter = 0;
while (file_exists("documenti/".$filename)) {
$filename = $name .'_'. $counter . $ext;
$newpath = "documenti/".$newname;
$counter++;
}
$this->Output("documenti/".$filename);
$this->Output();
}
$pdf->file_newname(date("Ymd").".pdf");<<<<
Related
When I upload an image file to the host, why the file repeat filename extension again ? I check the filename in the host is like test.jpg.jpg
Here is the code:
$uploadPath = "../../upload/Image/";
$handle = new Upload($_FILES['pic'], 'zh_TW');
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
$filename = $pic;
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
$handle->file_new_name_body = $filename;
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 212;
$handle->image_ratio_fill = true;
$handle->allowed = array('image/*');
$handle->file_overwrite = true;
$handle->process($uploadPath);
if($handle->processed){
$handle->file_dst_name = $filename;
}
else{
echo "<script>";
echo "alert('$handle->error');";
echo "history.back();";
echo "</script>";
die;
}
}
else{
$filename = $_POST['currentPic'];
}
Base on your conditions. you can just get the name onle part by explode function.
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
//$filename = $pic;
$filename = explode(".",$pic)[0];
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
This is so you dont need to modify your class, also if you modify your class you will get trouble on the "ELSE" side of your condition that will cause additional spending time where to get the extension.
I use this Simple upload and resize image on PHP project to do my project.
https://gist.github.com/zeuxisoo/910107/483c7b6082dcc484d7b4cee21aad12650c53e416
but I don't know how to rename the file after upload.
I want to rename file and upload it into server as well as in database. The follow is code:
public function run() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
I use a lot of method , eg basename
It can't to it, any idea?? Thanks
You can do this
public function run() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
$tempName = explode(".", $this->files['name'][$i]);
$newName = "IMAGE_NAME"; //generate unique string to avoid conflict
$newfilename = $newName . '.' . end($tempName );
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$newfilename) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
In $newName you can generate new name for your file.
Update
To avoid conflict use unique string each time when you generate the name.
Instead of using move_uploaded_file use it as per code example given below.
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Here is your solution
public function run(){
$total = count($this->files);
for($i=0; $i<$total; $i++){
if(empty($this->files['name'][$i]) === false){
$ext = substr(strtolower(strrchr($this->files['name'][$i], '.')), 1); //get the extension
$new_name = 'new-name'.date('dmY').$ext;
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$new_name) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
Can someone tell me why this php code doesn't work? It doesn't chek if file_exists, but it just run the code. Sorry for my bad (grammer) english, english is not my main langue :).
$files = glob("../templates/Default/*");
for ($i=0; $i<count($files); $i++) {
$src = $files[$i];
$fileName = $src;
$fileName = str_replace("../templates/Default/", "", $fileName);
$dirName = $fileName;
$dest = "../Sites/NewSite1/$fileName";
if(file_exists($fileName)){
copy($src, $dest);
echo $fileName;
}else{
$fileName = "../templates/Default/$dirName";
$fileName = str_replace("$dirName", "$dirName/*", $fileName);
$dFiles = glob($fileName);
for ($t=0; $t<count($dFiles); $t++) {
$src2 = $dFiles[$t];
copy($src2, $dest);
echo $src2;
}
}
}
if you want to check whether the file exists in the directory where you are trying to copy it to, then you need to provide file_exists() with the entire directory path, therefore do the following:
change this: if (file_exists($fileName)) {
to this: if (file_exists($dest)) {
Here is the right code: (it still need some tweeking).
$files = glob("../templates/Default/*");
for ($i=0; $i<count($files); $i++) {
$src = $files[$i];
$fileName = $src;
$fileName2 = str_replace("../templates/Default/", "", $fileName);
$dirName = $fileName2;
$dest = "../Sites/$websiteName/$fileName2";
if (!copy($src, $dest)) {
$fileName3 = "../templates/Default/$dirName/*";
$dest2 = "../Sites/$websiteName/$fileName2";
$dFiles = glob($fileName3);
for ($t=0; $t<count($dFiles); $t++) {
$src2 = $dFiles[$t];
$fileName4 = $src2;
$fileName4 = str_replace("../templates/Default/$dirName/", "", $fileName4);
mkdir("../Sites/$websiteName/$dirName");
$dest2 = "../Sites/$websiteName/$dirName/$fileName4";
copy($src2, $dest2);
}
}
}
I'm using following code format to change image name if it already exists on server. I want incremental image names if they already exist with the same name.
Ex: abc.png, abc_1.png, abc_2.png
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
$counter = 1;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
return $newname;
}
Above code is working if image name is abc.png. If already an image is there on server with name abc_1.png and I run the code it generates image format as abc_1_1.png.
Expected output:
if already abc_1.png is present and I run the code $newname should return abc_2.png . How I can achieve it?
You just need to check what the string ends with, no need to use a regex for that. Take advantage of weak typing and is_numeric to find the value of any previous counter.
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
// New code here:
if(file_exists($newpath)){
$counter = 1;
if($pos = strrpos($name, '_')) {
$oldcounter = substr($name, $pos + 1);
if(is_numeric($oldcounter)){
$counter = $oldcounter + 1;
$name = substr($name, 0, $pos);
}
}
$newname = $name . '_' . $counter . $ext;
$newpath = $path . '/' . $newname;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
}
return $newname;
}
I've simplified the functionality a bit so I could get it into a live example, but If you want to play around with the code in the replacement section that I added you can check it out here: http://ideone.com/xR1v0j Just modify the initial value of $name to see how it will react to different inputs.
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);
}
}