I have been generating the PDFs and download it. Everything works fine. But whenever the file is output, it simply replaces the previous generated file.
Is there any way to output the file with the different name every time the NEW user downloads it by selecting data from the database?? What changes I can make in Output() method?
I have read output() doc.
$mpdf->Output("PDFs/something.pdf");
// change the path to fit your websites document structure
$fullPath = "PDFs/something.pdf";
You can do:
$filename = 'pdf' . time(). '.pdf';
$mpdf->Output("PDFs/$filename");
You can attach some timestamp/date with filename.
$filename = "PDFs/something-" . time() . ".pdf";
$mpdf->Output($filename);
// change the path to fit your websites document structure
$fullPath = $filename;
With the help of the answer given by Ramesh and some help from Immibis, I have found my way like this. Since the 'proposal_id' will always be unique in my case, so there will be no chance of downloading two pdfs of same id at the same time by different users.
$con = mysqli_connect("localhost","root","","my_db");
$name="Select name FROM table_name WHERE proposal_id= '$id'";
$name_result= mysqli_query($con,$name);
$row_name= mysqli_fetch_array($name_result);
$filename = $row_name['name']. time();
$mpdf->Output("PDFs/$filename.pdf");
$fullPath = "PDFs/$filename.pdf";
Related
all the idea i need to be sure that the file doesn't saved more than one time and don't lose any file because if tow files get the same (md5) the second file will not saved
(my goal don't save the same file Twice on hard disk)
In other words,
if one user upload image and after that another user upload the same image i need to don't save the the second image because it's already exist in the hard disk all of this because
i need to save space on my hard disk
this is my code it works fine
$targetFolder = '/test/uploadify/uploads'; // Relative to the root
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$myhash = md5_file($_FILES['Filedata']['tmp_name']);
$temp = explode(".", $_FILES['Filedata']['name']);
$extension = end($temp);
$targetFile = rtrim($targetPath,'/') . '/' .$myhash.'.'.$extension;
if(file_exists($targetFile)){
echo 'exist';
}
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
}
else {
echo 'Invalid file type.';
}
thanks for all of you
Well, of course you can do this, in fact this is the way I use to avoid file duplications (and I mean not having two files wit the same content and not just silly name collision).
If you are worried about collisions, then you might take a look at sha1_file:
http://es1.php.net/manual/en/function.sha1-file.php
What are the chances that two messages have the same MD5 digest and the same SHA1 digest?
I've been using the md5 approach the way you are suggesting here for image galleries and it works just fine.
Another thing to take care about is the time it takes to calculate the hash, the more complex the hash, the more time it needs, but I'm talking about processing really big batches.
If I understand your question correctly your goal is just to generate unique file names. If so, there is no point in reinventing the wheel - every hash function with fixed output length is going to have collisions - just use built in tempnam function.
Manual states:
Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.
Following should work well enough:
$targetDirectory = $_SERVER['DOCUMENT_ROOT'] . '/test/uploadify/uploads';
$uploadedFile = $_FILES['Filedata']['tmp_name'];
$targetFile = tempnam($targetDirectory, '');
move_uploaded_file($uploadedFile, $targetFile);
You could always add the systems current time in milliseconds to the filename. That plus the md5, would have a very unlikely chance of returning the same values.
It's very small, but the chance is there. You can read more here and here
I suggest you add a salt to the end of the filename to make it practically impossible for files to conflict(You should put the salt in a different md5 function though)
$salt = md5(round(microtime(true) * 1000));
$hash = md5_file($_FILES['Filedata']['tmp_name']);
$targetFile = rtrim($targetPath,'/') . '/' .$hash.$salt.'.'.$extension;
You should then insert the filename in a database so you can access it later.
When someone uploads an image to my server, it uploads as the name they have for the image on their computer. I want the image name to become a short number as the name instead of the name, because when someone uploads an image as the same name, it overwrites it.
Here is my script where the names are defined:
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext);
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);
$err = '';
This is a piece of (working) code I wrote a few years ago, that I still use to this day.
You probably may have to modify it to fit your script as well as the position in the script and the path.
However, I did replace my own original name (photo) with your fileup name.
Plus there are a few other goodies in there you probably could use, somewhere down the line.
$file_name = $HTTP_POST_FILES['fileup']['name'][0];
// should there be spaces in the uploaded file, replace them with an underscore
$file_name = str_replace(" ","_",$file_name);
$random_digit = substr(number_format(time() * rand(),0,'',''),0,10);
$new_file_name=$random_digit._.$file_name;
$path1= "./uploads/".$new_file_name;
// you can also use (my original write):
// copy($HTTP_POST_FILES['fileup']['tmp_name'][0], $path1);
move_uploaded_file($HTTP_POST_FILES['fileup']['tmp_name'][0], $path1);
$path_to_file_web = "http://www.example.com/uploads/$new_file_name";
The original script that I wrote was used on an older server with an older PHP version.
However, copy() will still work.
I do something like this:
i am just add some random string at beginning of file name
$new=generate_name(10);
$name=$new.$name;
Function generate_name();
function generate_name($long){
$cadena="[^A-Z0-9]";
return substr(eregi_replace($cadena, "", md5(rand())) .
eregi_replace($cadena, "", md5(rand())) .
eregi_replace($cadena, "", md5(rand())),
0, $long);
}
and generate this name:
03f396a35902-06-2013.csv
from 02-06-2013.csv file.
Not only do you not have to use the name provided when uploading a file, you shouldn't do so - like any user input, it is untrusted and could be used as a security hole.
So all you need to do is generate a random image name, and ensure it is not one that you've already used (e.g. by checking with file_exists() and using a do ... while loop to keep generating random names until that returns false). Then use that as the argument to move_uploaded_file(), which is the correct function to use for putting the file into a final location.
If you don't mind too much about the length and format, uniqid() is a good way to generate your filenames, because it is based on the current time so is unlikely to produce collisions.
I already looked at this StackOverflow question and it didn't help (similarly titled).
I'm passing an image in from my Android application. If I type
$file = fopen('test.jpg', 'wb');
It works correctly and the image uploads; however, I want to allow for multiple uploads from android phones, so I want to randomize the name of the .jpg file so that I can save each new upload as a different name. I was trying this below:
$destination = time() + rand(1, 1000) . ".jpg";
$url_destination = "/project_images/" . $destination;
$file = fopen($url_destination, 'wb');
fwrite($file, $binary);
fclose($file);
It doesn't write the file to the server, however. I tried different variations of the URL there - with 'project_images/', '/project_images/', even trying the full URL (which the aforementioned StackOverflow post corrected me on), and I still can't get it to write.
The permissions of the project_images folder are set to allow files to be written to it. Any ideas?
Your problem is "/project_images" which is a wrong absolute path.
For it to work change it to "project_images/" or dirname(__FILE__).'/project_images/'.
For those who use XAMPP on Windows: use DIRECTORY_SEPARATOR instead /
dirname(__FILE__).DIRECTORY_SEPARATOR.'project_images'.DIRECTORY_SEPARATOR
I am able to upload a zip file and compress it, now i need the filename alone... but when i try to reach the name i get along with zip.
asas.text = "upload/" +fileRef.name + "/" +as.text;
Also How can i point the current viewing URL before the upload path.. something if
http://www.yahoo.com/upload/filename/ If the file is viewed from yahoo domain
Use the basename function.
$fileName = basename('/path/to/file.zip'); // $fileName == 'file.zip';
I think you're asking for the server name? Using your example above:
echo $_SERVER['SERVER_NAME']; // prints "www.yahoo.com"
I have the php code below which help me get a photo's thumbnail image path in a script
It will take a supplied value like this from a mysql DB '2/34/12/thepicture.jpg'
It will then turn it into this '2/34/12/thepicture_thumb1.jpg'
I am sure there is a better performance way of doing this and I am open to any help please
Also on a page with 50 user's this would run 50 times to get 50 different photos
// the photo has it is pulled from the DB, it has the folders and filename as 1
$photo_url = '2/34/12/thepicture_thumb1.jpg';
//build the full photo filepath
$file = $site_path. 'images/userphoto/' . $photo_url;
// make sure file name is not empty and the file exist
if ($photo_url != '' && file_exists($file)) {
//get file info
$fil_ext1 = pathinfo($file);
$fil_ext = $fil_ext1['extension'];
$fil_explode = '.' . $fil_ext;
$arr = explode($fil_explode, $photo_url);
// add "_thumb" or else "_thumb1" inbetween
// the file name and the file extension 2/45/12/photo.jpg becomes 2/45/12/photo_thumb1.jpg
$pic1 = $arr[0] . "_thumb" . $fil_explode;
//make sure the thumbnail image exist
if (file_exists("images/userphoto/" . $pic1)) {
//retunr the thumbnail image url
$img_name = $pic1;
}
}
1 thing I am curious about is how it uses pathinfo() to get the files extension, since the extension will always be 3 digits, would other methods of getting this value better performance?
Is there a performance problem with this code, or are you just optimizing prematurely? Unless the performance is bad enough to be a usability issue and the profiler tells you that this code is to blame, there are much more pressing issues with this code.
To answer the question: "How can I improve this PHP code?" Add whitespace.
Performance-wise, if you're calling built-in PHP functions the performance is excellent because you're running compiled code behind the scenes.
Of course, calling all these functions when you don't need to isn't a good idea. In your case, the pathinfo function returns the various paths you need. You call the explode function on the original name when you can build the file name like this (note, the 'filename' is only available since PHP 5.2):
$fInfo = pathinfo($file);
$thumb_name = $fInfo['dirname'] . '/' . $fInfo['filename'] . '_thumb' . $fInfo['extension'];
If you don't have PHP 5.2, then the simplest way is to ignore that function and use strrpos and substr:
// gets the position of the last dot
$lastDot = strrpos($file, '.');
// first bit gets everything before the dot,
// second gets everything from the dot onwards
$thumbName = substr($file, 0, $lastDot) . '_thumb1' . substr($file, $lastDot);
The best optimization for this code is to increase it's readability:
// make sure file name is not empty and the file exist
if ( $photo_url != '' && file_exists($file) ) {
// Get information about the file path
$path_info = pathinfo($file);
// determine the thumbnail name
// add "_thumb" or else "_thumb1" inbetween
// the file name and the file extension 2/45/12/photo.jpg
// becomes 2/45/12/photo_thumb.jpg
$pic1 = "{$path_info['dirname']}/{$path_info['basename']}_thumb.{$fil_ext}";
// if this calculated thumbnail file exists, use it in place of
// the image name
if ( file_exists( "images/userphoto/" . $pic1 ) ) {
$img_name = $pic1;
}
}
I have broken up the components of the function using line breaks, and used the information returned from pathinfo() to simplify the process of determining the thumbnail name.
Updated to incorporate feedback from #DisgruntledGoat
Why are you even concerned about the performance of this function? Assuming you call it only once (say, when the "main" filename is generated) and store the result, its runtime should be essentially zero compared to DB and filesystem access. If you're calling it on every access to re-compute the thumbnail path, well, that's wasteful but it's still not going to be significantly impacting your runtime.
Now, if you want it to look nicer and be more maintainable, that's a worthwhile goal.
The easiest way to fix this is to thumbnail all user profile pics before hand and keep it around so you don't keep resizing.
$img_name = preg_replace('/^(.*)(\..*?)$/', '\1_thumb\2', $file);
Edit: bbcode disappeared with \.