2

Cont on. PHP show message based on user had attach file or not attach file (part 2)

Now, I want to show the error message on p tag when user didn't upload file 1 or file 2. Here is the code that I tried:

<html>
<head></head>
<body>
<p>
<?php
if(isset($_GET['action']) && ($_GET['action'])=='add')
{
     echo $errorMessage;
}
else
{
     echo ' ';
}
?>
</p> 

<form name="addform" method="post" action="add.php?action=add" enctype="multipart/form-data">
    File 1: <input type="file" name="file1" />
    File 2: <input type="file" name="file2" />
<input type="submit" name="submit" value="ADD">
</form>
</body>
</html>

<?php
if(isset($_GET['action']) && ($_GET['action'])=='add')
{
    UploadFile("file1","file2");
}

function UploadFile($file1, $file2)
{
    $file1Name = $_FILES[$file1]['name'];
    $file2Name = $_FILES[$file2]['name'];

    if(empty($file1Name) && empty($file2Name))
    {
        $errorMessage = 'Please upload file';
    }
}
?>

From above code, I get the following error:

Notice: Undefined variable: errorMessage on add.php in line 9

What mistakes am I made? How should I modify it?

Community
  • 1
  • 1
KKL Michael
  • 795
  • 1
  • 13
  • 31

2 Answers2

2

you are using the variable before declaring and inititlizing, so keep the uploading part above like this

<html>
<head></head>

<body>
<p>
<?php
if(isset($_GET['action']) && ($_GET['action'])=='add')
{
    UploadFile("file1","file2");
}

function UploadFile($file1, $file2)
{
    $file1Name = $_FILES[$file1]['name'];
    $file2Name = $_FILES[$file2]['name'];

    if(empty($file1Name) && empty($file2Name))
    {
        $errorMessage = 'Please upload file';
    } else {
         $errorMessage = ''; 
    } 

    echo $errorMessage;
}     
?>
</p>

<form name="addform" method="post" action="add.php?action=add"     enctype="multipart/form-data">
File 1: <input type="file" name="file1" />
File 2: <input type="file" name="file2" />
<input type="submit" name="submit" value="ADD">
</form>
</body>
</html>
KKL Michael
  • 795
  • 1
  • 13
  • 31
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
1

Modify, because you want to return the value of $errorMessage to be used again somewhere.

if(empty($file1Name) && empty($file2Name))
    {
        $errorMessage = 'Please upload file';
    }

to

if(empty($file1Name) && empty($file2Name))
    {
        $errorMessage = 'Please upload file';
    }
return $errorMessage ;
William Madede
  • 727
  • 4
  • 8