How to capture a line from a file and then overwrite?

Asked

Viewed 732 times

-1

I have to access a file by php, this file has a variable at line x I want to take the contents of this variable, step to a condition, if other than expected I replace the value of this variable by php, without having q access the file manually.

Summarizing need to access a.php file from a library via php code, check which value of the variable, if different from the expected value change its value, only 2 values, production and test.

Example

linha 12 $varivel = 'teste'; // arquivo.php

// tenho o código que captura o valor da variavel
$oqueTemLinha12 = 'o que tem la';

if ($variavel != 'teste') {
// alterar para produção, e vice e versa, o problema não é a condição e sim como obter um valor de um arquivo e como troca-lo se preciso
}
  • You are already able to open the file, at least?

  • Yes, I can get the value, I just haven’t been able to replace it yet, I use the file to get the line, I get the content, now just change it. @Felipeavelar

2 answers

1


Correct answer

<?php

    // transforma o conteudo do arquivo em array
    $arquivo = file('Library/config/PaymentConfig.php');

    // armazena o que contem a linha 11
    $conteudoLinha = $arquivo[10];

    // captura apenas o valor da variavel
    function getAmbiente($conteudoLinha){
        $removeCaracteres = array('$ambiente = ', "'", ';');
        return str_replace($removeCaracteres, '', urldecode($conteudoLinha));
    }

    // seta o que vai conter na linha 11
    $arquivoe[10] = '$ambiente = "teste";' . "\n";

    // recria o arquivo com a linha 11 alterada
    file_put_contents('Library/config/PaymentConfig.php', implode("", $arquivo));

?>

0

You can rewrite part of the text of a particular file, without having to write the entire file, using the fseek, but the number of bytes (sentence size) must be equal.

Using fseek to position the pointer to the file position, you must overwrite the text $varivel = 'teste'; for $varivel = 'certo'; or even $varivel = '' ;. Always keep the 7 characters, counting the quotes to the semicolon.

Browser other questions tagged

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