I have my users uploading a text file which then gets processed by my application. Once the processing is done, I would like to save a copy of this text file somewhere on my server for future reference. Currently, the uploaded text file stays in the PHP temp folder until it is closed by my app.
What's a simple way to accomplish this?
BTW, I'll need to know how to do this on my web server along with localhost (for testing).
You can use the fwrite function (this is probably not a very good idea in this particular example though.
$fp = fopen('data.txt', 'w');
fwrite($fp, $yourContents);
fclose($fp);
But, if you already have the file simply copy it using the copy command (if you want to keep it in the temp folder that is, if not move it with the rename function instead).
To copy, do something like this
$tempfile = 'tempfile.txt';
$newfile = 'newfile.txt';
if (copy($tempfile, $newfile)) {
echo "success!";
} else {
echo "misery :(";
}
To move with rename
// Rename returns a bool, just as in the copy example
rename("/tmp/tempfile.txt", "/home/user/files/newfile.txt");
Added this: To move with move_uploaded_file
Please note, I didn't test this in a development environment. This may not execute perfectly.
$uploads_dir = 'C:\\movefiles\\here\\';
foreach ($_FILES["upload-tracking-file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["upload-tracking-file"]["tmp_name"][$key];
$name = $_FILES["upload-tracking-file"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir\\$name");
}
}
References
Copy, http://php.net/manual/en/function.copy.php
Move (rename), http://php.net/manual/en/function.rename.php
move_uploaded_file, http://php.net/manual/en/function.move-uploaded-file.php
fwrite, http://php.net/manual/en/function.fwrite.php
use php's function ob_start(), and file_put_contents() this should help you. this links will help you if not post your reply
php.net/manual/en/function.ob-start.php, php.net/manual/en/function.file-put-contents.php
Related
I have cleanup script, which move the XLS files from one place to another. for this file moving process, I have used the rename function. This script is working fine. but when the XLS file is open, when I try to move that xls, I am getting error which simply say Can not rename sample.xls. But I would like to add the functionality like, Check the XLS is open before initiate rename function.
I believe this is function call flock but this is applicable for TXT file alone.
How to check XLS file is opened before call the rename function.
One simple thing you could try is to use flock to acquire a Exclusive Lock on the file and if it fails you will know the file is being used:
<?php
$fp = fopen('c:/your_file.xlsx', 'r+');
if(!flock($fp, LOCK_EX))
{
echo 'File is being used...';
exit(-1);
}
else
{
fclose($fp);
// rename(...);
}
An alternative would be to check the existence of the locking file excel usually creates when a file is being used:
<?php
$file = 'c:/testfile.xlsx';
$lock = 'c:/~$testfile.xlsx';
if (file_exists($lock))
{
echo "Excel $file is locked.";
}
else
{
echo "Excel $file is free.";
}
The hidden file is usually name with the prefix ~$ as for old excel files I believe 2003 and older the lock files are saved on the temp folder with a random name like ~DF7B32A4D388B5854C.TMP so it would be pretty hard to find out.
You should use flock(). This puts a flag on the file so that other scripts are informed that the file is in use. The flag is turned off either intentionally using fclose or implicitly by the end of the script.
Use file lock like:
flock($file,LOCK_EX);
see this
I know you can create a temporary file with tmpfile and than write to it, and close it when it is not needed anymore. But the problem I have is that I need the absolute path to the file like this:
"/var/www/html/lolo/myfile.xml"
Can I somehow get the path, even with some other function or trick?
EDIT:
I want to be able to download the file from the database, but without
$fh = fopen("/var/www/html/myfile.xml", 'w') or die("no no");
fwrite($fh, $fileData);
fclose($fh);
because if I do it like this, there is a chance of overlapping, if more people try to download the same file at exactly the same time. Or am I wrong?
EDIT2:
Maybe I can just generate unique(uniqID) filenames like that, and than delete them. Or can this be too consuming for the server if many people are downloading?
There are many ways you can achieve this, here is one
<?php
// Create a temp file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'MyFileName');
echo $temp_file;
?>
The above example will output something similar to:
/var/tmp/MyFileNameX322.tmp
I know you can create a temporary file with tmpfile
That is a good start, something like this will do:
$fileHandleResource = tmpfile();
Can I somehow get the path, even with some other function or trick?
Yes:
$metaData = stream_get_meta_data($fileHandleResource);
$filepath = $metaData['uri'];
This approach has the benefit of leaving it up to PHP to pick a good place and name for this temporary file, which could end up being a good thing or a bad thing depending on your needs. But it is the simplest way to do this if you don't yet have a specific reason to pick your own directory and filename.
References:
http://us.php.net/manual/en/function.stream-get-meta-data.php
Getting filename (or deleting file) using file handle
This will give you the directory. I guess after that you are on your own.
For newer (not very new lol) versions of PHP (requires php 5.2.1 or higher) #whik's answer is better suited:
<?php
// Create a temp file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'MyFileName');
echo $temp_file;
?>
The above example will output something similar to: /var/tmp/MyFileNameX322.tmp
old answer
Just in case someone encounters exactly the same problem. I ended up doing
$fh = fopen($filepath, 'w') or die("Can't open file $name for writing temporary stuff.");
fwrite($fh, $fileData);
fclose($fh);
and
unlink($filepath);
at the end when file is not needed anymore.
Before that, I generated filename like that:
$r = rand();
$filepath = "/var/www/html/someDirectory/$name.$r.xml";
I just generated a temporary file, deleted it, and created a folder with the same name
$tempFolder = tempnam(sys_get_temp_dir(), 'MyFileName');
unlink($tempFolder);
mkdir($tempFolder);
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);
I have a script that uploads a file and then moves it to a directory. However the script does not know the name of the file its creating because it hasn't created it yet and cannot find the file to update.
So either one requires a way to make the file first or there is another way of doing this. The code.
<?php
$filename = '/home/divethe1/public_html/update/z-images/admin/upload/test/';
if ($_FILES['thumbfile']['error'] === UPLOAD_ERR_OK) {
$info = getimagesize($_FILES['thumbfile']['tmp_name']);
if (($info[2] !== IMG_GIF) && ($info[2] !== IMG_JPEG)) {
die("not a gif/jpg");
}
if (filesize($_FILES['thumbfile']['tmp_name']) > 100000) {
die("larger than 100000");
}
move_uploaded_file($_FILES['thumbfile']['tmp_name'], $filename . $_FILES['thumbfile']['name']);
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Archiving"</script>Archiving';
}
else
{
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Invalid File Format"</script>Invalid File Format';
}
?>
Any ideas?
I think you're misunderstanding how move_uploaded_file() works. It doesn't create a file for you. It:
Takes the temporary filethat PHP created for you to hold the upload (the filename/path for which is in $_FILES['thumbfile']['tmp_name'])
does a few security checks to make sure no one's tampered with the file between the time the upload completed and the move_uploaded_file call was issued
then MOVES the file to the location you specify.
It doesn't handle the upload, or receive the file - by the time your upload-handling script gets fired up, the upload has already been completed and the file is waiting in that tmp_name location.
If the move can't be completed for any reason, move_uploaded_file() returns false. It won't warn you if you're overwriting a file in the destination, on the assumption that you know what you're doing.
My mistake. I left the directory test in place. That should have gone. Thanks anyway for all help.
I am uploading a file to soundcloud.com from my own server with using an API in PHP:
if (isset($mime)) {
$tmp_file = $tmp_path . $_FILES['file']['name'];
// Store the track temporary.
if (move_uploaded_file($_FILES['file']['tmp_name'], $tmp_file)) {
$post_data = array(
'track[title]' => stripslashes($_POST['title']),
'track[asset_data]' => realpath($tmp_file),
'track[sharing]' => 'private'
);
if ($response = $soundcloud->upload_track($post_data, $mime)) {
$response = new SimpleXMLElement($response);
$response = get_object_vars($response);
$message = 'Success! Your track has been uploaded!';
// Delete the temporary file.
unlink(realpath($tmp_file));
} else {
$message = 'Something went wrong while talking to SoundCloud, please try again.';
}
} else {
$message = 'Couldn\'t move file, make sure the temporary path is writable by the server.';
}
} else {
$message = 'SoundCloud support .mp3, .aiff, .wav, .flac, .aac, and .ogg files. Please select a different file.';
}
}
This is my code. The temp path is http://122.166.23.38/dev3/bids4less/funkeymusic/upload
and it has permissions 777 (-rwxrwxrwx).
But it shows:
Couldn't move file, make sure the temporary path is writable by the server.
How do I fix this problem?
I believe your temp path in php should point to a directory on your server, not a http location.
This question is too old, but as it were popped anyway...
You don't have to move anything, nor unlink.
Just read uploaded file from it's temporary location.
And it comes extremely handy to split your complex task into smaller chunks, in order to locate an error. Try to send a static file first, then test file upload, and only then join these tasks into final application.
TRY S_SERVER you will get brief description from this url http://php.net/manual/en/reserved.variables.server.php
Here is the example given to find address for your server
try big example to sort out you method
What's the file size, and how long takes it to upload the file?
Can you please verify those 2 php.ini values:
max_execution_time
post_max_size
Maybe PHP's upload facility is constrained in some way? Is PHP in safe_mode?