-1

I am trying to execute a php code inside a variable, that prevents a text print if a variable is empty. The code is as follows:

$file = 'file.txt';

if (file_exists($file)) {
    $counter += file_get_contents($file);
}
file_put_contents($file, $counter);

$Item1 = @$_POST['Item1'];
$Item2 = @$_POST['Item2'];

$filename = "mydata.txt";
$txt = "\n";

$f_data= '
'<?php if (isset($Item1) && !empty($Item1)) { ?>' Item 1 : '.$Item1.' '} ?>'
'<?php if (isset($Item2) && !empty($Item2)) { ?>' Item 2 : '.$Item2.' '} ?>'
';

$file = fopen($filename, "a");
fwrite($file,$f_data);
fclose($file);
}
else
{
die("error");
}

I am facing problem at:

'<?php if (isset($Item1) && !empty($Item1)) { ?>' Item 1 : '.$Item1.' '}'
'<?php if (isset($Item2) && !empty($Item2)) { ?>' Item 2 : '.$Item2.' '}'

This code basically prevents the "Item 2 : " from printing if the @$_POST['Item2'] from the form is empty.

The code I am using for this is here: https://stackoverflow.com/a/24857671/5008955

I am getting the error "Parse error: syntax error, unexpected '?'" with this line.

Thanks for your help.

Cody Coderson
  • 411
  • 1
  • 9
  • 21

1 Answers1

0

You appear to be entering PHP tags and then leaving them twice.

'<?php if (isset($Item1) && !empty($Item1)) { ?>' Item 1 : '.$Item1.' '} ?>'
'<?php if (isset($Item2) && !empty($Item2)) { ?>' Item 2 : '.$Item2.' '} ?>'

You should have the following:

'<?php if (isset($Item1) && !empty($Item1)) { ?>' Item 1 : '.$Item1.' ' <?php } ?>'
'<?php if (isset($Item2) && !empty($Item2)) { ?>' Item 2 : '.$Item2.' ' <?php } ?>'

You are also checking if $Item1 and $Item2 are set, which regardless if there is any data received from the form, those variables will be set as you have defined them.

So you could make it:

'<?php if (!empty($Item1)) { ?>' Item 1 : '.$Item1.' ' <?php } ?>'
'<?php if (!empty($Item2)) { ?>' Item 2 : '.$Item2.' ' <?php } ?>'

Or one step further:

'<?php echo (empty($Item1)) ?: " Item 1 : $Item1 "?>'
'<?php echo (empty($Item2)) ?: " Item 2 : $Item2 "?>'

You may also wish to write it like this:

// Set the $f_data variable so that if neither $Item1 or $Item2 
// have any data, your `fwrite($file,$f_data);` won't fail.

$f_data = '';

if (!empty($Item1)) {
    $f_data .= "Item 1 : $Item1 ";
}
if (!empty($Item2)) {
    $f_data .= "Item 2 : $Item2 ";
}
Rubixryan
  • 107
  • 7