How to run custom PHP code in WordPress – the right way

I’ve recently been asked to look at integrating some complex forms into a WordPress powered site. None of the current plugins satisfied our (multi-lingual) needs, so the next simplest approach appeared to be integrating PHP code with WordPress. (I had considered integrating Kohana, my favoured PHP framework, as there is a module that allows easy integration, but this seemed overkill for a few forms).

Running PHP code from within WordPress is nothing new. There are numerous plugins. I opted for Exec-PHP, partly because it gets high user ratings and the developer has provided feedback on his site, and partly because it worked for me first time.

Having installed the plugin, it was simple to create a Page, add some PHP code using the traditional PHP tags . However, once I started writing code in anger, I began to understand that to run the code efficiently, and to give the end-user a good experience, simply placing code in the page (blog entry) is too simplistic.

The key issues, is that the PHP code is evaluated at run-time, using the PHP eval() function. This function is highly inefficient. So, the first improvement was to move the bulk of the code to a separate PHP file and include it. This way, the only code evaluated is the include statement.

I chose to put my included code in a folder called custom-php within the WordPress wp-content folder. The best way to reference the file is using the ABSPATH constant provided by WordPress, as follows:

<? require_once(ABSPATH. '/wp-content/custom-php/contact-form.php'); ?>

Now I can simply place my PHP code in the external file for inclusion. So far, so good. But it wasn’t long until I hit my next hurdle. I need to send an email when the form is submitted. Nothing too taxing there. In fact, this is super simple thanks to the @wp_mail WordPress tag.

Now, normally when writing a PHP form script, the form is POSTed to the server, the server sends the email using some SMTP library, and then the script renders an HTML page ( or View if using an MVC framework). And if you’re a good developer, you’ll actually perform an HTTP redirect instead, to prevent double form submission (see this article on Wikipedia).

However when PHP code is executed within a WordPress page, some of the response has already been sent. This has two side effects:

  1. Firstly, the page renders in the browser until it reaches the script; waits until the email has been sent, and then continues rendering the rest of the page/
  2. Secondly, as part of the response has already been sent, it is not possible to modify the HTTP headers, and hence a redirect cannot be sent.

So, we need a way to run the script before the response is sent. Here’s my solution:

Firstly, the PHP page included in the WordPress page, contains an HTML form. I add to the form a hidden field so that it can easily identified when POSTed e.g.:

<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="form-name" value="contact" />
<div style="text-align:left; border: 1px solid #bbb; padding:10px;">
	<div>
		<label for="name">name</label>
		<input type="text" name="name" id="name" />
	</div>
	<div>
		<label for="email">email</label>
		<input type="text" name="email" id="email" />
	</div>
	<div>
		<label for="message">message</label>
		<textarea name="message" id="message" style="width:250px; height:100px"></textarea>
	</div>
	<input type="submit" value="go" />
</div>
</form>

Now, when the form is submitted, I am able to detect it, and therefore process the form submission prior to rendering the page. I do this by adding some code to the WordPress page template. I opted to add some more include code to the first line of the header.php file within my theme, like so:

<?php require_once(ABSPATH. '/wp-content/custom-php/contact-form-test.php'); ?>

There may be a better place to put this code (wp-config, wp-settings ?). I’m no WordPress guru, and I’m happy to be educated.

The contact-form-test.php code is as follows:

<? 
    session_start();
    if($_POST['form-name'] AND "contact" === $_POST['form-name']) {
         require_once(ABSPATH. '/wp-content/custom-php/contact-form-functions.php');
	 send_message();
     }
?>

This is fairly simple code. We test to see if our form was posted, and if so include the code to send the email. No point including it unless we need to. The key is, the code is now included before any other WordPress code executes.

For completeness, the contact-form-functions.php is as follows:

<?
function send_message()
{
	$subject = "Test email form WordPress";
	$body = $_POST['message'];
	$recipient = "rocky-racoon@abbeyroad.co.uk";

	$success = @wp_mail($recipient, $subject, $body);

	if($success) {
		session_start();
 		$_SESSION["mail_message"] = "Thank you. your message has been sent.";
		header( 'Location:  '.$_SERVER['HTTP_REFERER'] ) ;
	}
	else {
		$GLOBALS["mail_message"] = "Euston, we have a problem.";
	}
}
?>

We use WordPress’ mail functionality to send the email. If it sends OK, we perform an HTTP redirect. First we also set a flashvar using the PHP $_SESSION as, due to the redirect, we cannot use a $GLOBAL as it obviously goes out of scope.

One final change is required to contact-form.php to retrieve the success (or error) message. The following code is placed before the HTML form:

<?php
	if(isset($GLOBALS["mail_message"])) {
 		echo "<p>".$GLOBALS["mail_message"]."</p>";
	}

	if(isset($_SESSION["mail_message"])) {
 		echo "<p>".$_SESSION["mail_message"]."</p>";
		unset($_SESSION["mail_message"]);
	}
?>

This solution is useful for an custom PHP code that is server-intensive, be it database queries, web service calls or sending email.

Hope you found this useful

Tags: ,

28 Comments

David Lyle commented on November 11th, 2009 at 5:38 pm

Excellent tip to Include the php code rather than just drop it in the page/post!

Thanks for sharing

carlitos commented on November 17th, 2009 at 9:24 am

I’ve got a problem, I got this page done topxxname.php and uploaded it to wpcontent/themes/mytheme/ and when i try to open on browser that file my wp send me to the 404 page!

How i can add custom php pages to the themes folder and run them?

If i do ur tutorial it will work ?

Thanks

badlyDrawnToy commented on November 17th, 2009 at 10:49 pm

@carlitos – you can’t just upload a file and access it using WP. Everything goes through the controller, index.php. You need to create a PAge within WP, and run your code within this.

carlitos commented on November 19th, 2009 at 6:09 am

yeah thank you i finally figure it out

Michael commented on November 20th, 2009 at 11:48 pm

Thanks for taking the time to post this. It has saved me hours and at my age…that is important :)

Joe commented on December 1st, 2009 at 8:01 pm

Thanks for this article. Makes sense but I cannot get it to work.

When I first display the form page it begins with this error:

Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/myacctname/public_html/mywpsitename/wp-content/themes/formtheme/header.php:8) in /home/myacctname/public_html/mywpsitename/wp-content/custom-php/contact-form.php on line 2

In my themes header.php the first line reads:

…and in “contact-form-test.php” the entire module is

…and in “contact-form-functions.php” the entire module is

The error message appears, followed by the contact form itself. If I fill out the contact form and click GO then I get the “Thank you. your message has been sent” message, but I never get the email.

As a test I tried commenting out the session-start command at the beginning of “contact-form.php”. and that did eliminate the error message, but now when I fill out the form and click GO I no longer get the ‘thank you’ message.

I researched the error message and read that it might be caused by stray nonblank characters either before the but it looks like my Notepad++ is set to Unix/ANSI so I don’t think that is the problem.

Any suggestions on 1) why the error message, and 2) why I got the “…your message has been sent” and yet received no email?

TIA

badlyDrawnToy commented on December 1st, 2009 at 8:21 pm

Hi Joe. You’re on the right track with the stray characters. To start a session the headers need modifying in the HTTP response. This cannot happen once the response has started being written. This is a classic gotcha with PHP when you are mixing server-side code with client-side HTML. If you have so much as a space or carriage return outside of the PHP tags, prior to the session_start call, then you are actually sending a response. You have to work through ALL the files that might be loaded before the session_start call. This includes those loaded by WordPress such as index.php, wp-config.php. If there’s a new line after the closing PHP tag, this cvould ber the culprit. Often, you’ll find there is no closing tag, to avoid this error. Quite likely it’s header.php, contact-form-test.php, contact-form-functions.php or contact-form.php.

If sessions aren’t working, then you will not see the message. It needs to be set in session so it can subsequently be pulled out after the redirect.

As to why you’re not receiving email, the code I posted is using Worpress’ underlying mail function. This means that whatever WP uses, the function uses. Can you send mail outside of this script? If not, you might need to configure WP with an SMTP plugin, rather than using the native sendmail() function.

god luck

Joe commented on December 2nd, 2009 at 3:54 am

Thanks for the encouragement, but I looked at the header.php and the other files you mentioned but no luck: I’m still getting the “headers already sent” message whenever I display the contact form page (all other site pages are fine).

I also tried relocating the “require_once(ABSPATH. ‘/wp-content/custom-php/contact-form-test.php” to the wp-configure.php, and also deactivating all plugins but still I get the same “headers already sent” error message.

If you have any other ideas – or perhaps know of some diagnostic tool to perhaps capture the outgoing stream and that would reveal the culprit (i.e., the code that is possibly sending the stray character(s) after the php closing bracket) then I’m all ears.

Shaun Tarves commented on March 10th, 2010 at 5:48 pm

I think the problem Joe is having is the same one I am having. When you try to use session_start() in contact-form.php where contact_form.php isn’t the only thing included on the page, PHP complains that headers are already sent.

My form sends just fine, but I can’t extract the error message to display it. Here’s my set up:

contact-form-test.php is the first line in header.php

contact-form-functions.php does its job and sends the mail through WordPress

contact-form.php is included from index.php since I want the form to appear on my home page, toward the bottom. So when contact-form.php loads, the session_start() in line 2 of contact-form.php that should resume the session to pull out the error message makes PHP complain that headers have already been sent out (since it’s almost done rendering the entire page). I can’t see how any of this would actually work.

Maybe you can shed some light on how you got this going? Perhaps showing the code for the page that calls contact-form.php would be helpful.

Shaun Tarves commented on March 10th, 2010 at 7:38 pm

TO ANYONE HAVING PROBLEMS WITH THIS

I finally fixed this after nearly a day of debugging. Here’s the strategy:

in the header.php of my template, I have:
if (!session_id()) {
session_start();
}
require_once(ABSPATH. ‘…/contact-form-test.php’);

contact-form-test.php:
if($_POST['form-name'] AND “contact” === $_POST['form-name']) {
session_register(‘mail_message’);
require_once(ABSPATH. ‘…/contact-form-functions.php’);
send_message();
}

contact-form-functions.php
function send_message()
{
$subject = ‘Test email form WordPress’;
$body = $_POST['message'];
$recipient = ‘shaun@tarves.net’;

$success = @wp_mail($recipient, $subject, $body);

if($success) {
$_SESSION['mail_message'] = ‘Thank you. your message has been sent.’;
session_write_close();
header( ‘Location: ‘.$_SERVER['HTTP_REFERER'].’#contact’);
}
else {
$GLOBALS['mail_message'] = ‘Euston, we have a problem.’;
}
}

Doing it this way allows you to only have to include session_start() one time, and the key here is session_write_close(). For some reason, upon page redirection, PHP often loses session data. Ensuring the write is closed makes everything work.

Thanks so much for this great tutorial!

badlyDrawnToy commented on March 11th, 2010 at 9:56 am

Shaun, Joe

I just took a look at my code, and I had modified it since the orignal post. I moved the session_start() call to the contact-form-test.php include. Looking at your fix, this might be the reason. (I’ve modified this post to show the update).

and yes, PHP will lose all session data unless you tell it otherwise. Check out the wp_unregister_GLOBALS() function in wp-settings.php

tudoquemegustaeillegal commented on March 23rd, 2010 at 2:53 pm

hi,

the only way I got this to work was to put the session_start() in the index.php of my theme ? http://bugs.php.net/bug.php?id=14636

Neil commented on March 29th, 2010 at 11:57 am

Hi
Thanks for this.
I also found a plugin which inserts a shortcode for php includes.
http://www.amberpanther.com/contributions/wp-include-file/
It would be good to hear your thoughts on this. Goo didea or not?
thanks

badlyDrawnToy commented on March 29th, 2010 at 12:27 pm

Neil

Plugin looks good. Only thing to watch is *when* it executes your code. If it calls the include part way through the page, you could have session issues

Koleksi Web commented on May 7th, 2010 at 10:42 am

Thanks for the tips! I will try this script in my WP blog

Lenin commented on June 12th, 2010 at 8:43 am

Let me try ;) I am switching from blogspot to wordpress

Blog Setup Service commented on August 19th, 2010 at 11:36 am

I’m also giving it a try. Great article by the way.

Sergey Lempert commented on January 20th, 2011 at 7:04 pm
David commented on January 25th, 2011 at 6:36 am

Great article!
Definitely not the way I would have done it, but I learned a lot. I really do appreciate your humility in admitting wordpress isn’t your trade, although Php obviously is. I’m sure your method is still better, but I would have developed a seperate page template. I guess I’m just more comfortable with my approach. It wouldn’t require any Php getting inserted into backend, where making content, instead it would all stay in the Php template files. Customize the template appropriately to the form, then when making a post, choose that template instead. (kinda like page v post, or custom post type).

I didn’t know about the WP email function, and the suggestions you gave on that were great. It’s helpful not to resort to regular php functions when WP already has them integrated. Thanks!
~David

wilson keenan commented on January 28th, 2011 at 3:54 am

Hi – really great post. Thanks so much.

I’m in the process of trying to run a few PHP files to handle an HTML form I have on one of my pages: https://globalcitizenyear.org/donate/donation-form-2 – - the handler sends an API call to PayPal.

I can get this to work quite well in simple PHP (outside of wordpress – where I can actually use the .php file in the “action” and also rely on an error page etc), but I have been unable to get it to work in WordPress. Do you have any thoughts?

Also, given that you are taking care of this all on one page – how could you force the form to hide after submission?

My organization really needs to get this issue taken care of

badlyDrawnToy commented on January 28th, 2011 at 1:45 pm

Hi David

I wrote this post a while back and have since used templates much more. I ave a love/hate relationship with WordPress and PHP (I was a Java dev, and have noe moed onto Django/Python).

A standalone template is an easier option. Not even sure these were available when I wrote this article? The key point about Response Headers is still a potential gotcha.

badlyDrawnToy commented on January 28th, 2011 at 1:47 pm

Wilson, like the previous commenter said, a standalone template might be easier. Couldn’t begin to guess what issue you’re having re: PayPal API. First thing I’d check is that your standalone script executes fine form your webserver – i.e. it’s not an connectivity issue

Good Luck

wilson keenan commented on January 29th, 2011 at 2:44 am

Cool – thanks!

So, my question is pretty easy then –

If I use a require_once function for my PHP form handler (in the header.php file) as part of a condition that says: If form submitted, require this .php file.

And, this form handler php file starts a session, will it work. That may not be enough info, but might you have any suggestions that could help me detect the errors? Right now I’m not getting anything other than something that tells me the API did not work.

All of this is working at: http://www.wilsonkeenan.com/learningphp/DoDirectPayment.php – - it’s just when I try to move everything into PHP = not working…

Judd Exley commented on April 1st, 2011 at 7:55 am

Mate, you’re BRILLIANT. You just saved me about 2 hours of Googling and swearing.

Thank you!

Thomas commented on May 1st, 2011 at 4:38 pm

great finally I found the correct way to include my file :-)

Vikram Kothari commented on May 5th, 2011 at 8:10 pm

You are very right about eval being ineffective. But I am not sure how just moving the code to a separate file will solve the issue? From the manual, the include statement also evaluates the content of file.

Steve commented on May 21st, 2011 at 9:32 am

Great job! I have been seraching for this, thanks.

Andy commented on May 26th, 2011 at 5:46 am

I guess this is a question for everyone in this comment thread, but how does this method of including php via ABSPATH in the main template file compare to making custom templates for pages with php functions? I’m just wondering if one method will result in better end-user experience compared to other.

Colophon

badlyDrawnToy is the blog of Howie Weiner, a Manchester based freelance web developer.

Howie specialises in Django, PHP and Java web application development.

This site is no longer updated. You can now follow Howie at howieweiner.co.uk

View Howie Weiner's profile on LinkedIn
View Howie's twitter feed

Tags

Destinations