PHP move_uploaded_file to directory and create file - php

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.

Related

PHP get file content without saving

I have the following php code that runs when someone uploads a file:
if ($_FILES['files']['error'] === UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$namme = $_FILES['files']['name'][0];
$namme = substr($namme, strpos($namme,"."), strlen($namme));
$ok = false;
switch ($namme) {
case '.docx':
case '.txt':
case '.pdf':
break;
default:
die("Unknown/not permitted file type");
}
$filename = $_FILES['files']['tmp_name'][0];
$file = _file_get_contents('./'.$_FILES['files']['name'][0], true);
I want to print all of the content out but i don't wish to save the file first and then open it.
My question is: Is it possible to open the text file print the content without saving the file first?
When the user uploads a file, it gets saved in a temp location. That's just how the HTTP server works, before your PHP script ever gets called. It would be bad if the server held all uploaded files in memory; what if the user is uploading a dozen files that are all 10 MB?
The only way to avoid that is to not use file upload (for example, have the user paste the file contents into a text area that gets submitted), or write your own HTTP server and don't use PHP (not a practical solution, most likely).

Save Uploaded Text File to Web Server

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

PHP - upload and overwrite a file (or upload and rename it)?

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

Why is move_uploaded_file not working?

Whenever I try to move a file it does not work and shows "Image file not uploaded"... I just want to know where the error is...
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if( move_uploaded_file( $target, $destination ) ) {
echo "Image file is successfully loaded";
} else {
echo "Image file not uploaded.";
}
I have checked error log (tail -f /var/log/apache2/error.log) but found nothing.
target and destination both directories have 777 permissions.
Can someone tell me that how to find out the error. Any idea ?
If you are not using HTTP POST upload method then you can use rename()
rename($target, $destination);
Has the file been uploaded in the current request?
move_uploaded_file will refuse to move files that are not uploads. (i.e. $target must equal $_FILES[$field_name]['tmp_name']
If it has been uploaded previously, move_uploaded_file will refuse to work (if it is even still there - PHP will delete it if you don't handle the file on that upload if I remember correctly)
If it is in fact not a file that has been uploaded with this request you'll want to use rename
move_uploaded_file() only works on http post files. http://php.net/manual/en/function.move-uploaded-file.php
to move a file already on the server, you will have to copy the file and unlink the old file
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if (copy($target, $destination)) {
unlink($target);
} else {
echo "Unable to copy $target to $destination.";
}

Setting up path in the below code

<?php
if($_FILES['Filedata']['size']>=520000)
{
echo "\n Sorry, Not Moved Size below 5.2kb or 5200 bytes Only\n";
return;
}
$ext = end(explode('.', strtolower($_FILES['Filedata']['name'])));
if(move_uploaded_file($_FILES['Filedata']['tmp_name'], "./".$_FILES['Filedata']['name']))
{
echo "\nfile moved Success\n";
return;
}
?>
When i set path, it does not work... i dont know where to exactly set path such that the file gets saved in the directory.
See the move_uploaded_file documentation.
The first argument ($_FILES['Filedata']['tmp_name']) is the source, which you shouldn't change. The second argument ("./".$_FILES['Filedata']['name']) is the destination, which will currently put the file in the current working directory with its original name (This can be a security issue; you should put the file in an upload directory that has no execute permissions.)

Categories