PHP file upload suddenly stopped working - php

I had file upload working fine this morning and did a couple of test uploads using small csv files, but when I did another test it has stopped working.
var_dump of $_FILES['file'] is NULL, and trying if($_FILES) produces nothing.
No one else uses my server so I know nothing's been changed.
Here is my form which posts to the same page.
<form method="post" enctype="multipart/form-data" style="border:1px solid #999">
<input type="file">
<input type="hidden" name="customerID" value="<?=$_GET['customerID']?>">
<input type="submit" value="Import">
</form>
Php handler:
if($_FILES)
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path = "files/".$_POST['customerID']."/";
echo $path."<br>";
if(!file_exists($path)) mkdir($path);
$path = $path.basename($_FILES['file']['name']);
echo $path."<br>".$_FILES['file']['tmp_name']."<br>";
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) echo "Upload success";
else echo "Upload failed";
}
else echo "No temp file";
}

You had to change something... because $_FILES['file'] should be undefined in code you gave. No file is sent at all by most browsers in the case when file input has no name attribute in HTML form.
Simply change:
<input type="file">
to
<input type="file" name="file">

You need to add a "name" attribute to your <input type="file">. The name you give to the input will be the index of the array element in $_FILES that contains the uploaded file data.

Related

How to check if $_POST[image] is set

Re asking how to check if $_POST[FILE] isset
I have a file input and if I submit my form without an image I want something to happen if I uploaded a file in the input I want something different to happen.
if (!isset($_POST[image])) { }
seems to trigger regardless of whether or not I have uploaded a file in the input or not.
<label>
<p>Profile Picture:</p>
<input type="file" name="image" value="" />
</label>
My last question was marked as a duplicate of this answer Check whether file is uploaded however
if (!file_exists($_FILE['image'])) { }
didn't work either it is still showing truthy even when an image is uploaded. So not the answer I need.
To check if there is a file uploaded is you need to check the size of the file.
Then to check if its an image or not is you need to use the getimagesize() function. See my script below:
HTML:
<form action="index.php?act=s" method="post" enctype="multipart/form-data">
<input type="file" name="image" value=""/>
<input type="submit">
</form>
PHP:
<?php
if(isset($_GET['act'])){
// Check if there is a file uploaded
if($_FILES["image"]["size"]>0){
echo "There is a file uploaded<br>";
// Check if its an image
$check_if_image = getimagesize($_FILES["image"]["tmp_name"]);
if($check_if_image !== false) {
echo "Image = " . $check_if_image["mime"] . ".";
} else {
echo "Not an image";
}
}
else{
echo "There is NO file uploaded<br>";
}
}
?>

Display uploaded file name below Button in PHP

I am trying to display the name of the uploaded file below the input button. The default text should say "No File Uploaded", once the file is selected and added to the server "file_name.ext was uploaded".
Here is my code at the moment:
<label for='upload' class='upload-button'></label><input type='file' name="fileAttach" class='upload-button' id='upload'/><br>Upload Site List
<?php
if (isset($_FILES['fileAttach']['name'])) {
echo "File is attached.";
}
?>
This code is on the form page using POST with enctype multipart/form-data.
My knowledge is below the entry level, so I'm sorry if this is really simple question. All the info I found so far did not help.
<label for='upload' class='upload-button'></label><input type='file' name="fileAttach" class='upload-button' id='upload'/><br>Upload Site List
<?php
if(isset($_FILES['fileAttach']['name'])) {
echo $_FILES['fileAttach']['name']." was uploaded";
}else{
echo "No File Uploaded";
}
?>
The form will have to be submitted for php to echo the statement.
<form enctype="multipart/form-data" action="" method="POST">
<input type='file' name="fileAttach" class='upload-button' id='upload'/>
<input type="submit">
</form>
<br>Upload Site List<br>
<?php
if(isset($_FILES['fileAttach']['name'])) {
echo $_FILES['fileAttach']['name'] . " was uploaded";
} else {
echo "No File Uploaded";
}
?>

Undefined Index: File when uploading image to PHP But works when php and html in same file

I had been stuck on this problem for about 3 days straight.
When i upload an image to php it gives me an error Undefined index: file.
I read many other questions i made sure i have enctype="multipart/form-data" in my form tag, i made sure each image name has name="file[]" but no luck, But when i try doing the html and php within 1 single file, everything works perfectly. But when i split the php from the html then it stops working.
There should not be any problem on the php side, because i can get it working if html is within the php.
Html
<form enctype="multipart/form-data" id="submitform" class="form-horizontal" action="submitlisting.php" method='post' >
<p id="result"></p>
<span class="btn btn-file"><input type="file" name="file[]" id="file[]"></span>
Remove
<button id="submit" type="submit" value="Submit" name="submit" class="btn btn-success" style="width:100px;">Submit</button>
</div>
</div>
</form>
Php:
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
$username=$_SESSION['username'];
$userid=$_SESSION['id'];
for($i=0;$i<count($_FILES["file"]["name"]);$i++)
{
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png');
$path = $_FILES["file"]["name"][$i];
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ((!in_array($ext, $supported_image) )&&($_FILES["file"]["size"][$i] > 1000000))
echo "Picture[$i]". "either empty or File format incorrect, You can change the pictures later<br>";
else{
if ($_FILES["file"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"][$i] . "<br>";
echo "Size: " . ($_FILES["file"]["size"][$i] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"][$i] . "<br>";
echo "<br>";
if (file_exists("rentaid.info/Bootstraptest/rent" . $_FILES["file"]["name"][$i]))
{
die($_FILES["file"]["name"][$i] . " already exists please add another file, or change the name ");
}
else
{
$photo=$_FILES["file"]["name"][$i];
move_uploaded_file($_FILES["file"]["tmp_name"][$i],
"Bootstraptest/rent/$photo");
echo $photo."&nbsp&nbspadded</br>";
mysqli_query($con,"INSERT INTO listingpic (pic,listingid,userid) VALUES
('$photo','$form_insert_id','$userid');") or die(mysqli_error());
echo"Listing added";
}
}
}}
}
?>
Its calling the error right at the first time the $File enters the php, in the for loop condition for($i=0;$i<count($_FILES["file"]["name"]);$i++)
Debugging the problem usually makes it go away.
In your php file input following lines:
echo '<pre>';
print_r($_FILES);
echo '</pre>';
This will output whatever comes in from your form.
Also, a good programming practice is to first check the values you get from your form. What if someone doesn't load a file to the form? Then, trying to loop through files will cause error.
So,
if(isset($_FILES['file'])) {
// do whatever
}
And, lastly, change the following to real path, relative the root - /
action="submitlisting.php"
action="/submitlisting.php"
You are most likely openning the form in the browser. Assuming some local virtual host like 'mytest.com' or maybe 'localhost' is used - your form is open at 'mytest.com/myform.php' and form handler at 'mytest.com/submitlisting.php' the action attribute of the form should be '/submitlisting.php'. If the scrpit is somewhere else - put that path there, relative from the root of the site.
EDITED:
Try adding MAX_FILE_SIZE to your form as a hidden input.
To do that edit your HTML part:
<form ...>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
...
<input type="file" ..>
Hidden input before any actual file input fields.

uploading a file server side

Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>

Trouble with uploading a file

I can't get any files to upload successfully, it's just going to echo 'error';
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value = "2000000">
Upload this file: <input name ="userfile" type="file">
<input type="submit" value="Send File">
</form>
PHP:
<?php
if ($_FILES['userfile']['error']>0)
{
echo 'Problem.';
exit;
}
$upfile='/uploads/'.$_FILES['userfile']['name'];
if (is_uploaded_file($_FILES['userfile']['name']))
{
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile))
{
echo 'Problem: could not move file';
exit;
}
}
else
{
echo 'Error';
exit;
}
echo 'File uploaded successfully.';
?>
I'm sure it's something simple I'm messing up, but I've spent about an hour trying to find it. Thanks.
if (is_uploaded_file($_FILES['userfile']['tmp_name']))
tmp_name instead of name
$_FILES['userfile']['tmp_name'] is the name of the uploaded file. $_FILES['userfile']['name'] is just the name that the file had when it was on the computer of the user.
For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.

Categories