Page refreshes without uploading file when clicking submit button - php

I'm very new to coding.
I'm trying to upload an image (any file for now) in a particular folder.
<?php
$name = $_FILES["file"]["name"];
$tmpName = $_FILES["file"]["tmp_name"];
if(isset($name)){
if(!empty($name)){
$location = "uploads/";
$destination_path = getcwd().DIRECTORY_SEPARATOR;
if (move_uploaded_file($tmpName,$destination_path.$location.$name)) {
echo "uploaded!";
}
else {
echo "boo";
}
}
else {
echo "please choose a file";
}
}
?>
<html>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<br>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
Everything is getting executed properly until the "move_uploaded_file" if-condition. Getting the else-echo-statement("boo")

Related

Renaming a form-selected file before submitting upload

I am attempting to create a form which allows the renaming of a selected file within the form, before submitting the upload.
I created the form with a 'text' field named "new_fileName" in addition to the file-picker.
On the upload.php side, I changed the variable to $newname, and tried a few ways to use that to change the name of the uploaded file. Including using it to replace the ['name'] part of the $filename variable. But so far, no success with anything.
FORM
<!DOCTYPE html>
<html>
<head>
<title> Rename and Upload Form </title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="file" id="file" />
<br><br>
<input type="text" name="new_fileName" placeholder="Rename File"/>
<br><br>
<input type="submit" value="Rename and Upload" />
</form>
</body>
</html>
upload.php
<?php
$newname = $_POST['new_fileName'];
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
if( move_uploaded_file($_FILES['file']['tmp_name'], $location)){
echo 'File uploaded successfully';
}else{
echo 'Error uploading file';
}
?>
After a bit of tinkering with the 'upload.php' page, this is what ended up working to change the name of the file before submitting the upload form.
This code also adds the file-type extension to the new file name.
(New) upload.php
<?php
$filename = $_POST['new_fileName'];
$name = $_FILES["file"]["name"];
$ext = end((explode(".", $name)));
if($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_FILES['file']['error'] > 0) { echo 'Error: ' . $_FILES['file']
['error']; }
if (file_exists('upload/' . $_FILES['file']['name'])) { unlink
('upload/' . $_FILES['file']['name']); }
move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $_POST =
$filename . "." . $ext);
echo 'File uploaded successfully' ; }
else { echo 'Error uploading file'; }
?>

Simple File upload code in PHP

This issue might have been discussed multiple times but I wanted a simple PHP script to upload a file, without any separate action file and without any checks. Below is my written code:-
<html>
<head>
<title>PHP Test</title>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="upload file" name="submit">
</form>
</head>
<body>
<?php echo '<p>FILE UPLOAD</p><br>';
$tgt_dir = "uploads/";
$tgt_file = $tgt_dir.basename($_FILES['fileToUpload']['name']);
echo "<br>TARGET FILE= ".$tgt_file;
//$filename = $_FILES['fileToUpload']['name'];
echo "<br>FILE NAME FROM VARIABLE:- ".$_FILES["fileToUpload"]["name"];
if(isset($_POST['submit']))
{
if(file_exists("uploads/".$_FILES["fileToUpload"]["name"]))
{ echo "<br>file exists, try with another name"; }
else {
echo "<br>STARTING UPLOAD PROCESS<br>";
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $tgt_file))
{ echo "<br>File UPLOADED:- ".$tgt_file; }
else { echo "<br>ERROR WHILE UPLOADING FILE<br>"; }
}
}
?>
</body>
</html>
I saved it in /var/www/html/phps/ location. But everytime I try to upload the file, I get ERROR WHILE UPLOADING FILE error. What am I doing wrong here. P.S. I have no previous experience of PHP, I just started with bits & pieces from internet.
Thanks
kriss
<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ".basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} 
else {
echo "Sorry, there was an error uploading your file.";
}
?>
I hope that this thing will work and this is what you are in need of.
<?php
$name = $_POST['name'];
$image = $_FILES['fileToUpload']['name'];
$tempname = $_FILES['fileToUpload']['tmp_name'];
move_uploaded_file($tempname, "foldername/$image");?>

File upload not working | Php

I'm trying to upload a file in php and unable to do it. The file I'm trying to upload is a csv file, but it should not be a concern. I'm using php to upload my file. I'm also trying to process the form in the same page. Below is my code for file upload and it is not working...
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="file" name="csv_file">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
if(isset($_POST['csv_file'])) {
echo "<p>".$_POST['csv_file']." => file input successfull</p>";
fileUpload();
}
}
function fileUpload () {
$target_dir = "var/import/";
$file_name = $_FILES['csv_file']['name'];
$file_tmp = $_FILES['csv_file']['tmp_name'];
if (move_uploaded_file($file_tmp, $target_dir.$file_name)) {
echo "<h1>File Upload Success</h1>";
}
else {
echo "<h1>File Upload not successfull</h1>";
}
}
?>
update your form code with enctype attribute
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype = "multipart/form-data">
<input type="file" name="csv_file">
<input type="submit" name="submit">
</form>
use enctype="multipart/form-data"
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="csv_file">
<input type="submit" name="submit">
</form>
I have try below code and it's work perfect.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="csv_file">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
echo "<p>" . $_POST['csv_file'] . " => file input successfull</p>";
$target_dir = "images ";
$file_name = $_FILES['csv_file']['name'];
$file_tmp = $_FILES['csv_file']['tmp_name'];
if (move_uploaded_file($file_tmp, $target_dir . $file_name)) {
echo "<h1>File Upload Success</h1>";
} else {
echo "<h1>File Upload not successfull</h1>";
}
}
?>
</body>
</html>
It should be something like this
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="csv_file">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
if ($_FILES['csv_file']['size'] > 0)
{
echo "<p>".$_FILES['csv_file']['name']." => file input successfull</p>";
fileUpload();
}
}
function fileUpload () {
$target_dir = "var/import/";
$file_name = $_FILES['csv_file']['name'];
$file_tmp = $_FILES['csv_file']['tmp_name'];
if (move_uploaded_file($file_tmp, $target_dir.$file_name)) {
echo "<h1>File Upload Success</h1>";
}
else {
echo "<h1>File Upload not successfull</h1>";
}
}
?>
</body>
Below are the changes you need to make
Add enctype = "multipart/form-data" in form tag as new attribute
Change from this if(isset($_POST['csv_file'])) { to this if($_FILES['csv_file']['size'] > 0) { as you need to check size
whether its uploaded or not
Change from this echo "<p>".$_POST['csv_file']." => file input
successfull</p>"; to this echo "<p>".$_FILES['csv_file']['name']."
=> file input successfull</p>"; as you need to use $_FILES to get file name instead of $_POST
Last but not the least, complete </body> tag if you have not yet.
Upload code in PHP[without checking its extension]
<?php
if(isset($_POST['save'])){
$path="var/import/";
$name = $_FILES['csv_file']['name'];//Name of the File
$temp = $_FILES['csv_file']['tmp_name'];
if(move_uploaded_file($temp, $path . $name)){
echo "success";
}else{
echo "failed";
}
}
?>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="csv_file">
<input type="submit" name="save" value="submit">
</form>
First Give permission to folder where you going to upload Ex: "var/import/" folder.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype= "multipart/form-data">
<input type="file" name="csv_file">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
if(isset($_FILES['csv_file']) && $_FILES['csv_file']['size'] > 0) {
echo "<p>".$_FILES['csv_file']['name']." => file input successfull</p>";
fileUpload();
}
}
function fileUpload () {
$target_dir = "var/import/";
$file_name = $_FILES['csv_file']['name'];
$file_tmp = $_FILES['csv_file']['tmp_name'];
if (move_uploaded_file($file_tmp, $target_dir.$file_name)) {
echo "<h1>File Upload Success</h1>";
}
else {
echo "<h1>File Upload not successfull</h1>";
}
}
for uploading files, the trick is enctype="multipart/form-data"
use this form definition

How can I get an error message when no file is selected in my file uploader?

This is my file uploader:
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
This is what happens now:
If I do not select any file and I click on "submit", I will be redirected to the done.php.
What I need:
If there is no file selected and I click on submit, I want to stay on my site and get an error messagage "No file selected".
done.php:
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
if (file_exists($target_file)) {
echo "file already existes";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
}
I updated my code now like Florian suggested:
done.php:
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
if (file_exists($target_file)) {
echo "file already existes";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
}
else {
echo 'No file selected. Back to upload form';
}
What happens now is, when I do not select any file I get the error message: "file already exists". I do not understand why.
Extend your done.php as follow:
if(!file_exists($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
} else {
echo 'No file selected. Back to upload form';
// maybe you want to include the upload form here or do something else
}
<html>
<body>
<script>
function unlock(){
document.getElementById('buttonSubmit').removeAttribute("disabled");
}
</script>
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="unlock();" name="file">
<button type="submit" id="buttonSubmit" value="upload" disabled>Upload</button>
</form>
</body>
</html>
Depending on your "View-Code" it could be something like that
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="todo" value="fileupload"?>
<button type="submit" value="upload">Upload</button>
</form>
<?php if($_POST && !$_FILES):?>
<h3>"No file selected".</h3>
<?php endif;?>
<html>
<head>
<style>
li
{
display: inline-block;
}
</style>
<script>
function formValidation()
{
if(document.getElementById("fileName").value==""||document.getElementById("fileName").value==null)
{
alert("no file selected");
return false;
}
else
return true;
}
</script>
</head>
<body>
<form action="done.php" method="post" enctype="multipart/form-data" onSubmit="return formValidation()">
<input id="fileName" type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
</body>
</html>
You can check it with
if(strlen($_FILES[$mcFile]['name'])==0){
echo "Error No file selected ";
}
OR
if ($_FILES["file"]["error"] > 0){
echo "Error No file selected ";
}
These both are the way to check files validation at server end

File upload with preserving the ajax controls

I am having a small problem with file uploading.
So there is a button that you click and a window comes up( ajax powered), you select your file and press upload. The problem is as soon as the file gets uploaded to the browser the page reloads and closes the window. And there is no file :(. I have tested the codes without the window and they work greatly fine. What do you recommend?
here are my codes for upload
<html>
<body>
<h2 class="">Step 1: Add the video</h2>
<p class="note">Your text goes here</p>
<form method="post" enctype="multipart/form-data">
File Name:<input type="text" name="name"/>
<br/><br/>
Browse: <input type="file" name="file"/>
<br/><br/>
<input type="submit" id='button' Value="Upload the video file" name="submit"/>
</form>
<?php
if(isset($_POST["submit"]))
{
$filename=$_POST["name"];
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$size=$_FILES["file"]["size"];
$size=$size/1000000;
$size=round($size, 2);
$size.="MB";
$namewithext=$filename." (".$size.")".".".$ext;
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("../../../moreinfo/files/videos/" . $_FILES["file"]["name"]))
{
echo "<script> alert('".$_FILES["file"]["name"] . " already exists. "."');</script>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../../../moreinfo/files/videos/" . $namewithext);
echo "<script> alert('"."success"."');</script>";
}
}
}
else
{
}
?>
<?php
foreach(glob('../../../moreinfo/files/videos/*.*') as $filename){
$name = str_replace('../../../moreinfo/files/videos/', '', $filename);
$ext = pathinfo($name, PATHINFO_EXTENSION);
$notneeded=".".$ext;
$name = str_replace($notneeded, '', $name);
echo $name."</br>";
}
?>
</body>
</html>
Note that echo "<script> alert('"."success"."');</script>"; never gets executed because there is no time for that.
Thanks!
Replace
<form method="post" enctype="multipart/form-data">
with
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
if this is not issue then try
echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; exit;
and see if there is any error.

Categories