PHP Subscribe Script not working

I am receiving a html 500 error when running this script - is there something I am missing?

<?php
if (isset($_POST["subscribeemail"])) 
{
$emailaddress = $_POST["subscribeemail"];
$newsletterfile = $fopen("C:\mailinglist\newsletteremails.txt","a");
$fwrite($newsletterfile, "\r\n");
$fwrite($newsletterfile, $emailaddress);
$fclose($newsletterfile);
echo "<html><body><center><img src='subscribe.png' width='100px'><br><span style='color: #ff1d25;'>Thanks! Your newsletters will be sent to the following email address: $emailaddress<br><br>Redirecting...</span></center></body></html>";
header("Location: index.html");
};
?>

It’s hard to say without more context, but one obvious error is this:-

You can’t have any output to the browser before sending headers.

You don’t need the semi-colon after a closing bracket of a conditon.
Another issue, though it should not stop it running (at this stage), is the complete lack of any validation for the email address.

What’s the reason for the dollar-symbol before the various fopen(), fwrite() and fclose() function calls? Is that something like the @ error-suppressor? I haven’t seen it before.

3 Likes

Can you talk us through what your script is supposed to be doing? I’m afraid none of it makes any sense.

1 Like

As I read it, it takes an email address from a form posting, appends it to the end of a stream file, then displays a message and doesn’t redirect to another page.

That’s because it is wrong.

1 Like

Oh, it is not supposed to be there, thanks

Yes, it just creates a mailing list for my company newsletter; users enter their email and click a subscribe button

1 Like

Thanks for the help!

This must have been the issue because now it works! Thanks!

I completely failed to notice that.
But my comments still stand about headers and email validation.
At the very least, first ensure that what the user inputs is an actual email address, not some gobbledegook, or nasty code injection.
https://www.php.net/manual/en/filter.examples.validation.php
Then to ensure that the address really belongs to the user, send them a confirmation email, with a link to confirm the subscription. This will prevent signing up people who didn’t want to, and act as some form of acknowledgement, negating the need for echoing the message that no one will see.
One more thing.

Make sure this is above the root or in a protected folder, so just anyone can’t access all your contact data.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.