For part of my website I need to be able to write php code to a file with php. For example:
$myfile = fopen("event.php", "w");
$txt = "
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "events";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['create_event'])){
$sql = "INSERT INTO event (event_name, date_created)
VALUES (
'".$_POST['event_name']."',
'".date('Y-m-d')."'
)";
$result = mysqli_query($conn,$sql);
} ?> ";
fwrite($myfile, $txt);
fclose($myfile);
?>
How can I insert a php file inside the file I created. But, instead of creating the file, it throws an error:
Parse error: syntax error, unexpected 'localhost' (T_STRING) in C:\xampp\htdocseap2017\event\create.php on line 8
A string is indicated by two quotes. As soon as there is a second quote the compiler is going to think your string ends there. However, you want to have a string within a string for your server variables.
There are two ways to do this:
1. Using single '
and double "
quotes 2. Escaping the quote character with a backslash \"
Furthermore you'll need to wrap any variable names in your string in curly braces { }
to prevent PHP from interpolating your variables. Basically PHP even recognises variables in strings, and the braces tell it to use the literal text instead of the variable value.