0

I find this example in w3school to get display the file path of the file uploaded.

I need to get the chose file path using php.

I've added "form" with method "Post" and submit button to try to read javascript value but no result

"Try it" button call javascript function and I wanna "submit" get the same data as "Try it" button

 <!DOCTYPE html>
    <html>
    <body>
    <form action="" method = "post" enctype="multipart/form-data">
    Select a file to upload:
    <input type="file" id="myFile" size="50">
    <p>Click the button below do the display the file path of the file upload button above (you must select a file first).</p>
    <button type="button" onclick="myFunction()">Try it</button>
    <p id="demo" name="demo" type="text"></p>
    <input type="submit" name="submit" value="Submit" />
    </form>

    <script type="text/javascript">
    function myFunction() {
        var x = document.getElementById("myFile").value;
        document.getElementById("demo").innerHTML = x;
    }
    </script>
    </body>
    </html>

    <?php
    if(isset($_POST["submit"]))
    {
        $loc = $_GET["demo"];
        echo $loc;
    }
    ?>
hd najjar
  • 11
  • 1

1 Answers1

0

You say you want to get the same data with PHP; then just read the superglobal array called $_FILES after submit was clicked. The $_FILES array contains information about the file being uploaded: filename, filetype(MIME type), tmp_name(path to the temporary file on the server that contains the uploaded file), error and size.

<!DOCTYPE html>
    <html>
    <body>
    <form action="" method = "post" enctype="multipart/form-data">
    Select a file to upload:
    <input type="file" id="myFile" name="myFile" size="50">
    <br />
    <p>Click the button below do the display the file path of the file upload button above (you must select a file first).</p>
    <button type="button" onclick="myFunction()">Try it</button>
    <p id="demo" name="demo" type="text"></p>
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    <script type="text/javascript">
    function myFunction() {
        var x = document.getElementById("myFile").value;
        document.getElementById("demo").innerHTML = x;
    }
    </script>
    </body>
    </html>

    <?php
    if(isset($_POST["submit"]))
    {
        echo '<pre>';
        var_dump($_FILES);
        echo '</pre>';
        echo '<br />';

        echo 'C:\\fakepath\\' . $_FILES['myFile']['name'];

    }
    ?>
lovelace
  • 1,195
  • 1
  • 7
  • 10
  • thanks so much it works but there is still an issue: how to get the real path instead of C:\fakepath\?? – hd najjar Oct 01 '17 at 00:36
  • $_FILES['myFile']['tmp_name'] is all you'll ever get in terms of 'real path'. It is the full path to the temporary file on the server that contains the uploaded file. (your uploaded files will be stored as temporary files until needed.) – lovelace Oct 01 '17 at 10:33