fopen: failed to open stream: No such file or directory

Asked

Viewed 467 times

-1

Hello I’m starting to learn PHP, and I created an HTML input that receives a TXT file that should be read in PHP but I’m having difficulties in reading the input file, which returns me the following error:

Warning: fopen(teste.txt): failed to open stream: No such file or directory in C:\Apache2\htdocs\teste.php on line 8

I wonder how I can solve?

My code is: (index.php)

    <html>
    <body>
    
    <form action="teste.php" method="post">
        <label for="myfile">coloque seu arquivo:</label>
        <input type="file" id="myfile" name="myfile"><br><br>
        <input type="submit" value="Submit">
    </form>

(php test.)

<html>
<body>

Arquivo txt:  <?php echo $_POST["myfile"]; ?><br>

<?php
$input_txt =$_POST["myfile"]; 
// Abre o Arquvio no Modo r (para leitura)
$arquivo = fopen ($input_txt, 'r');
?>

</body>
</html>
  • The fopen would only work if the file was already saved in the project directory. You need to get the file data from $_FILES.

  • And you’d have some clue how I can do that?

  • I posted the answer below

1 answer

0


Assuming your txt has the following structure:

João,[email protected],125
Maria,[email protected],123

First in the form you need to add enctype="multipart/form-data" as an attribute for you to send files. Then you need to take the array that is generated when you send a file $_FILES['myfile'], this array has 5 items, name, type, tmp_name, error e size, in your case you will need the tmp_name, being like this:

$myfile = $_FILES['myfile']['tmp_name'];

Now just process the data:

//file — Lê todo o arquivo para um array
$dados = file($myfile );

foreach($dados as $linha){
   
   $ln_valor = explode(',', $linha); //Explode na virgula
   
   $nome = $valor[0];
   $email = $valor[1];
   $id = $valor[2];

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.