How to Write a PHP Script to Send a Trackback
Written by Brian on January 8, 2008 – 10:11 pm -Don’t know what a trackback is? Check out this set of articles for a bit more information.
Assuming you do know what a trackback is, how do you send one - technically speaking? And how can we write a php script to send one?
A trackback is a simple ping - an HTTP Request. It is specially formatted with a limited amount of information. The receiving server is set up to handle that information and use it to create the comment based on your trackback ping.
The Trackback API As Per Moveable Type
Since Moveable Type introduced the trackback, they were the ones responsible for writing the standards and API. You can read through the trackback technical specs on the SixApart website.
In order to send a trackback ping with a PHP script, there’s a few things we need to know…
- The ping is in the form of an HTTP Post Request.
- The ping is sent to the trackback URI of the receiving post.
- The request must have a content-type header defining it as
application/x-www-url-encoded - All of the parameters included in the content should be url encoded.
- The standard parameters are “title,” “excerpt,” “url,” and “blog.” Only the “url” parameter is required.
- The server will send a short XML response - containing
<error>0</error>if there was no error, and<error>1</error>along with a<message></message>element if there was an error.
With that in mind, we can begin to write our script. We need to do four things.
- Receive input from the user (the blog url, title, excerpt, etc).
- Create the header and format the information correctly
- Send the header and get a response
- Read the XML to see if it was successful or not
Getting Input From the User
Getting input is pretty simple. We’ll create a form in HTML, set the action to the page containing the script, and set the method to post.
You’ll want a text input for the URL, title, and blog. You could use either a text input or a small textarea box to take the excerpt.
Here’s some sample HTML to create the form. You’d want to add some css to make it look pretty, but you can do that some other time.
<form id="trackback-form" action="trackback.html" method="post"><fieldset id="trackback"><label for="trackback-uri">Trackback URI:</label> <input id="trackback-uri" name="trackback-uri" type="text" /> <label for="title">Post Title:</label> <input id="title" name="title" type="text" /> <label for="url">Post URL:</label> <input id="url" name="url" type="text" /> <label for="excerpt">Excerpt:</label> <input id="excerpt" name="excerpt" type="text" /> <label for="blog">Blog Name:</label> <input id="blog" name="blog" type="text" /> <label for="submit"></label> <input id="submit" name="submit" type="submit" value="Send Trackback Ping" /> </fieldset></form>
Simple… but effective. Set the “action” to the name of the file with the form in it. We’ll add the php script to the top, and the form will just return the information to itself.
Reading the Information from the Form and Encoding It
Once you hit submit, all of the form information will get sent to the file so that the script - at the beginning of the file - can handle it.
All of this form information is in the $_POST array. The ‘key’ for each element is the ‘name’ attribute of the form element.
We’ll also need to use the urlencode() function. This takes the input and escapes any special characters (like spaces) so that the input is in the proper format.
Here’s a snippet to read the $_POST variables, encode them, and store the information in some new variables. Note that you’d probably want to include some error checking (i.e. check to see if the $_POST[] element is empty, and set an error message if it is). I’ll leave that up to you.
$title = urlencode($_POST['title']); $url = urlencode($_POST['url']); $excerpt = urlencode($_POST['excerpt']); $blog_name = urlencode($_POST['blog']); $trackback_uri = $_POST['trackback-uri'];
Now that have all of our information, we need to create the HTTP header.
You could format this as a special string, but php has a built in function - stream_context_create - that will take a formatted array and use it to send an HTTP header. That’s what we’ll be using.
A HTTP header looks something like this…
POST http://targeturl.com Content-Type: application/x-www-form-urlencoded; charset=utf-8¶mvar=Param+Value¶mvar2=Param+Value+2
In order to use stream_context_create, we need to create an array in the following format.
$params['http']['method']is the method (POST)$params['http']['header']is the optional headers (in this case the Content-Type)$params['http']['content']is the actual content - the parameter variables and values. This will be the string containing all of the trackback information (the post url, post title, blog name, and excerpt).
So, to create the array we need, here’s a short snippet of code, picking up where we left off before…
$params['http']['method'] = "POST"; $params['http']['header'] = "Content-Type: application/x-www-form-urlencoded"; $params['http']['content'] = "title=$title&url=$url& blog_name=$blog_name&excerpt=$excerpt";
Note that because we used double-quotes (” “) when declaring $params['http']['content'], we could simply include the variables in the string - and PHP will punch in the values for us.
Send the Header! Pings Away!
Now that we’ve created the array, we’re ready to create a context and actually send the HTTP request to the target website.
Like I said before, we’ll use the function stream_context_create to do the work. Then we’ll fopen the target, write the header, fclose the target, and save the response.
stream_context_create just needs one parameter - our formatted array.
fopen will take a few parameters - the target URL ($trackback_uri), the mode (’rb’ for read-only, binary), a boolean option which is false for us, and the context we created with stream_context_create.
Here’s the actual code snippet. (Note: You can only use a context in fopen() in PHP 5 or greater. You’ll need to manually make the header if you’re using PHP 4)
// Create the context from the formatted array $context = stream_context_create($params); // Open a stream to the url, save it in the pointer $fp $fp = @fopen($trackback_uri, 'rb', false, $context); // Send the header and get the results, saved in $response $response = @stream_get_contents($fp); // Always close for good measure fclose($fp);
At this point, you should be able to send trackbacks just fine.
Read the Result Message - Error or No?
Now we need to read the results (saved in $response) and find out if we were successful.
You could just echo it. The xml tags will be hidden by the browser, so the user will just see the output. However I like to have the script read it so that I can output a customized message.
One way to do this would be to build an xml parser and find out directly what’s in the element. This is a lot of work for one error message, though.
Instead, we can use our knowledge of the standard format of the message to good use.
First, we know that a success is always returned with . If we do a stripos or substr search to see if that string is included in $response, we’ll know if the test was successful or not.
Then, we can isolate the element and echo that.
Here’s the code I used to do it. Not sure if it’s the most efficient way to do it, but it works… so why not?
// If this is true, there was no error if (stripos($response, '0')) $outcome = "All clear! Trackback was sent successfully."; else { // Find the beginning and end of the message element $start_resp = stripos($response, ''); $end_resp = stripos($response, ''); // substr will return the actual message element, // with the tags included $outcome = substr($response, $start_resp, $end_resp - $start_resp - 1); // Replace the tags with blank space $outcome = str_replace('', '', $outcome); $outcome = str_replace('', '', $outcome); $outcome = "Error: " . $outcome; } // Echo the results. I formatted 'error' to be red. echo " $outcome ";
Recap
Well, there you have it. Put all that code together and you should have a functioning example.
Even if you’re not going to use this on your own site, this is a pretty cool learning activity. You get to see how contexts and streams work, sending an HTTP header to get a response.
We also make use of the urlencode() function and use stripos() and substr() to do some half-assed xml parsing. You could use a similar method for reading HTML and parsing tags.
Enjoy, and be sure to leave a comment if there’s something else you’d like to see explained in a tutorial.
Posted in Nerds at Work, Programming |
Tags: PHP
Find that post enjoyable or informative? Why don't you subscribe to the feed for Nerds at Work. Or, subscribe to the site-wide feed and catch up on all my antics.
12 Comments
1 Trackbacks/Pingbacks
-
Pingback:
This Life of Brian » Blog Archive » Good-Tutorials.com: Niche Article Sites to Help Increase Traffic
November 29, 2008

Great post. I am having troubles with my trackback.php file.
Hopefully if this doesnt help mabe you can help.
DOTTED - http://www.newsdots.com/tutorials/how-to-write-a-php-script-to-send-a-trackback-web-cash/
Thanks for the comment. Let me know if you can’t get your trackback.php file working. Can’t promise anything, but I’d be glad to take a look at it.
The trackback file I have is from a script called Pligg, its a Digg like website. So when the user submits a URL, the script looks to see if the submission has a trackback, it does, it fetches it, but it doesn’t ping the original source. So if I submitted your blog, it would find and store the trackback, but your blog would never know that it was mentioned on my site.
I dont see a ping feature in the trackback.php file I use, so maybe thats the problem.
I could email you the file and maybe you can see something I am missing.
Anyways, email me if you want or post a response here.
Thanks.
Hello there. Just found your site. Great job! I like it much.
thanks
Nice information
A fantastic site, and brilliant effort. A great piece of work.
nice…how to put this script in our own scripts??
hey you are missing the ) from this line, just took me longer than it should of!!
$url = urlencode($_POST[’url’];
Thanks for the heads up. Fixed the typo.
Hi,
I am new to this trackback funda. I tried to implement this in my php scipt. It doesn’t show up anything. Unfortunately echo statements are supressed out in our website. The blog feature present in our website is developed from scratch. I read that some blog platforms doesn’t support TrackBack. How to identify the blog platform and know weather it supports trackback or not? Can any one help me how to do this?
Also we need to implement the vice versa functionality i.e, we need to provide trackback url in our blogs and if some one sends trackback to our blogs we need to send a XML response. Any information will be greately helpful.
Hey man nice blog, just wanted to show some love