Dreamy
Dreamy

Reputation: 67

Can't access upload file input with php

I created a simple form, to create a post, that has three inputs:

So, when I submit my form (using post) I call a php file, that "echoes" the value from each input.

It works just fine, but when I try to call the php function $_FILES['my_input_name']['tmp_name'], on my file input, I get an error saying:

Undefined index: my_input_name

My form looks like this (shorter version):

<form action="processForm.php" method="post">
  <input type="text" name="title" class="input" required>
  <textarea id="description" name="description"required></textarea>
  <input type="file" name="fileMedia">
</form>

My php file looks like this

$method = $_SERVER[ 'REQUEST_METHOD' ];

if ( $method=='POST') {
    $_args = $_POST;
    $_INPUT_METHOD = INPUT_POST;
}
elseif ( $method=='GET' ) {
    $_args = $_GET;
    $_INPUT_METHOD = INPUT_GET;
}
else {
    exit(-1);
}

$title = $_args['title'];
$description = $_args['description'];
$mediaName = $_args['fileMedia'];
$mediatmpPath = $_FILES["fileMedia"]["tmp_name"];

echo $title."<br>";
echo $description."<br>";
echo $mediaName."<br>";
echo $mediatmpPath ."<br>";

I have no idea of what I'm doing wrong, so any helped would be really apreciated!

P.s: My form's is really reduced. In the original one I have row, cols, divs, etc, and some other inputs, which I did not find relevant for this question

Upvotes: 1

Views: 1084

Answers (2)

Chintan
Chintan

Reputation: 123

You need to add this below line in <form> tag

<form action="processForm.php" method="post" enctype='multipart/form-data'>
   <input type="text" name="title" class="input" required>
   <textarea id="description" name="description"required></textarea>
   <input type="file" name="fileMedia">
   <input type="submit" name="save" value="save">
</form>

And below post data code:

<?php $method = $_SERVER[ 'REQUEST_METHOD' ];

    if ( $method=='POST') {
      $_args = $_POST;
      $_INPUT_METHOD = INPUT_POST;
    }
    elseif ( $method=='GET' ) {
      $_args = $_GET;
      $_INPUT_METHOD = INPUT_GET;
    }
    else {
     exit(-1);
    }

    $title = $_args['title'];
    $description = $_args['description'];
    $mediaName = $_FILES["fileMedia"]["name"];
    $mediatmpPath = $_FILES["fileMedia"]["tmp_name"];

    echo $title."<br>";
    echo $description."<br>";
    echo $mediaName."<br>";
    echo $mediatmpPath ."<br>";
   ?>

I think this help you.

Upvotes: 0

Arka Patra
Arka Patra

Reputation: 31

You just need to add multipart = "form/data" in form tag

Upvotes: 1

Related Questions