Simple File upload code in PHP - 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");?>

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'; }
?>

Page refreshes without uploading file when clicking submit button

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

Cannot upload img to a folder

Im using laravel. And the img wont upload to my public/imgs folder. It keeps saying Sorry, there was an error uploading your file.
// PHP CODE
$target_dir = "public/imgs/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
if (move_uploaded_file($_FILES["img"]["name"], $target_file)) {
echo "success";
}
else {
echo "Sorry, there was an error uploading your file.";
}
// HTML CODE
<form method="POST" action="/listings" enctype="multipart/form-data">
<input type="file" name="img">
</form>
First make sure the upload dir is existing and writable; then file_uploads is on in php.ini
Maybe you should change your original move_uploaded_file function to
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)
See the diff between name and tmp_name
<form method="POST" action="/listings" enctype="multipart/form-data">
<input type="file" name="img">
</form>
HTML
$target_dir = "public/imgs/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
if ($_FILES['img']['error'] == 0) {
if (move_uploaded_file($_FILES['img']['tmp_name'], $target_file)) {
echo 'success';
} else {
echo 'upload failed<br>';
echo '<pre>';
echo 'tmp name: ';
print_r($_FILES['img']['tmp_name']);
echo "\n target: ".$target_file;
echo "\n\n";
print_r($_FILES['img']);
echo '</pre>';
}
} else {
echo 'upload failed: ' . $_FILES['img']['error'];
}
PHP
This code should work and show all data for debugging.

How to upload to a different drive in PHP?

I have a php page that lets you upload files, and the files just get uploaded to my computer, but I need them to be uploaded to a different hard drive. I need them to be uploaded to
"D:\uploads". I know there are some other problems with this code but i just need this out of the way. Heres the code itself:
<link rel="icon" type="image/png" href="favicon.ico.ico"/>
<?php
define("DOC_ROOT", $_SERVER['DOCUMENT_ROOT']."/");
define("PDF_UPLOADS", DOC_ROOT."uploads/");
#$name = $_FILES['file']['name'];
#$size = $_FILES['file']['size'];
#$type = $_FILES['file']['type'];
#$tmp_name = $_FILES['file']['tmp_name'];
if (isset($name))
{
if (!empty($name))
{
if(move_uploaded_file($tmp_name, PDF_UPLOADS. $name))
echo 'Uploaded';
else
echo "Not Uploaded";
}
else
{
echo 'Please choose a file';
}
}
?>
<form action="first.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br><br>
<input type="Submit" value="Submit">
</form>
Wouldn't it be as simple as this:
define("PDF_UPLOADS", "D:/uploads/");

PHP upload not working, maybe permission issues

I need to make an upload page in my site, I'm using an altervista trial server.
I used the tutorial http://www.w3schools.com/php/php_file_upload.asp
but the upload doesn't work. maybe, as I read is a permission issue, but I don't have the slightest idea on how to change the permissions of my folders.
Is it possible to add also pdf in the uploadable files?
thanks
uploadpage.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento senza titolo</title>
<link href="valsilehome.css" rel="stylesheet" type="text/css">
</head>
<body>
<form action="/tmp/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
$target_dir = "/tmp/uploads";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
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.";
}
}
?>
As of w3 schools, they have created many conditions for the example. But we don't need follow it strictly. We can use it only if we needed.
Here's the Minimal Code that you can have
<!DOCTYPE html>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
if (isset($_POST['submit']))
{
echo 'succesfully uploaded';
$structure = 'uploadedfiles/';
$target_file = $structure.basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
?>
If you use the above code you should create a folder named as uploadedfiles in the folder where you keep this file.
Else if you need to create each folder for each file upload then you should code.. It will create the file's name as folder each time.
<!DOCTYPE html>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
if (isset($_POST['submit']))
{
echo 'succesfully uploaded';
$structure = $_FILES["fileToUpload"]["name"];
if (!mkdir($structure, 777, true))
{}
$target_file = $structure.basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
?>
As you suggested in your post, try to change the permission of the folder following the code below:
chmod("/tmp/uploads", 0777);
you are using absolute path linux type, /tmp/uploads, if you are using linux try to show permission folder with "ls -l /tmp/uploads", if you are using windows hosts maybe you can print the path $target_file, inthe w3schools example the tagtet_path doesnt have the "/" "tmp/uploads" != "/tmp/uploads".

Categories