An Example Rich Text Editor Image Upload with PHP

After my previous image uploader and turbogears image uploader posts, the overwhelmingly most requested information has been a PHP implementation of the upload script. I’m not much of a PHP guru. Luckily, a few users have posted possible solutions for this. I’ve added an editor to this post that uses a PHP script to process the image on the server. The original image uploader script is compatible with the newer 2.4 version of the editor.

Whithout further delay, here is the editor. Just click on the “insert image” link under “Insert Item” to test the upload functionality.

Here is the initialization JavaScript for the editor on this page. You can find information on Yahoo’s Rich text editor here. You can read my YUI image upload post for more information on the image uploading extension if you need as well.

<link rel="stylesheet" type="text/css" href="">
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<!-- Visit the previous post on the image uploader to download the image uploader JavaScript -->
<script src="/wp-content/uploads/2007/10/yui-image-uploader.js"></script>
<script type="text/javascript">
var myEditor = new YAHOO.widget.Editor('example_editor', {
 height: '300px',
 width: '522px',
 dompath: true,
 animate: true
// Don't forget to change the parameters of your function to point to the correct uploader script.
yuiImgUploader(myEditor, '/wp-content/uploads/2007/12/yui_img_uploader.php','image');

And here is the PHP script that you need to host on your server. This is just an example. I’m not an expert at coding PHP so there are probably bugs/issues with this that I haven’t addressed. Remember, the location on your server that you host this script will need to be the 2nd parameter of the yuiImgUploader function in your JavaScript.

header("content-type: text/html"); // the return type must be text/html
//if file has been sent successfully:
if (isset($_FILES['image']['tmp_name'])) {
 // open the file
 $img = $_FILES['image']['tmp_name'];
 $himage = fopen ( $img, "r"); // read the temporary file into a buffer
 $image = fread ( $himage, filesize($img) );
 //if image can't be opened, either its not a valid format or even an image:
 if ($image === FALSE) {
  echo "{status:'Error Reading Uploaded File.'}";
 // create a new random numeric name to avoid rewriting other images already on the server...
 $ran = rand ();
 $ran2 = $ran.".";
 // define the uploading dir
 $path = "editor_images/";
 // join path and name
 $path = $path . $ran2.'jpg';
 // copy the image to the server, alert on fail
 //you'll need to modify the path here to reflect your own server.
 $path = "/wp-content/uploads/2007/12/" . $path;
 echo "{status:'UPLOADED', image_url:'$path'}";
} else {
 echo "{status:'No file was submitted'}";

A couple things to remember:

  1. Don’t forget to create the directory that the images will be stored in.
  2. Don’t forget to set the file permissions appropriately so your web server can write images to the directory you’re saving in.

Feel free to leave a comment or contact me if you have questions or suggestions.

This entry was posted in Programming and tagged , , , , , , . Bookmark the permalink.

102 Responses to An Example Rich Text Editor Image Upload with PHP

  1. Dennis says:

    I put a breakpoint on your response in yui-image-loader.js. You have warning information about headers already being set coming back from your php script. It’s causing the response to be invalid JSON and thus causing the script to fail. The error is logged but the console isn’t writing the error for some reason. This is probably because you need to tell the YUI logger to log debug info or something.

  2. Robyn says:

    Weird. Where else would the headers be set? My uploader php file has the first line of

    header(“content-type: text/html”); // the return type must be text/html

    and that’s it, that I know of. If the YUI RTE js files were setting headers, everyone else would be having this problem, too, right?

  3. Dennis says:

    You’re correct that if it was the JS, everyone would be having problems. JS can’t set headers anyway. You’ll have to work with the response from php directly and get it to return the Json object w/ out the warning information.

  4. Robyn says:

    Ok. I’ll see what I can do. Thanks so much for your response and guidance!

  5. Robyn says:

    Hey, by the way, just wanted to let you know that the problem turned out to be that I had a line break in my PHP file before the <?php tag.

    I guess that blank space was what was “sending header information”. I don’t normally deal with much AJAX or JSON stuff, so didn’t realize an extra space would cause a problem.

  6. Brad says:

    Hi Dennis,

    I’m running into a similar issue that others have had. I’ve implemented the yuiImgUploader and am using the PHP script you wrote, though it’s not uploading anything.

    Unfortunetly I’m not all that familiar with PHP uploades or even Javascript, and going through the user posts here I have not been able to determine the issue. As suggested, I tried using FireBug, though my understanding of this plugin is extremely basic.

    Here is the page I’m working on.

    Path to uploaded files: /uploadedFiles/

    I’m building a CMS, so i’ve added some things to the editor already. If you could take a look and maybe point out where i’ve gone wrong, that would be greatly appreciated! (Note that i haven’t yet adjusted the style sheets to resolve the upload input field being 0px wide in IE)

    Thanks in advance!

  7. What happend on The Local Sever with out Internet Connetion says:

    what happened, if we implement this RITCH TEXT edtior, on the local serevr and not having Internet connetion, it will not work

    Arvind Baghel

  8. Dennis says:

    You do need a web server but you don’t need an Internet connection. You could for instance, run your web server on localhost instead. You can’t however direct the script to a file location. You need to actually listen for a connection and process the data.

  9. Sky says:

    i get the browse button but no upload text next to it, any idea where i went wrong?

  10. Sky says:

    sorry, i had the wrong script yui js script, when i use the one from this page page i get NO ‘browse’ button? i ‘ve got an alert message in the script which shows i’m getting to the file but then i’m lost 🙁 any help? here’s the script i’m using:

  11. fakhru says:

    nice article
    i have downloaded the whole api, when i start and click on rich text editor the firefox crashes every time i do the same thing is happen. i dont know whats wrong with the script. can anybody tell me the solution. in rest of all browser it is working.
    i m using fire fox 3.0.7 …..
    if some one can reply its best for me
    thanx a lot

  12. Dennis says:

    I haven’t ever heard of FireFox crashing because a script. I bet it’s related more to your firefox installation than it is to the javascript or HTML. You might try trimming out pieces of the code until you find something that works and something that causes the crash.

  13. fakhru says:

    thanx a lot for your reply Dennis.
    ya i have done all the trimming part only one java script which gives me problem…. is
    “editor-min.js” when i remove this script it works fine but without fomatting and tab only text area is displaying …

  14. fakhru says:

    hello everyone,
    please if any one can send me trimmed version of editor then i ll implement in my site please
    its s humble request.

  15. noob says:

    Hi, may i have the fully working code/script??
    Im new to YUI

  16. kornesh says:

    im using version 2.7…but its not showing anything when i past your code on the html file and i upload it to the server.
    you’re welcomed to use my email address.TQ

  17. Dennis says:

    noob: the latest client code is on the Image uploader with YUI 2.6 page.

  18. Dennis says:

    kornesh: I think the 2.6 code works with 2.7.

  19. Arun Kaur says:

    Very nice and helpful article.
    Many thnx goes to author.

    I share with this site for various links….

  20. This worked very well for me, and you have certainly just made things easier for my clients! Thanks.

  21. gtlitc says:

    Thanks for the RTE image upload. Great work. I am looking at using it in a project of mine where I need an RTE with image functionality to work with my custom CMS functionality. Iam woking on a php script that handles the creation of more useful filenames for the images (SEO) things like “title-of-article-001-img01.jpg. This is going well but I would really like to impliment functionality so that when an image is deleted in the editor it also gets deleted on the server. Has anybody any thoughts on how this would be done? Would need a way of hooking into the delete operation in the RTE and then passing that image-redf to a delete script on the server?

  22. Dennis says:

    I haven’t reviewed every hook available in the editor, but I bet there is a way to capture when the image is deleted. It shouldn’t be much different (and actually easier) than the upload handler to send a command to your server to delete the image.

  23. Maria says:

    i cant get the files from there… can any one send the files?

  24. David says:

    Hi Dennis,
    I tried using yui-image-uploader26 (with yui27) and it successfully uploads the image (I can see it on the server), but still throws an error ‘upload failed:Expected hexadecimal digit’ and does not display the image in the editor. Any ideas?


  25. Dennis says:

    Use Firebug to see what the server response is. It looks to me like the server isn’t sending the response correctly.

  26. bentsen says:


    I have a little probleme. When i clic on upload button, my image is uploaded but the name of the image appear just seconde or less in the field “Image Url: and he disappear!!!!.

    Any ideas ?

    PS : thanks for your great job!!!

  27. Hi Dennis,

    First of all thanks for your code, image upload directly into a rich text editor is an essential feature.

    I have written some code that implements what you have written. It would be great if you could post it on your site. The URL is

    Thanks and Regards,


  28. Pingback: An Image Upload Extension for YUI Rich Text Editor | All My Brain

  29. Pingback: Example Image Upload with YUI Rich Text Editor 2.7.0 | All My Brain

  30. Brilver says:

    image is uploading to the richtext area. But when submitted only the text are submitting. Please help

  31. Dennis says:

    Images are uploaded at the time you select them and they appear in the editor. Uploaded text contains links to the images only.

  32. Brilver says:

    I know, but the link to the uploaded image is not submitting. Only the text pre loaded with the page in textarea is submitting.. Please help..

  33. Dennis says:

    Sounds like something not related to the image uploader. I think you’ll find the best support for this on this problem on the yui forum.

  34. Brilver says:

    I checked can’t find a solution..
    These are the codes i tried.. Please help

    My test file is

  35. Chito says:

    Hi Dennis,

    Your example is amazing, and I want to implement it to my website.

    But I have followed your sample, there’s something wrong with my editor.

    Here’s my test editor

    I have no idea what the problem is between my .js and .php

    Here’s the .js and .php

  36. Chito says:

    Referring to previous msg, the photo can’t be uploaded, after I have chosen the photo,

    But then, I tried to upload a photo through ui_img_uploader.php directly, and it works!!!
    (you can try here

  37. Dennis says:

    Just use Firebug w/ Firefox to see what is going on. Compare to the example here. I’m sure you’ll find a difference that is causing the error.

  38. Castell says:

    Hi there, i´ve used to get this script working on yui 2.8.2r1
    but it stops at

    imgPanel.on ( ‘contentReady’, function() {..

    Does anyone have an idea of what´s wrong with that line?

    Any help is appreciated,

  39. Dennis says:

    I’ll have to see if there are any editor differences that need a patch with the latest YUI version.

  40. Brendan says:

    Hi Dennis,

    Not sure what i am doing wrong here. The upload script works, the image gets uploaded, but I don’t see the image in the editor.

    here is where the editor is:

    Here is my PHP code:

  41. Brendan says:

    woops.. my code did not get in the post. You can view it here:

  42. Nithin says:

    This is a great example. Pls tell me how to pass image’s alt and title values, if user hasn’t entered it

  43. sonu sindhu says:

    Sir tell me how to use this in my websites.

  44. madhan says:

    i am confused about ‘example_editor’ and i couldnt understand this line “”

  45. madhan says:

    i couldnt understand this line

  46. madhan says:


  47. beingaquatic says:

    to all those people looking to resize the image after uploading if it’s too big, following code may help:

    $scale_constraint = $size[0]/530;
    $new_width = 530;
    $new_height = $temp_height/$scale_constraint;
    $new_width = $temp_width;
    $new_height = $temp_height;

    $thumb_src = “_content/content_temp.jpg”;
    ini_set(‘memory_limit’, ‘128M’);
    $thumb_img_r = imagecreatefromjpeg($thumb_src);
    $thumb_dst_r = ImageCreateTrueColor( $new_width, $new_height);
    imagecopyresampled($thumb_dst_r, $thumb_img_r, 0, 0, 0, 0, $new_width, $new_height, $temp_width, $temp_height);
    $new_filename = “HL_Content_”.date(“YmdHis”).”.jpg”;
    $path = “_content/”.$new_filename;

    imagejpeg($thumb_dst_r, $path, 100);

    echo “{status:’UPLOADED’, image_url:’$path’}”;
    } else {
    echo “{status:’No file was submitted’}”;

    and the file names will be based on timestamp so pretty unique.

  48. beingaquatic says:

    if (isset($_FILES[‘image’][‘tmp_name’])) {
    // open the file
    $img = $_FILES[‘image’][‘tmp_name’];
    $himage = fopen ( $img, “r”); // read the temporary file into a buffer
    $image = fread ( $himage, filesize($img) );
    //if image can’t be opened, either its not a valid format or even an image:
    if ($image === FALSE) {
    echo “{status:’Error Reading Uploaded File.’}”;
    // create a new random numeric name to avoid rewriting other images already on the server…
    // define the uploading dir
    $path = “../../_content/content_temp.jpg”;

    $size = getimagesize(“../../_content/content_temp.jpg”);
    $temp_width = $size[0];
    $temp_height = $size[1];

    sorry that part of the code was truncated for some reason

  49. Greg says:

    Hello! My php application uses Codeigniter and I handle all uploads in a controller method


    How is it possible access that in the js?

  50. Greg says:

    I’m unable to upload images. I’m using firebug and for some reason I get the following error after selecting an image

    this._formNode.submit is not a function


    connection-min.js (line 8)

    I tried renaming my submit button but I don’t think that’s the issue. Please help I don’t know why this occurs.

Comments are closed.