Search code examples
phpfwrite

Trying to build a file in PHP and use fwrite to file


trying to figure out how i can make a and save a file while including default info from another file. i tried include but it did not work. any suggestion on how to build this file?

<?php
$wrtID = $_POST["fileID"];

SQL statement here to get relevant info

mkdir("CNC/$wrtID", 0770, true);

?>
<?php

$batfile = fopen("CNC/$wrtID/$wrtID.bat", "w") or die("Unable to open file!");
$txt = "
@ECHO OFF
@ECHO **** Run NC-Generator WOODWOP 4.0 ****
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sl.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sr.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-dc.mpr
@ECHO **** Done ****
";
fwrite($batfile, $txt);
fclose($batfile);
?>

<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
$txt = "

include("defaultcnc.php");

if ( additional file pats needed ) {
    include("component-1.php");
}

";

fwrite($slfile, $txt);
fclose($slfile);
?>

Solution

  • I don't see a problem in the first block of code.

    On the second block, the interpreter will consider the second double quotes to mean the end of the string $txt = " include(". So everything after that would produce a PHP error.

    But even if you escape those the mpr file will have the string include("defaultcnc,php"); but not the actual contents of that file. For that you should do file_get_contents("defaultcnc.php").

    something like:

    <?php
    $slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
    // set params to pass to defaultcnc.php
    $value1 = 1;
    $value2 = "I'm a text string";
    $file = urlencode("defaultcnc.php?key1=".$value1."&key2=".$value2);
    $txt = file_get_contents($file);
    
    if ( additional file pats needed ) {
        $txt .= file_get_contents("component-1.php");
    }
    
    fwrite($slfile, $txt);
    fclose($slfile);
    ?>
    

    I assume additional file pats needed means something to you. It should be a condition evaluating either true or false.