I am currently doing a PHP project that requires me to make a logs of all the imported excels in the database.
I was able to get the tmp_name from the $_FILES global variable but not able to get the exact file path.
Here is my code snippet.
index.php
<form role="form" method="post" action="post_data.php" enctype="multipart/form-data">
<input type="file" name="file" required>
<button>Submit</button>
</form>
post_data.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//var_dump($_FILES['file']);
//var_dump($_FILES['file']['name']); #gets the file name
var_dump($_FILES['file']['tmp_name']); #gets the temp file path and name
}
?>
Any help would be much appreciated. I can also work with javascript if there are any available solutions for this problem. Thanks
You'll not get the file path. The File Upload in PHP works such that when you upload a file, it'll be uploaded to a temporary location and then your form will be posted. The path of the temporary location will be provided in tmp_name option in $_FILES array.
By using the move_uploaded_file function, this file will be moved from the temporary location to the location of your choice. But you'll have to provide the location (including the filename) where you want to move the file from temporary location.
So if you are looking for a path where you want to move the file from then it'll be present in tmp_name.
Hope this helps.
<?php
//variable containing path of Server's folder where you want to upload your file
$path;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//var_dump($_FILES['file']);
//var_dump($_FILES['file']['name']); #gets the file name
var_dump($_FILES['file']['tmp_name']); #gets the temp file path and name
if (move_uploaded_file($_FILES['file']['tmp_name'], $path . DS . $_FILES['file']['name'])) {
//file uploaded successfully
//your file is uploaded at $path . DS . $_FILES['file']
}
else {
//error in uploading file
}
}
?>
$image=$_FILES['file'];
$base=$_SERVER['DOCUMENT_ROOT']; $filename=$_FILES['file']['name'];
$path=$base."/trial/Uploads/Original_folder/signature/".$filename."";
if(file_put_contents($path,$image)!=false)
{
echo $path;
}
Related
This question has been asked many times, but I can't find the right answer.
I'm trying to upload a file with javascript, ajax and php. Which works so far. However, I would like to rename the file when uploading and in javascript, so that I can determine the name of the file from there.
my function to upload the file via ajax in javascript
async function uploadFile() {
let formData = new FormData();
formData.append("file", fImage.files[0]);
await fetch('/upload.php', {
method: "POST",
body: formData
});
alert('The file has been uploaded successfully.');
}
my input field in html
<input class="form-control" type="file" id="fImage">
my upload.php
<?php
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "upload/".$filename;
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
}
?>
The aim would be to determine the file name via javascript, e.g. via a variable
you can use the 3rd parameter of append to specify the filename (MDN)
formData.append("file", fImage.files[0], new_name);
I am creating a form on a website, where files (images and pdfs) need to be uploaded too. Until now, I have used a simple input type="file" element, coupled to a PHP file on the backend (snippet follows):
$allowed = array('jpg', 'jpeg', 'pdf', 'png');
if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){
$extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"not_allowed"}';
exit;
}
// create folder to upload files to
$id = session_id();
$user_folder = 'user_data/' . $id;
if( is_dir($user_folder) === false ){
mkdir($user_folder);
}
if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], $user_folder . "/" . $_FILES['uploadctl']['name'])){
echo '{"status":"success"}';
exit;
}
echo '{"status":"error"}';
}
This works well. However, I would like more functionality for the upload form and have looked into filepond. I created the filepond object as per the documentation and copied the boilerplate code to ./file-pond-assets, which I plan to adapt to my needs later:
<input type="file" name="uploadctl" multiple accept=".pdf,.png,.jpg,.jpeg">
<script>
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create( inputElement );
pond.setOptions({
server: './file-pond-assets'
});
</script>
which is showing when displaying the website. When trying to upload a file, the front-end looks fine, as an upload complete message appears. However, I cannot find the uploaded files in the tmp and uploads folder inside ./file-pond-assets. I tried changing permissions of the folders and also checked the console, but cannot find an error message. The config.php file also points to the right folders. What do I miss that makes my files not appear on my server? I would like to keep the upload as a multipart/form-data.
Here is a link to my sample file-pond PHP server implementation repository on gihtub
Repo Link: https://github.com/Onihani/filepond-php-server-example
Live Preview: http://www.ics-courses.co.uk/natbongo/filepond-php-server-example/
The issue I'm facing is, I get the following error while trying to upload some pdfs your upload file is not PDF file. However, this error doesn't show up for all pdfs, it's only for some pdf files I get this error.
<?php
$error = $_FILES['fileToUpload']['error'];
//get upload file type
$type = $_FILES['fileToUpload']['type'];
$action = "upload";
//get file name
$picname = $_FILES['fileToUpload']['name'];
$nameArray = explode(".", $picname);
if {
//check files
//filetoUpload code
}
?>
The issue is that, in the url: '../controller/uploadFile.php' even if the file is PDF, $type = $_FILES['fileToUpload']['type']; will return empty and then it will go into the condition else if($type !="application/pdf" ) and pop up the alert your upload file is not PDF file.. Like I said, this issue is with most of the pdf file. However, some pdf files manage to get uploaded without any issue and if a pdf file gets uploaded, then $type will be application/pdf.
Your input will be highly appriciated.
---UPDATE---
The issue is with $_FILES, it's not fetching the pdf file details for some reason
The issue has been resolved. I checked '$error= $_FILES['fileToUpload']['error']; and the value was returning 1
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.```
You could better check the extension, this also prevents malicious users to upload exe or zip files when they provide the header Content-Type: application/pdf. Also not all browsers/api libraries specify a Content-Type.
If your filename does not contain a path, check it with a regex so people cannot upload files to directories they shouldn't (ex ../../cache/exe). use for example
preg_match("/^[a-zA-Z0-9_+\\- ]+\\.pdf$/", $filename) to check if it is a pdf.
Do never do unlink('files/' . $filename); when $filename could be anything submitted by the user. Delete ../index.php could destroy your server.
I am using Laravel 5. I have a form which has an upload file inside it. If I want to edit the data and edit the file(upload new file), it's works. But if I want to edit the data without uploading a new file (example the mail's name, because the file's name depends on the mail's name), it works just change the file name in the database without rename a file which stored in the server, so when I click view file, I have got an error the file is not found. Do you know how to replace a file name?
$destination = 'files';
if($request->hasFile('ubah_upload_file')) {
$file = $request->file('ubah_upload_file');
$extension = $file->getClientOriginalExtension();
$file_name = str_replace('/','_',$request['ubah_nomor_surat']) . '.' . $extension;
$file->move($destination, $file_name );
} else {
$file_name = str_replace('/','_',$request['ubah_nomor_surat']) . '.' . "pdf";
}
Use the rename() function to rename a file
Ps: update the name in the db too if you rename it permanently
The below code checks for a directory 'dat'; if it ins't there, it creates one. That part works just fine; what I need is for it to write a file to said directory where AJAX can read it from.
Here's the php...
//checks for 'dat' directory; if false, creates it, if true, does nothing.
$dir = 'c:\wamp\www\dat';
if(file_exists($dir)){
return;
}
else{
mkdir ('C:\wamp\www\dat',0700);
}
//writes chats to file
$data = fopen($dir. "/chatlog". date('d'). '.txt', 'a+');
fwrite($data, $speak);
fclose($data);
}
And here's the AJAX; I don't need as much help here as I do above, but I won't complain if you provide the help for the AJAX below, mainly in getting it to read from the file within the 'dat' directory...
xhr.open("GET","chatlog<?php /*stamps the chatlog file with date (numerical day only)*/ echo date("d");?>.txt",true);
Your PHP script is running inside www, then, your file you be created there.
If you want to create the file inside the directory www/dat, just change this line
$file = "chatlog". date('d'). ".txt";
for this one
$file = 'dat\chatlog'. date('d'). '.txt';