Problem with fopen

2

This file is performing its function perfectly, but it is returning some errors and I would like to correct them. I need to know if I have to use fopen and file_get_contents because I can not undo any.

# /pasta/copy.php 
<?php
$original = fopen('/pasta/copy.txt','r+');
$ip = fopen('/pasta/origin.txt','r');
$ip = file_get_contents('/pasta/origin.txt','r');
$copia = fopen('/pasta/ok.txt','w+');
if ($original) {
    while(true) {
        $linha = fgets($original);
        if ($linha==null) break;
        if(preg_match("/ASSunto/", $linha)) {
            $string .= str_replace("ASSunto", $ip, $linha);
        } else {
            $string.= $linha;   #**Linha 13**
        }
    }
    rewind($copia);
    ftruncate($copia, 0);
    fwrite($copia, $string);
    fclose($original);
    fclose($copia);
    fclose($ip);    #**Linha 21**
}
?>

And the errors are as follows:

PHP Notice:  Undefined variable: string in /pasta/copy.php on line 13
PHP Warning:  fclose() expects parameter 1 to be resource, string given in /pasta/copy.php on line 21

The file copy.txt .

# /pasta/copy.txt
Assunto para primeira linha
ASSunto

The file origin.txt .

# /pasta/origin.txt
Assunto para segunda linha

The ok.txt file looks like this.

# /pasta/ok.txt
Assunto para primeira linha
Assunto para segunda linha
    
asked by anonymous 14.03.2015 / 22:45

1 answer

3
  

PHP Notice: Undefined variable: string in ..

The first error is generated because the variable string was not declared, you are trying to concatenate a value to a non-existent variable.

  

PHP Warning: fclose () expects parameter 1 to be resource, string given in ..

The second error is generated due to 4 and 5 lines, or you use fopen or file_get_contents . The ip variable is being given the result of the file_get_contents function and not the file pointer opened by fopen .

If you choose to use file_get_contents and file_put_contents instead of fopen and fwrite , your code can look like this:

<?php

$original = file_get_contents('/pasta/copy.txt');
$ip = file_get_contents('/pasta/origin.txt');
$copia = '/pasta/ok.txt';

if ($original === false){
    echo "Não foi possível ler o arquivo";
    exit;
}

$string = str_replace('ASSunto', $ip, $original);

if (file_put_contents($copia, $string) === false){
    echo "Erro ao gravar no arquivo ". $copia;
} else {
    echo "Operação realizada com sucesso.";
}

?>

It is not necessary to state with preg_match whether a word exists in the file or not , str_replace will see and replace all as occurrences of this word.

If the file specified in file_put_contents does not exist, it will be created, if it exists, it will be overwritten.

    
14.03.2015 / 23:52