This is the case:
I have a 2Gb dump file called myDB.sql. It is a dump file that deletes a existing database and creates a new one, with views and triggers. So I have the string myDB_OLD
spread for many lines of the code.
I would like to change these strings occurrences to myDB_NEW
.
I could do this easelly using notePad++. But notepad does not opens a 2Gb file.
What I did is a PHP code that reads line by line and find and replace the string I want.
This is the code:
$myfile2 = fopen("myDB.sql", "r") or die("Unable to open file!");//Reads the file
while (!feof($myfile2)) {//Pass trough each line
$str=fgets($myfile2);//Store the line inside a variable
if (preg_match("/myDB_OLD/",$str)) {//If the string I want to change exists - replace it and conacatenate
$newStr .= str_replace("myDB_OLD","myDB_NEW",$str);
}
else {//If not concatenate it
$newStr .=$str;
}
}//End of while
fclose($myfile2);
//Save the newStr in a new file named
$myfile = fopen("newDB.sql", "w") or die("Unable to open file!");
fwrite($myfile, $newStr);
echo "finished";
This code retrieve each line of the file changes the string, concatenate in variable and creates a new file. It should works but it is not. I dont know why. I am using xdebug to figure out what is the issue, but no luck.
So I change the approach. Instead of save each line in a variable, I save it directly in a file and that works good.
This is the new code:
$myfile = fopen("newDB.sql", "w") or die("Unable to open file!");//Creates a new file "newDB.sql"
$myfile2 = fopen("myDB.sql", "r") or die("Unable to open file!");//Reads the file
while (!feof($myfile2)) {//Pass trough each line
$str=fgets($myfile2);//Store the line inside a variable
if (preg_match("/myDB/",$str)) {//If the string I want to change exists - replace it . (Do not concatenate)
$strRep=str_replace("myDB","myDB_NEW",$str);
}
else {
$strRep =$str;
}
fwrite($myfile, $strRep);// Add the new line to the file "newDB.sql"
}//End of while
fclose($myfile);
fclose($myfile2);
echo "finished";
Ok, I solved my issue but it raises a thought. What is the issue of the first code? I think the issue is the amount of information to be stored in a PHP variable, 2Gb. So, is there a limit in size to a PHP variable to stores value, in this case, a string ? If yes how can I check or change it? Any php.ini variable?