Here is my code:
<html>
<body>
<div>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="file" id="myFile" name="filename">
<input type="submit" name="Submit">
</form>
</div>
<?php
if(isset($_POST['Submit']))
{
$file = $_POST["myFile"];
echo("hello");
}
?>
</body>
</html>
when I run it and input a file it says: Undefined array key "myFile"
what am I doing wrong?
CodePudding user response:
Uploaded files don't get added to the $_POST array but they are loaded into the $_FILES array. Try check that out.
You can then use the move_uploaded_file() to save it wherever you want.
Important: as soon as the script execution is over, the temporary uploaded file is removed if it was not saved somewhere else with move_uploaded_file().
CodePudding user response:
Add on form enctype="multipart/form-data"
This value is necessary if the user will upload a file through the form.
Your file type name is "filename".
<html>
<body>
<div>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<input type="file" id="myFile" name="filename">
<input type="submit" name="Submit">
</form>
</div>
<?php
if(isset($_POST['Submit']))
{
$file = $_POST["filename"];
echo("hello");
}
?>
</body>
</html>
CodePudding user response:
The request transfers the data using the names of the form fields and not the IDs, the file data can be found in the global variable $_FILES.
Use $file = $_FILES['filename']['name'];
for the name of the uploaded file
or $file = $_FILES['filename']['tmp_name'];
for the temporary file path of the uploaded file.