/    Sign up×
Community /Pin to ProfileBookmark

Upload form with email attachment

Hi Guys
I have got my hands on a great bit of code that works, see below. I have edited it a bit to meet my needs but there is still a few things I would like to do and I don’t know how so I wonder if someone can amend this for me.

I would like to add in a validation to only allow upload of .doc, .docx and .txt files.
I would like to add some text to display in the textarea to describe the type of thing I want the user to type about.
And finally, I would like it to redirect to a page saying thanks for the file, rather than just staying on the same page and displaying a message saying thanks.

Would be very grateful if you could help with this.

Thanks, Adrian

[code]
<?php
/* Mailer with Attachments */

$action = “”;
$action = $_REQUEST[‘action’];
global $action;

function showForm() {
?>

<form enctype=”multipart/form-data” name=”send” method=”post” action=”<?=$_SERVER[‘PHP_SELF’]?>”>
<input type=”hidden” name=”action” value=”send” />
<input type=”hidden” name=”MAX_FILE_SIZE” value=”10000000″ />
<p>Name: <input name=”from_name” size=”50″ /></p>
<p>Email: <input name=”from_email” size=”50″ /></p>
<p>Subject: <input name=”subject” size=”50″ /></p>
<p>Message: <textarea name=”body” rows=”10″ cols=”50″></textarea></p>
<p>Attachment: <input type=”file” name=”attachment” size=”50″ /></p>
<p><input type=”submit” value=”Send Email” /></p>

<?php
}

function sendMail() {
$from_name = stripslashes($_POST[‘from_name’]);
$subject = stripslashes($_POST[‘subject’]);
$body = stripslashes($_POST[‘body’]);
$attachment = $_FILES[‘attachment’][‘tmp_name’];
$attachment_name = $_FILES[‘attachment’][‘name’];

if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$fp = fopen($attachment, “rb”); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
//Let’s start our headers
$headers = “From: $from_name<” . $_POST[‘from_email’] . “>n”;
$headers .= “Reply-To: <” . $_POST[‘from_email’] . “>n”;
$headers .= “MIME-Version: 1.0n”;
$headers .= “Content-Type: multipart/related; type=”multipart/alternative”; boundary=”—-=MIME_BOUNDRY_main_message”n”;
$headers .= “X-Sender: $from_name<” . $_POST[‘from_email’] . “>n”;
$headers .= “X-Mailer: PHP4n”;
$headers .= “X-Priority: 3n”; //1 = Urgent, 3 = Normal
$headers .= “Return-Path: <” . $_POST[‘from_email’] . “>n”;
$headers .= “This is a multi-part message in MIME format.n”;
$headers .= “——=MIME_BOUNDRY_main_message n”;
$headers .= “Content-Type: multipart/alternative; boundary=”—-=MIME_BOUNDRY_message_parts”n”;

$message = “——=MIME_BOUNDRY_message_partsn”;
$message .= “Content-Type: text/plain; charset=”iso-8859-1″n”;
$message .= “Content-Transfer-Encoding: quoted-printablen”;
$message .= “n”;
/* Add our message, in this case it’s plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= “$bodyn”;
$message .= “n”;
$message .= “——=MIME_BOUNDRY_message_parts–n”;
$message .= “n”;
$message .= “——=MIME_BOUNDRY_main_messagen”;
$message .= “Content-Type: application/octet-stream;ntname=”” . $attachment_name . “”n”;
$message .= “Content-Transfer-Encoding: base64n”;
$message .= “Content-Disposition: attachment;ntfilename=”” . $attachment_name . “”nn”;
$message .= $data; //The base64 encoded message
$message .= “n”;
$message .= “——=MIME_BOUNDRY_main_message–n”;

// send the message
mail(“[email protected]”, $subject, $message, $headers);
print “Mail sent. Thank you for using the MyNewName5333 Mailer.”;
}

?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>

</head>
<body>

<?php
switch ($action) {
case “send”:
sendMail();
showForm();
break;
default:
showForm();
}
?>

</body>
</html>[/code]

to post a comment
PHP

45 Comments(s)

Copy linkTweet thisAlerts:
@djadejonesauthorJul 17.2011 — I've now found this validation code to put in my own, but where do I put it??

// check for valid file types
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] &gt; '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'&lt;&amp;lt Go Back');
}
}
}
Copy linkTweet thisAlerts:
@ericatekkaJul 17.2011 — See below:

Dont really need to use a for loop if its only gonna allow you to upload one file only.
Copy linkTweet thisAlerts:
@ericatekkaJul 17.2011 — Sorry this might be easier:


[code=php]// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<&lt Go Back');
}else{

$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Thanks for this, I presume I am to replace:

[CODE] if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
[/CODE]


with your bit of code?

Adrian
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — I have now put that validation bit of code in to my page, thanks for that.

But now I have a new problem. When I made a test.php and put this code in, sent the form, I received the email with attachment. Now I have copied the code over to my wordpress page template, it doesn't seem to work.

When I click send, it just takes me back to the home page, and I don't receive any emails.

Here is what I have:

[code=php]<?php
/* Mailer with Attachments */

$action = "";
$action = $_REQUEST['action'];
global $action;

function showForm() {
?>

<form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<p>Name: <input name="from_name" size="40" /></p>
<p>Email: <input name="from_email" size="40" /></p>
<p>Subject: <input name="subject" size="40" /></p>
<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>
<p>Attachment: <input type="file" name="attachment" size="30" /></p>
<p><input type="submit" value="Send Your CV" /></p>

<?php
}

function sendMail() {
$from_name = stripslashes($_POST['from_name']);
$subject = stripslashes($_POST['subject']);
$body = stripslashes($_POST['body']);
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];

// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<&lt Go Back');
}else{

$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}

//Let's start our headers
$headers = "From: $from_name<" . $_POST['from_email'] . ">n";
$headers .= "Reply-To: <" . $_POST['from_email'] . ">n";
$headers .= "MIME-Version: 1.0n";
$headers .= "Content-Type: multipart/related; type="multipart/alternative"; boundary="----=MIME_BOUNDRY_main_message"n";
$headers .= "X-Sender: $from_name<" . $_POST['from_email'] . ">n";
$headers .= "X-Mailer: PHP4n";
$headers .= "X-Priority: 3n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['from_email'] . ">n";
$headers .= "This is a multi-part message in MIME format.n";
$headers .= "------=MIME_BOUNDRY_main_message n";
$headers .= "Content-Type: multipart/alternative; boundary="----=MIME_BOUNDRY_message_parts"n";

$message = "------=MIME_BOUNDRY_message_partsn";
$message .= "Content-Type: text/plain; charset="iso-8859-1"n";
$message .= "Content-Transfer-Encoding: quoted-printablen";
$message .= "n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "$bodyn";
$message .= "n";
$message .= "------=MIME_BOUNDRY_message_parts--n";
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_messagen";
$message .= "Content-Type: application/octet-stream;ntname="" . $attachment_name . ""n";
$message .= "Content-Transfer-Encoding: base64n";
$message .= "Content-Disposition: attachment;ntfilename="" . $attachment_name . ""nn";
$message .= $data; //The base64 encoded message
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_message--n";

// send the message
mail("[email protected]", $subject, $message, $headers);
header("Location: http://www.primarycarecommunity.net/success");
}


?>
[/code]


The above is located just before my <!DOCTYPE html> stuff and header.

And in the main content, I have:

[code=php]<div id="right">
<?php
switch ($action) {
case "send":
sendMail();
showForm();
break;
default:
showForm();
}
?>
</div>[/code]


So the form displays as it should, you can see this here: http://www.primarycarecommunity.net/vacancies/

But it just doesn't work.

Adrian
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — I think you'll find that the exiting of php is "echoing" the form contents before your doctype possibly causing issues:

function showForm() {

?>

<form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER['PHP_SELF']?>">

<input type="hidden" name="action" value="send" />

<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />

<p>Name: <input name="from_name" size="40" /></p>

<p>Email: <input name="from_email" size="40" /></p>

<p>Subject: <input name="subject" size="40" /></p>

<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>

<p>Attachment: <input type="file" name="attachment" size="30" /></p>

<p><input type="submit" value="Send Your CV" /></p>

<?php

}
[/quote]

<i>
</i>function showForm() {
echo '&lt;form enctype="multipart/form-data" name="send" method="post" action="'.$_SERVER['PHP_SELF'].'"&gt;
&lt;input type="hidden" name="action" value="send" /&gt;
&lt;input type="hidden" name="MAX_FILE_SIZE" value="10000000" /&gt;
&lt;p&gt;Name: &lt;input name="from_name" size="40" /&gt;&lt;/p&gt;
&lt;p&gt;Email: &lt;input name="from_email" size="40" /&gt;&lt;/p&gt;
&lt;p&gt;Subject: &lt;input name="subject" size="40" /&gt;&lt;/p&gt;
&lt;p&gt;Message: &lt;textarea name="body" rows="5" cols="31"&gt;&lt;/textarea&gt;&lt;/p&gt;
&lt;p&gt;Attachment: &lt;input type="file" name="attachment" size="30" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type="submit" value="Send Your CV" /&gt;&lt;/p&gt;';
}


Aside from that, it may have something to do with the processing that WP does during page loads and such.
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Hi criterion9

I amended the code as you suggested but this had no effect. ?

Adrian
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — You might take a peak at how this plugin was coded to see if there are any specific WP workarounds.

Disclaimer: I have not downloaded the above linked plugin to check that it works nor am I affiliated in any with the developer of the plugin.
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Did you happen to be using a different host for the test page versus including it in WP?



Also:

http://www.catswhocode.com/blog/how-to-create-a-built-in-contact-form-for-your-wordpress-theme
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Nope, same host. The test form is still live, here: http://www.primarycarecommunity.net/formtest.php - this one works

and my slightly modified and wp integrated form is here:

http://www.primarycarecommunity.net/vacancies - this one doesnt

That tutorial looks great and I may give it a go tonight to build the form again, but it doesn't show how to add the file upload box? Do I just copy that bit of code from my own?

Adrian
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Nope, same host. The test form is still live, here: http://www.primarycarecommunity.net/formtest.php - this one works

and my slightly modified and wp integrated form is here:

http://www.primarycarecommunity.net/vacancies - this one doesnt

That tutorial looks great and I may give it a go tonight to build the form again, but it doesn't show how to add the file upload box? Do I just copy that bit of code from my own?

Adrian[/QUOTE]

I would imagine you could modify the script after following the tutorial to add in the upload handling stuff.

Did you happen to get any error messages or anything when including it in your WP install?
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Nope no error messages, it displays just as it should, it just doesnt work, the code originally told it to display a thanks message, I changed it to redirect to a page, but when "send" is clicked, it redirects to index.html (it should redirect to success.php) and I dont get any email from it.
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Nope no error messages, it displays just as it should, it just doesnt work, the code originally told it to display a thanks message, I changed it to redirect to a page, but when "send" is clicked, it redirects to index.html (it should redirect to success.php) and I dont get any email from it.[/QUOTE]
Is it possible your "php_self" might be hitting the wrong place? What is the form's action once the form is loaded?
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Sorry to sound stupid but thats dutch to me. Could you view the source of this page and tell from that? - http://www.primarycarecommunity.net/vacancies
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — 
<form enctype="multipart/form-data" name="send" method="post" action="/index.php">

<input type="hidden" name="action" value="send">

<input type="hidden" name="MAX_FILE_SIZE" value="10000000">

<p>Name: <input name="from_name" size="40"></p>

<p>Email: <input name="from_email" size="40"></p>

<p>Subject: <input name="subject" size="40"></p>

<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>

<p>Attachment: <input type="file" name="attachment" size="30"></p>

<p><input type="submit" value="Send Your CV"></p></form>
[/quote]

The above looks as expected. Can you check the value you are sending to the redirection header statement?
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Well I sort of copied the redirect line of code from an old contact form processfile so not even sure if I had done that right, I will change the code back to the original which said:

// send the message

mail("[email protected]", $subject, $message, $headers);

print "Mail sent. Thank you for using the Mailer.";

}
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Well I sort of copied the redirect line of code from an old contact form processfile so not even sure if I had done that right, I will change the code back to the original which said:

// send the message

mail("[email protected]", $subject, $message, $headers);

print "Mail sent. Thank you for using the Mailer.";

}[/QUOTE]


You could also check is mail() failed:
[code=php]
$worked = mail($var,$var,$var,$var);
if(!$worked){
//an error occurred and the mail was not sent
} else {
echo "Mail was sent successfully";
}
[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — same result, directed to index page.

Would it just be easier to use a wordpress plugin that stores the file on the server and emails me a link to it? Because this is becoming to be a right pain
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Try this and see if you get a page with a line or two of text:

[code=php]
$worked = mail("[email protected]", $subject, $message, $headers);
if(!$worked){
//an error occurred and the mail was not sent
echo "called: mail("[email protected]", $subject, $message, $headers)<br />";
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
} else {
echo "Mail was sent successfully";
}
[/code]
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — I got:

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 107

Line 107 seems to be:

echo "called: mail("[email protected]", $subject, $message, $headers)<br />";
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Oops. Forgot to escape the quotes.
<i>
</i>echo "called: mail("[email protected]", $subject, $message, $headers)&lt;br /&gt;";
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — amended, still no result, same redirection to the index page :-(
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Just saw this:

action="/index.php"
[/quote]

Remove the leading slash.
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — I cant seem to find that at all?

Is that this bit...

echo '<form enctype="multipart/form-data" name="send" method="post" action="'.$_SERVER['PHP_SELF'].'">

were '.$_
SERVER['PHP_SELF'].' is being replaced by /index.php do you think?
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — I cant seem to find that at all?

Is that this bit...

echo '<form enctype="multipart/form-data" name="send" method="post" action="'.$_SERVER['PHP_SELF'].'">

were '.$_
SERVER['PHP_SELF'].' is being replaced by /index.php do you think?[/QUOTE]


That is what it looks like to me. You could try just leaving it blank since the default is to post back to the same place the page is currently. I bet it has something to do with how WP deals with the "prettified" URLs.
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Right, just done a couple of tests, and the form DOES work... as you can see if you fill out my test form here... http://www.primarycarecommunity.net/formtest.php

BUT then I copy the exact same code over to my wordpress page template, thats when it no longer works.

Would you know anything about this?

The code from formtest.php is:

<?php

/* Mailer with Attachments */

$action = "";

$action = $_REQUEST['action'];

global $action;

function showForm() {

echo '<form enctype="multipart/form-data" name="send" method="post" action="'.$_SERVER['PHP_SELF'].'">

<input type="hidden" name="action" value="send" />

<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />

<p>Name: <input name="from_name" size="40" /></p>

<p>Email: <input name="from_email" size="40" /></p>

<p>Subject: <input name="subject" size="40" /></p>

<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>

<p>Attachment: <input type="file" name="attachment" size="30" /></p>

<p><input type="submit" value="Send Your CV" /></p>';

}

function sendMail() {

$from_name = stripslashes($_POST['from_name']);

$subject = stripslashes($_
POST['subject']);

$body = stripslashes($_POST['body']);

$attachment = $_
FILES['attachment']['tmp_name'];

$attachment_name = $_FILES['attachment']['name'];

// check for valid file types

if (is_uploaded_file($attachment)) { //Do we have a file uploaded?

$allowedExtensions = array("doc","docx","txt");

foreach ($_FILES as $file) {

if ($file['tmp_name'] > '') {

if (!in_array(end(explode(".",

strtolower($file['name']))),

$allowedExtensions)) {

die($file['name'].' is an invalid file type!

'.

''.

'<&lt Go Back');

}else{

$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}

}

}

//Let's start our headers

$headers = "From: $from_name<" . $_POST['from_email'] . ">n";

$headers .= "Reply-To: <" . $_
POST['from_email'] . ">n";

$headers .= "MIME-Version: 1.0n";

$headers .= "Content-Type: multipart/related; type="multipart/alternative"; boundary="----=MIME_BOUNDRY_main_message"n";

$headers .= "X-Sender: $from_name<" . $_POST['from_email'] . ">n";

$headers .= "X-Mailer: PHP4n";

$headers .= "X-Priority: 3n"; //1 = Urgent, 3 = Normal

$headers .= "Return-Path: <" . $_
POST['from_email'] . ">n";

$headers .= "This is a multi-part message in MIME format.n";

$headers .= "------=MIME_BOUNDRY_main_message n";

$headers .= "Content-Type: multipart/alternative; boundary="----=MIME_BOUNDRY_message_parts"n";

$message = "------=MIME_BOUNDRY_message_partsn";
$message .= "Content-Type: text/plain; charset="iso-8859-1"n";
$message .= "Content-Transfer-Encoding: quoted-printablen";
$message .= "n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "$bodyn";
$message .= "n";
$message .= "------=MIME_BOUNDRY_message_parts--n";
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_messagen";
$message .= "Content-Type: application/octet-stream;ntname="" . $attachment_name . ""n";
$message .= "Content-Transfer-Encoding: base64n";
$message .= "Content-Disposition: attachment;ntfilename="" . $attachment_name . ""nn";
$message .= $data; //The base64 encoded message
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_message--n";

// send the message
mail("[email protected]", $subject, $message, $headers);
print "Mail sent. Thank you for using the Mailer.";

}


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

</head>

<body>

<?php

switch ($action) {

case "send":

sendMail();

showForm();

break;

default:

showForm();

}

?>

</body>

</html>
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — post duplicated
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Try this?
<i>
</i>echo '&lt;form enctype="multipart/form-data" name="send" method="post"&gt;
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — Holy cow, if this e-mail comes through now i'm going to track you down and kiss you...

*kaching* - 1 new mail

EXCELLENT.

1 last thing now, - I dont want this...

print "Mail sent. Thank you for using the Mailer.";

I want it to redirect to sitename.net/success or any other page i choose.
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — To redirect just use your header("location:... from before. That was for testing so we could see the results without ushering the page away before we could read them.
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — ok i changed that line to:

header("Location: http://primarycarecommunity.net/success"); and i got:

Warning: Cannot modify header information - headers already sent by (output started at /home/adejones/public_html/wp-content/themes/pcc/jobs.php:112) in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 106
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — ok i changed that line to:

header("Location: http://primarycarecommunity.net/success"); and i got:

Warning: Cannot modify header information - headers already sent by (output started at /home/adejones/public_html/wp-content/themes/pcc/jobs.php:112) in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 106[/QUOTE]


It sounds like WP has already started sending content on line 106 or 112 of that file. Is that the file you are editing? What do those lines (and a couple before or after) look like?
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — yep jobs.php is the page template file that contains all this code.

The section around that is:

(lines 104-113)
[code=php] // send the message
mail("[email protected]", $subject, $message, $headers);
header("Location: http://primarycarecommunity.net/success");
}


?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>[/code]
Copy linkTweet thisAlerts:
@criterion9Jul 18.2011 — Try adding an "exit();" after your header? You might have to do a client-side redirection if WP is emitting content that you can't easily control. You might also check if WP has a hook for redirections you can just plug into.
Copy linkTweet thisAlerts:
@djadejonesauthorJul 18.2011 — I still get:

Warning: Cannot modify header information - headers already sent by (output started at /home/adejones/public_html/wp-content/themes/pcc/jobs.php:113) in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 106

but this time, it stopped the rest of the site loading from that point on i think because only my header image loaded.

notice this time it says :113 rather than :112 which is still <html <?php language_attributes(); ?>> because the exit(); pushed it down a line.
Copy linkTweet thisAlerts:
@criterion9Jul 19.2011 — I still get:

Warning: Cannot modify header information - headers already sent by (output started at /home/adejones/public_html/wp-content/themes/pcc/jobs.php:113) in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 106

but this time, it stopped the rest of the site loading from that point on i think because only my header image loaded.

notice this time it says :113 rather than :112 which is still <html <?php language_attributes(); ?>> because the exit(); pushed it down a line.[/QUOTE]


What is on line 106?
Copy linkTweet thisAlerts:
@djadejonesauthorJul 19.2011 — line 106 is: header("Location: http://primarycarecommunity.net/success");
Copy linkTweet thisAlerts:
@djadejonesauthorJul 19.2011 — Sorted :-) I followed this from another site following a google search.

Using output buffering is a good way to ensure that no output gets in the way of sending headers, cookies, etc. At the beginning of the script, put

<?php

ob_start()

?>, and at the end, put

<?php

ob_end_flush();

?>
Copy linkTweet thisAlerts:
@djadejonesauthorJul 19.2011 — last problem, i promise...

on validation, if the wrong file type is attached, the message appears to say so, but then anything under that doesnt load. I think the die command stops the rest of the page loading.

Can I get this to redirect to an error page?

If so, how do I amend this bit of code...

thanks

[code=php]// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<&lt Go Back');

}else{
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}

[/code]
Copy linkTweet thisAlerts:
@criterion9Jul 19.2011 — last problem, i promise...

on validation, if the wrong file type is attached, the message appears to say so, but then anything under that doesnt load. I think the die command stops the rest of the page loading.

Can I get this to redirect to an error page?

If so, how do I amend this bit of code...

thanks

[code=php]// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<&lt Go Back');

}else{
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}

[/code]
[/QUOTE]

The manual tells you all about die. You'll need to decide what you want the script to do before you change it. Sometimes I find it helps to write it out with a pencil and paper in common language so I can "walk through" the logic manually before I write anything.
Copy linkTweet thisAlerts:
@djadejonesauthorJul 19.2011 — OK here's my walkthrough

if its a .doc, .docx or .txt I want the form submitted, I get an e-mail with the attached file and the user redirected to a success page, this does happen now and is great.

If it is not one of those file types, I want the user directed to an error page stating its an invalid file type with a back button to go back and resubmit the form,

OR

a dialog to pop up stating its an invalid file type, they click ok, and they can then select another file.

Whichever is easier to do.
Copy linkTweet thisAlerts:
@criterion9Jul 19.2011 — OK here's my walkthrough

if its a .doc, .docx or .txt I want the form submitted, I get an e-mail with the attached file and the user redirected to a success page, this does happen now and is great.

If it is not one of those file types, I want the user directed to an error page stating its an invalid file type with a back button to go back and resubmit the form,

OR

a dialog to pop up stating its an invalid file type, they click ok, and they can then select another file.

Whichever is easier to do.[/QUOTE]


You could do it either way.

Option 1 (psuedocode):
<i>
</i>if(isInvalidType()){
Stuff was wrong with it, lets spit out some content and then "exit"
} else {
continue on as planned, nothing to see here
}


Option 2 (psuedocode):
<i>
</i>if(isInvalidType()){
Stuff was wrong with it, lets spit out some javascript or a "warning" inline
and then continue to display the form from before
we will need to check if values were submitted so we can put them
into the form before it gets sent
} else {
continue on as planned, nothing to see here
}
Copy linkTweet thisAlerts:
@djadejonesauthorJul 19.2011 — OK lets go with option B, could you help me implement this?

I do really appreciate your help, you have been a life saver.
Copy linkTweet thisAlerts:
@criterion9Jul 19.2011 — OK lets go with option B, could you help me implement this?

I do really appreciate your help, you have been a life saver.[/QUOTE]


I'll try to explain in a little more detail...sadly I don't have the time right now to merge it into your existing code.

(Totally untested, concept only)
[code=php]
/* This stuff should be with your other stuff that validates the submission */
function isInvalidType($file){
$acceptedTypes = array('doc','txt'); //add more as needed
$mime = mime_content_type($file['name']);
if(in_array($mime,$acceptedTypes)){
return false; // this means the mime returned in one of our acceptable ones
} else {
return true; // this means the mime returned was not in our list
}
}

if(!function_exists('mime_content_type')) {
function mime_content_type($filename) {
/* You might need to add the docx, etc variants that MS office now uses */
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',

// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',

// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',

// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',

// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',

// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',

// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$ext = strtolower(array_pop(explode('.',$filename)));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
}
elseif (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
else {
return 'application/octet-stream';
}
}
}

$formMsg = '';
/* don't forget to change your nameOfField to whatever you are using in your form */
if(isInvalidType($_FILES['nameOfField'])){
//Stuff was wrong with it, lets spit out some javascript or a "warning" inline
//and then continue to display the form from before
//we will need to check if values were submitted so we can put them
//into the form before it gets sent
$formMsg = 'this is the error message that you see';
} else {
//this is were the "working" code goes
// continue on as planned, nothing to see here
}
[/code]

Totally untested (concept only)
[code=php]
//this goes where you are echoing the form

//each form element will need to be populated:
?> <input type="text" name="formElement"<?php if(isset($_POST['formElement'])){
echo " value="".$_POST['formElement'].""
}?> />
<?php
//this goes where you want any messages to be displayed
if(isset($formMsg) && !empty($formMsg)){
echo $formMsg;
}
[/code]
Copy linkTweet thisAlerts:
@abigailjoyAug 22.2020 — If you want to extract all of your attachments from your emails, so you can try the IMAP Attachments Extractor. With the help of the **Softaken IMAP Attachment Extractor**, you can easily extract attachments from the IMAP server without making any changes at your documents. It allows your extract attachments in batch for quick processing. The IMAP Attachment Extractor is 100% safe and secure. IMAP Attachment Extract is free to save your files at the desired location. It easily exports attachments of big and large files. (Excel, PDF, jpg, HTML and any other files). It supports Windows 10,8.1,8.7,7, XP, and prior versions.IMAP Server Attachment Extractor extracts all your attachments very smoothly without formatting your data and any other files.
×

Success!

Help @djadejones spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...