Dropzone js and Verot's upload, how to upload to dynamic folder? - javascript

I'm using Dropzone.js and Verot's class.upload.php to create a simple upload file.
I want to have images upload to folders dynamically from a $_GET[] variable.
Below is the code I have, but no matter what I do, all files get uploaded to "uploads" folder.
upload.php
<?php include('includes/php/class.upload.php'); ?>
<form action="upload.php" class="dropzone"></form>
<?php
$ds = DIRECTORY_SEPARATOR;
$filesFolder = 'uploads';
if(isset($_GET['album'])){
$targetDir = dirname(__FILE__).$ds.$filesFolder.$ds.$_GET['album'];
}else{
$targetDir = dirname(__FILE__).$ds.$filesFolder;
}
if(!empty($_FILES)){
$handle = new upload($_FILES['file']);
if ($handle->uploaded) {
$handle->image_resize = true;
$handle->image_x = 960;
$handle->image_ratio_y = true;
$handle->process($targetDir);
}
}
?>`
So, if the url is index.php?album=rocks, images should get uploaded to "uploads/rocks". But, right now all gets uploaded to "uploads".
If I change the $filesFolder variable directly to "uploads/rocks" file uploads to the intended folder.
Am I doing something wrong? or is there a better way to achieve this besides using $_GET.

The issue with your code is the $_GET['album'] does not exist based on your current code, So the extended path never gets created. You must use a hidden input in your form for a GET request. But also be advised if your plan on using this code in on a live website or software please properly secure the data with validation and sanitization.
<form action = "upload.php" method="get" enctype="multipart/form-data">
<input type="hidden" name="dir" value="album"/>
<input type="submit"/>
</form>

Related

How to send a file from localhost to website

I want to send a preselected file (/tmp/test.txt) to a website (upload site) and get the response (shows a link to the uploaded file).
I have googled so much and didnt get it to work.
the following easy html form is working.
<html>
<body>
<form action="http://upload-site/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="testfile" value="select file" >
<input type="submit" value="Submit">
</form>
</body>
</html>
so i all need to send is the enctype und the file with info "testfile=test.txt" i guess ??
the form ofc wants me to select a file...what i dont want.
it has to be preselected since i want to automate the upload procedure and work with the response that gives me the link to the file.
how do i do that in php/curl/js ?
You have to use different approach to send your file to another website. You're transferring file over the server(technically over two machine). You could do it by FTP. Fortunately, PHP provides you functionality for this.
<?php
$file = 'somefile.txt'; // Path of the file on your local server. should be ABSPATH
$remote_file = 'somefile.txt'; // Path of the server where you want to upload file should be ABSPATH.
// set up basic connection
$conn_id = ftp_connect($ftp_server); // $ftp_server can be name of website or host or ip of the website.
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
I've never tried from localhost to website (Server). Give it try and let me know your feedback for this.
Without seeing your upload.php its hard to help you, but if you want to copy the selected uploaded file to a destination on your server and then display it in the browser you need to do something like this in the file upload.php which is your forms action.
//Get the file name
$file_name = $_FILES["testfile"]["name"];
//Create destination path
$dest = "/path/to/where/you/want/the/file/" . $file_name;
//Move the file
move_uploaded_file($_FILES["testfile"]["tmp_name"], $dest)
//View the file
echo "<script> location.href='http://someip/$dest'; </script>";
I think you need to change this
<input type="file" name="testfile" value="select file">
To this
<input type="file" name="testfile" id="testfile" value="select file">
You will notice im using JavaScript to redirect the browser to the newly uploaded file, you can also just send a new HTTP header using native PHP.
header("Location: http://example.com/thefile.txt") or die("Failed!");
You can read about what you think is the best approach for the redirect here.
I hope this helps?

Upload (not read) a .xlsx file from HTML and send it (any way) to a PHP file

I have an .xlsx file and a html file with an < input type="file">. I just need upload it and send it to a php file (with js or any other way).
The php file expects an .xlsx file (for this reason I dont parse the .xlsx.) if I load it direct in the php file, works perfectly but I need to upload through an user interface, in this case an html view.
Regards.
Update:
Now the .html looks like this:
<div class="MainContainerPrice">
<form action="php/excel_to_mysql.php" method="POST">
<input type="file" name="excel" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
<input type="submit">
</form>
</div>
And the .php looks like this:
<?php
include 'simplexlsx.class.php';
$file = $_FILES['excel'];
$xlsx = new SimpleXLSX('pricesExcel.xlsx'); //the file directly uploaded that I need to send from html.
...
?>
But now I have the next error:
Undefined index: excel in ...\excel_to_mysql.php on line 2.
Why doesn't recognize the name?
You need a bit of tweaking in the html and in the PHP part
<div class="MainContainerPrice">
<form action="php/excel_to_mysql.php" method="POST" enctype="multipart/form-data">
<input type="file" name="excel" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
<input type="submit">
</form>
</div>
Note the enctype="multipart/form-data". That's needed to actually send the file.
The in the PHP file
<?php
include 'simplexlsx.class.php';
$file = $_FILES['excel']['tmp_name'];
$xlsx = new SimpleXLSX($file); //the file directly uploaded that I need to send from html.
...
?>
$_FILES['excel']['tmp_name'] contains the full path to the uploaded file, note that you can't rely on the name having the '.xlsx' extension, cause the file gets a random name for security purposes.
I strongly suggest you to use the file from within the temporary directory, and to delete it after use.
If the SimpleXLSXclass needs the '.xlsx' extension to work properly, you can try to add it to the temp file
rename($_FILES['excel']['tmp_name'],$_FILES['excel']['tmp_name'].'.xlsx');

How do I add a simple image upload feature?

I want to give my new website a feature where I can upload 1 image by a button and stores(local storage) the image on another .html page, then if I grab it's absolute URL I can post this on forums websites where it's preview will show, so far I have a function that let's me upload and preview an image.. But I want to go to another level.
HTML:
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
Javascript:
<script>
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
</script>
Summary: upload image, store it(local storage), then grab it's absolute URL to paste it on another website to get the preview of that image.
Part 1: Upload
Uploading files to PHP is easy. To give the option for an user, you must add a file input to the HTML form. Here's an example:
<input type="file" name="picture" />
To make sure PHP receives the file, you must set the form method to POST and enctype to multipart/form-data
<form action="receiver.php" method="POST" enctype="multipart/form-data">
If you want to upload through javascript you might want to use AJAX. Here's an post for an example:
https://stackoverflow.com/a/6960586/3797667
Part 2: Receive (receiver.php)
The uploaded file can be accessed through $_FILES[].
Here's an example:
if(isset($_FILES['image'])){//Checks if file is set
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
//(above) checks file extension by getting text after last dot
$expensions= array("jpeg","jpg","png");//supported file types
if(in_array($file_ext,$expensions)=== false){//is the extension in the supported types
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){//PHP only supports files under 2MB
$errors[]='File size must be excately 2 MB';
}
//If there's no error moves files to folder "images" in the root of this file, else prints all the errors
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
For more methods on file management, check this link:
http://php.net/manual/en/ref.filesystem.php
Part 3: Access
You might want to check this post if you want to get an URL for your file:
PHP Dynamically get complete Absolute URL Path for specific file that will be included in other files
If you feel like you need more info, please comment below and I'll update the post. Good luck for your project!
Sources:
http://www.tutorialspoint.com/php/php_file_uploading.htm

Upload file in PHP error - goes to PHP file without allowing me to select?

I understand that SO advocates that we do our research before asking, but I'm not sure how to put it another way, so I thought I'd ask directly -
I'm actually trying to do something simple - upload a file, but when I select "choose" in the file browser, it just redirects to the PHP page, which shows the corresponding error message (since nothing has been uploaded).
Would really appreciate if you can explain the process flow of uploading a file. Here's my code:
HTML
Simple form
<form action = "./php/upload_avatar.php" method = "POST" enctype = "multipart/form-data">
<div class = "change-avatar-text">
改变头像
</div>
<!-- hidden button trick -->
<input type = "file" name = "file" id = "change-avatar-input"/>
<button type = "submit" class = "change-avatar" onclick = "fake_photo('change-avatar-input')"></button>
</form>
http://i.stack.imgur.com/6d2U4.png
The onclick is just a way to use a photo as the file button instead of a traditional button. I don't think it's relevant, so I omitted it here.
PHP
The upload file code
if (file_exists("../avatars/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "../upload/" . $_FILES["file"]["name"]);
}
Two things happened: when I tried clicking the upload button on the HTML page, it returned "already exists", but there's nothing in the ../avatars/ folder.
http://i.stack.imgur.com/DG8Vm.png
I then tried commenting out everything except for move_uploaded_file, and nothing happened.
Would appreciate your advice on this, thanks!
UPDATE
JS
Here's the fake photo function:
function fake_photo(element_id) {
document.getElementById(element_id).click();
}
You do not prevent the default action of the form from happening within your onclick method. But that will not be the only problem, since you are using the submit button as the trigger to start the file chose process you will need to resubmit the form after the image has been picked.
HTML
<form id="myform" action="./php/upload_avatar.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="change-avatar-input" onchange="onFileChanged()"/>
<button type="submit" id="submitBtn" class="change-avatar" onclick="fake_photo('change-avatar-input',event)"></button>
</form>
Javascript
var hasChosenFile = false;
function fake_photo(element_id,event){
//If hasChosenFile is false then we want
//to prevent the default action of the form
if(!hasChosenFile){
event.preventDefault();
document.getElementById(element_id).click();
}
//Else let the form submit.
}
function onFileChanged(){
hasChosenFile = true;
document.getElementById('myform').submit()
}

File Download hit counter PHP, MYSQL

I'm new to programming and Web Development all together. So please take it easy on me.
Right. My question is I have a file that users will download from the website. What I want to do is create a function that keeps track of the amount of times it has been downloaded. I have no problem in display the current count.
How can I update the Mysql database when a new click has been made?
So this is my link:
Download
This is my counter (retrieves amount of times it has been downloaded):
<h6 class="downloaded-count text-center"> Downloaded: <?php echo file_counter() ?></h6>
File counter:
function file_counter(){
$db = DB::getInstance();
$query = $db->query("SELECT temp_downloads FROM templates");
if(#$query->count()){
foreach($query->results() as $query_run){
$valid_count = $query_run->temp_downloads;
}
} return $valid_count;
}
Is there a way I could use html form with post method? and then create a function file_counter_inc() which receives form name or button name ? Or maybe use Javascript onclick method? which receives php function? P.s Don't know if the javascript thing would work
Update
OK I figured out how to increment the Mysql field after user clicks the button. Another proble m arise.... This is what I did. Looking at bellow code. How can I force a download now? I can't place the file into the form since the method now is PHP_SELF. So I cant place another method there.
This is my html now.
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="Download" name="download_counter">
</form>
<p class="text-center"> Downloaded: <?php echo file_counter() ?> </p>
This is file_counter_inc() method:
function file_counter_inc($tempID){
$db = DB::getInstance();
$query = $db->query("UPDATE templates SET temp_downloads = temp_downloads + 1 WHERE temp_id = '{$tempID}'");
}
Php uses Post method to know whether button was clicked.
if( isset($_POST['download_counter']))
{
file_counter_inc($website->temp_id);
}
How can I force a download after the file_counter_inc() method has been executed?
You can create a PHP function to handle the download requests, and increment the counter inside the function, for example, create download.php and pass the requested file as a GET parameter:
file_counter_inc(); // <-- The increment happens here
$file_url = $_GET['file_url'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"MyFile\"");
readfile($file_url);
Then you output the download link like this:
Download

Categories

Resources