0

I am trying to make a new .php file using php. But I get the following error:

error : Notice: Undefined variable: conn in C:\xampp\htdocs\create\index.php on line 4.

Here is the sample code :

<?php
    $myfile = fopen("koneksi.php", "w") or die("Unable to open file!");

    $txt = "<?php $conn=mysqli_connect('localhost', 'root', '', 'crm');
                  date_default_timezone_set('Asia/Jakarta'); 
           ?>";
    fwrite($myfile, $txt);
    fclose($myfile);
?> 
Binar Web
  • 867
  • 1
  • 11
  • 26
kafi
  • 41
  • 10
  • variables are replaced by their values in strings with double quotes `"`, try with simple quotes instead `'` – Kaddath Apr 17 '18 at 07:53
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Nigel Ren Apr 17 '18 at 07:55

2 Answers2

3

Either switch from double quotes to single quotes for your $txt variable - e.g.

$txt = '<?php $conn=...';

Or escape your dollar sign with a backslash

james_tookey
  • 885
  • 6
  • 12
0

If you put variable within double quotes PHP will print its value, and if it is not defined it will throw a notice.

If you want $conn to be part of your string you need to put in within single quotes.

$txt = '<?php $conn=mysqli_connect(\'localhost\', \'root\', \'\', \'crm\');
                date_default_timezone_set(\'Asia/Jakarta\'); 
  ?>';
xyzale
  • 745
  • 8
  • 14