passwd passwd - 4 months ago 18
PHP Question

PHP, cannot find syntax errors

EDIT: nvm, my bad, basically mis-read the errors reoported. Remember to check the dates and clear the logs wisely.

Apache's logs report errors in the lines 2,5 and 23, respectevely regarding unexpected "echo", "switch" and "echo" again.
I believe to already have checked every possible missing semicolon, but I still cannot find where the issues are.

Also, not sure if a semicolon should be added after the heredoc

<?php
if($_FILES){
$image = $_FILES['filename']['name'];

switch ($_FILE['filename']['type']) {
case 'image/jpeg': $ext = 'jpg';
break;
case 'image/png': $ext = 'png';
break;
case 'iamge/gif': $ext = 'gif';
break;
default: $ext = '';
break;
}
if($ext)
move_uploaded_file($_FILES['filename']['name'], "images/$image.$ext");
}

//$post_number = $post_number + 1;
$name = $_POST['name'];
$comment = $_POST['comment'];

$text = echo <<<_END
<article>
//<h3> '$post_number'</h3>
<h4>'$name'</h4>
<br>
<p> '$comment' </p>
<img src=images/'$image.$ext'>
</article>
_END;

$file = fopen("index.php", 'r+');
fseek($file, -17, SEEK_END);
fwrite($text);
fclose($file);
?>

Answer

I see a couple of problems:

1st: Replace this line

$text = echo <<<_END

With this

$text = <<< "_END"

If you'd like to echo, do echo $text later. Also make sure that there is nothing other than _END; on the closing line. No tabs, no spaces before or after _END; (see the docs).

2nd: Your fwrite will error because it needs the file handle, not just the text to write. While you're at it, you should check that the file was opened successfully before trying to write to it. Replace your file operations with the code below:

if($file = fopen("index.php", 'r+')){
    fseek($file, -17, SEEK_END);
    fwrite($file, $text);
    fclose($file);
}else{/* Todo: handle fopen failure */}

Happy coding.

Comments