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);
Related
I've got a web form which has a unique upload folder for each user (using their PHP session_id() as the folder name) which works well. When the form is submitted (after error checking) PHPMailer is used to send the email and the attachments. This is also working well. However, after the email is sent, I would like to remove the uploads from the folder and then the folder itself (sort of a self-cleanup!) The files are removed as expected but the folder remains (albeit empty). I wonder if the folder is somehow "still in use" so doesn't get deleted or something similar? This is the code:
// Empty the contents of the upload folder
if (is_dir($dir)) { // Target directory ($dir) is set above in photos POST section
// Check for any files inside the directory
$files = glob($dir.'/*'); // Get all file names
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
// Remove the upload folder
rmdir($dir); //NOT WORKING? NEEDS SOME TROUBLESHOOTING...
}
Any other ideas on why this folder is remaining?
Ben
I would guess that your folders might contain hidden files (starting with .) which the default glob pattern won't match, so try this:
$files = glob($dir . '/{,.}*'); // Get all file names including hidden ones
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
Also check the return value on both unlink and rmdir so you can see exactly where it's failing.
Turns out after much testing that the problem was not actually with rmdir at all! My web form uses a Dropzone for photo uploads to a unique folder for each user using their php session_id() and this folder is supposed to be created when they add a photo to Dropzone (if it doesn’t already exist). Problem was I’d put the folder creation code outside of the actual upload script so the folder was in fact being deleted but them instantly created again when the form submitted and the page reloads! Sorry about that but thanks for all your help. :)
hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).
I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}
I'm trying to push a file to a Amazon s3 filebucket.
I'm posting the file through an html form.
I try to generate a path to the file like this($file is a part of a foreach, because i need to support multiple files in a form-submit.)
$file['tmp_name'].'/'.$file['name'];
this outputs a filepath like this
/Applications/MAMP/tmp/php/phpZDcVQv/pdf.pdf
/Applications/MAMP/tmp/php/ exists, but nothing is inside it. I have set access read and write for everyone to that folder.
I use a library to post the images to Amazon: https://github.com/tpyo/amazon-s3-php-class It also complains that the filepath i have provided doesn't exist. It's running a check like:
if (!file_exists($file) || !is_file($file) || !is_readable($file))
How come the files aren't added?
Am I referencing the wrong folder? The file with the code is in /web/projectname/
Someone on the internet said something unclear about php removing the temp-file directly. Is this after the response has been run? Do I need to address this in some way?
The most simple code that generates the problem:
foreach ($_FILES as $file) {
$filepath = $file['tmp_name'].'/'.$file['name'];
if(file_exists($filepath)){
echo 'true <br />';
}else{
echo 'false <br />';
}
}
This echo:es false even if files have been uploaded.
$filepath contains the path i described above.
as the manual states:
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
and
$_FILES['userfile']['name']
The original name of the file on the client machine.
this means that file_exists($file['tmp_name']) should be true.
The path $file['tmp_name'].'/'.$file['name'] is bogus, since $file['name'] is there only for informing you of the original name, but this name is not used while saving the uploaded file on the server.
So in your example /Applications/MAMP/tmp/php/phpZDcVQv is actually the uploaded file.
I have a problem with saving PDF files to folders on my server. The code worked at one time and now it doesn't. What I want it to do is to check if someone is trying to upload a PDF when a form is submitted, and if there is a PDF in the file field it uploads it and then saves the path to the mysql database. Code is below:
if (!empty($_FILES['pdf'])){
$idir = "../files/PDF/"; //my directory file is supposed to be saved in
$randomd=rand(0000000,9999999); //creates a random number as filename
$domain = "http://".$_SERVER['HTTP_HOST'];
$file_ext = strrchr($_FILES['pdf']['name'], '.'); grabs file extension. my code checked if the file was a pdf a different way and neither seems to work.
$destination=$randomd.$file_ext; //new filename
if ($file_ext=='pdf') {
move_uploaded_file($_FILES['pdf']['tmp_name'], "$idir" . $destination);
$pdf= $domain."/files/PDF/".$destination; } else { echo("File type not supported.");
mysql_query("UPDATE tbl_listings SET pdf='$pdf' WHERE listing_id='$lid'");
}
The if not empty does not work and it always tries to upload a file, but when I check the folder nothing is in there and it doesnt update the mysql.
$_FILES['pdf'] will never be empty(when the form has been submitted), no matter if a file has been selected or not, it will always return an array.
Check $_FILES['pdf']['error'] , it will be 4 when no file has been uploaded.