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="http://yui.yahooapis.com/2.4.0/build/assets/skins/sam/skin.css">
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.0/build/element/element-beta-min.js"></script>
<script src="http://yui.yahooapis.com/2.4.0/build/container/container_core-min.js"></script>
<script src="http://yui.yahooapis.com/2.4.0/build/menu/menu-min.js"></script>
<script src="http://yui.yahooapis.com/2.4.0/build/button/button-min.js"></script>
<script src="http://yui.yahooapis.com/2.4.0/build/editor/editor-beta-min.js"></script>
<script src="http://yui.yahooapis.com/2.4.0/build/connection/connection-min.js"></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');
myEditor.render();
</script>

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.

<?php
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) );
 fclose($himage);
 //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.'}";
  return;
 }
 // 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
 $hout=fopen($path,"w");
 fwrite($hout,$image);
 fclose($hout);
 //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. RelaX says:

    ..it worked! Thanks alot!! 🙂

  2. Dennis says:

    No problem! For real purposes, you’ll have to add some additional code to manage where the image is stored. Also, there isn’t any image validation in what I uploaded. I’ll leave this as an exercise for those who know PHP better than myself.

  3. I tried it everything is good but when I click “upload Image” it is not doing anything.

  4. Dennis says:

    Are you referring to my example here or to your own implementation? I just double checked here and it worked fine. I’ve tested this with FireFox and Internet Explorer. Are you using a different browser?

  5. Alli says:

    Yo, cool yui add on, I’ve made a different php script though:
    (posted below, although not sure if your validation will remove the code.) Oh also it doesnt seem to work in Safari.

    0){

    $m = “”;

    $e = $_FILES[$form_handle][“error”];

    if($e == 1 || $e == 2) $m = “The image uploaded exceeds the maximum allowed file size.”;
    if($e == 3) $m = “The image was only partially uploaded.”;
    if($e == 4) $m = “Please select an image to upload.”;
    if($e == 5 || $e == 6 || $e == 7 || $e == 8) $m = “There is a technical error, please contact support.”;

    print “{status: ‘”.$m.”‘}”;
    return;

    }

    //if file has been sent successfully:
    if (isset($_FILES[$form_handle][‘tmp_name’])) {

    $image_file = $_FILES[$form_handle][‘tmp_name’];

    // get file type

    $ext = substr($_FILES[$form_handle][‘name’], strrpos($_FILES[$form_handle][‘name’], ‘.’));

    $new_name = $_FILES[$form_handle][‘name’].”_”.substr(time(), 2, 10).”.”.$ext;

    if(is_file($image_file)){

    if(move_uploaded_file($image_file, $relative.$path.$new_name)){

    echo “{status:’UPLOADED’, image_url:'”.$path.$new_name.”‘}”;

    }else{

    echo “{status: ‘Could not move file to correct directory’}”;

    }

    }

    }

    ?>

  6. I am using the same code as in your example and pointing to yahoo api’s along with http://allmybrain.com/wp-content/uploads/2007/10/yui-image-uploader.js, Do I need Python/any pre-requisits on IIS to make it work. I am not using PHP.

  7. Dennis says:

    Adeel: You do need some form of server processing. It doesn’t have to be Python, PHP, or any particular language at all. You just have to handle the file post, save the image, and return to the client the URL of the uploaded image.

    This PHP example is only one way to do it. The script that Alli uploaded is probably better than mine since I’m not really a PHP expert.

  8. Dennis,

    As soon as I click Upload Image it does not do any thing as it is happening in your example above.

    Can you provide me an ASP or ASPX page code instead of PHP. I will greatly appreciate.

  9. Dennis says:

    @Adeel, you can go back to the original post on this subject for how to write a server side handler. I don’t personally have the knowledge right now to implement a handler in ASP. I’m sure you’d be able to easily find scripts that will handle a file upload however. From there, all you have to do is modify the response to conform to the specification.

  10. Hello says:

    For those of you having problems, your probably like me, working in a hosted environment. In which case, your directory that you want to save in is located not at the ‘root’ of the drive, but somewhere deep down… to get there use getcwd(), which will return the directory structure all the way to your php script. You can then do something like the following:

    $save_location = getcwd().$_FILE[‘image’][‘name’];
    move_uploaded_file($_FILE[‘image’][‘tmp_name’], $save_location)

    This will, of course over write the old file, but thats a start from not working at all!!

  11. Johnnyhowey says:

    What is the variable name that the form post? I am not sure how to get the path so my coldfusion can upload the file

    Thanks

  12. Dennis says:

    You can name it whatever you want. In the example on this page, it was ‘image’. The name of the parameter is the 3rd parameter of the yuiImageUploader function.

  13. John says:

    cool tricks !! its work… thank you very much.. the best extension ever.. i wonder why the yui team didnt think of it

  14. yasser says:

    yes
    very profissional work
    i’m doing an editor too
    put
    i intend to make it simlpler

    thanks

  15. Christian says:

    Dennis,

    It appears that the js file you have provided does not work with the simple editor. Can you confirm?

    Thank you,

    Christian

  16. Dennis says:

    You’re probably correct. I wrote this before the editor was divided into the simple/full versions. I don’t think the simple editor contains the image tools.

  17. Christian says:

    Gotcha. I will try getting this one to work instead, then.

    Thank you for the quick response. It is appreciated.

  18. Christian says:

    Dennis,

    Is this the latest client code then?

    http://allmybrain.com/wp-content/uploads/2007/10/yui-image-uploader.js

    Thank you,

    Christian

  19. Dennis says:

    That is correct.

  20. Christian says:

    Dennis,

    This truly saves my skin. Once again, it is truly appreciated.

    Christian

  21. Tinus says:

    Hi Dennis,
    First of all compliments for the magnificent tool! On your example-website it workes great, I haven’t tested it on my personal website(s), though. First I have some questions.
    I’m not familiar with YUI, so the questions may seem ignorant.

    I guess the script is easy to integrate in an existing (php) website, apart from YUI?
    And the most important question: is there a possibility to save the result of the text (and image) editor to e.g. a webpage or an image? Thanks in advance!

  22. Dennis says:

    Thanks.

    1, you can use any server side language you want. You’ll need the YUI dependencies on the client side but you don’t have to include the on the entire site, only the page with the editor.

    2. On the server side, you can use the result of the text editor any way you like.

  23. Tinus says:

    Thanx! Ive been trying to implement the script. When trying to upload an image i keep getting t-string errors on line 6 in the php-code. Do you want to check the code as displayed above with the one you have working on your server with the example on top? Thanx a lot!

  24. Dennis says:

    I just double checked it. I think the only differences I have are a couple error_log statements that I used for debugging. I’m afraid you’ll have to check your php configuration. Perhaps add a few of those debugging statements to your side too.

  25. Niall says:

    This is really cool, thanks for sharing it!
    Here’s an example of the upload script for asp.net (just the code behind file):

    Option Explicit On
    Option Strict On

    Imports System.IO

    Partial Class yahooUI_upload
    Inherits System.Web.UI.Page

    ‘when porting this, you’ll have to change the vars with paths in them

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim jsonStatus As String

    Try
    Dim path As String = Server.MapPath(“.”) & “\uploads\”
    Dim imgUrl As String = “http://path-to-your-site/uploads/”
    Dim imgName As String

    For x As Integer = 0 To Request.Files.Count – 1
    imgName = Guid.NewGuid.ToString & “.jpg”
    Request.Files.Item(x).SaveAs(path & imgName)
    Next

    jsonStatus = “{status:’UPLOADED’, image_url:'” & imgUrl & imgName & “‘}”

    Catch ex As Exception
    jsonStatus = “{status:’Error Reading Uploaded File.’}”
    End Try

    Response.Clear()
    Response.ContentType = “text/html”
    Response.Write(jsonStatus)
    Response.End()

    End Sub

    End Class

  26. Nathan says:

    I have tried to implement the image upload portion of this script and when I click the Upload Image link it does nothing. It doesn’t even try to process the upload.php script to move the file to the script. And ideas?

    Thanx

  27. abhishek198 says:

    Hi Dennis,
    I was trying to use the RTE ..
    but when i click on the upload image button… nothing actually happens ..as far as i see it .. the link points to the same page .. instead of some other page to upload the image ..

    this is what i have edited :
    yuiImgUploader(myEditor, ‘/img_uploader.php’,’image’);

    Thanks

  28. abhishek198 says:

    Hi Dennis,
    Few issues .. i was wondering if you could help me out ..
    After i click on upload image .. it does get uploaded to my server but it is not displayed in the textarea … and secondly the text which the user ll be submitting along with the image .. ll be stored in a database .. what happens to the image info (path and other related info) .. how is it stored ..

  29. Dennis says:

    I could certainly take a quick look at something, just post the URL of the example not working.

  30. abhishek198 says:

    Hi Dennis,
    Kindly find the URL below:
    http://pangaaday.com/RTE/test1.php

    Thanks

  31. Dennis says:

    My initial guess is that you don’t have html and head tags in your editor page, only the basic html. Because your script isn’t in a head tag, it isn’t actually executed by my browser (FireFox). After you get the script executing, then you can debug your uploader php file to make sure that is working as expected.

    -Dennis

  32. Slappy THM says:

    In your PHP script, the trailing curly bracket on line 26:

    24. fwrite($hout,$image);
    25. fclose($hout);
    26. }

    should not be there.

  33. Dennis says:

    Fixed. Thanks. The actual script I’m using had that commented out.

  34. Hans says:

    so, is it mean that we read RTE from yahoo server? thanks

  35. Dennis says:

    Not sure exactly what you mean Hans.. You can of course, use the Yahoo RTE directly from the Yahoo servers.

  36. rajishankar says:

    I wanted to store all the matter I typed in text box as htm page. How to get it?

  37. Dennis says:

    The editor itself has a getEditorHTML method. You can also configure the editor to post it’s content along with the parent form if you just want to submit the content like any other textbox to your server for processing.

  38. quatromil says:

    Hi,
    I have a problem with the editor and i dont know what it is 🙁

    i have this code in my app:

    Editor = new YAHOO.widget.Editor(‘body’, {
    height: ‘400px’,
    width: ‘548px’,
    dompath: true,
    animate: true
    });

    Editor.render();

    yuiImgUploader(Editor, ‘include/yui_img_uploader.php’,’image’);

    In the yui_img_uploader.php file i have this paths:

    // define the uploading dir
    $path = “C:/”;

    //you’ll need to modify the path here to reflect your own server.
    $path = “C:/www/project_name/include” . $path;

    then when i select the image from the editor and i clic in “upload image”, the image is saved in “C:/” and also an alert which says “UPLOADED” is shown, but the image is not added to the text editor.

    I want the image to be added to the text editor, but i’m still dont know how to do that 🙁

  39. Dennis says:

    Sounds like you have a problem with the image page returned by your upload script.

    Check 2 things:
    1) You are returning the correct path back to the editor with your upload script.
    2) That the image is viewable with a web browser at that path. Example: http://myserver/uploads/myimage.jpg

  40. quatromil says:

    i changed the paths like this:

    // define the uploading dir
    $path = “C:/www/project_name/include”;

    //you’ll need to modify the path here to reflect your own server.
    $path = “C:/www/project_name/include” . $path;

    and the image is viewable from my www folder
    http://www/project_name/image.jpg

    but i have the same problem, i dont understand why

  41. Dennis says:

    It looks to me like you’re trying to do this on your local machine. It’s really set up to work with a web server. Not that you can’t do it on your local machine. The path returned to the script just needs to tell the editor the correct URL to display the image at. The problem may be that the editor things you’re using a relative path instead of an absolute one for the file or something.

    Have you tried debugging in FireFox with FireBug?

  42. quatromil says:

    Hi Denis.

    I realized what is the problem (because i could add an image to the text area, but writing the path with the Image file name), it’s the path,
    i have in my server this folders for the images:
    “project/images/uploads/” (http://project/images/uploads)

    I dont know what path do I must to put in:

    // define the uploading dir
    $path = “Image”;

    //you’ll need to modify the path here to reflect your own server.
    $path = “http://localhost/project/images/” . $path;

    (The path for this code is: http://localhost/project/images/Image.jpg)

    Because the Editor saves an image and later takes that new image to the textarea, and i am confuced about what paths should i put there.

    Can you help me? 🙂

  43. quatromil says:

    sorry, this is my server folders for images and not the last one:
    “www/project/images/uploads/” (http://localhost/project/images/uploads).

    just in case 😉

  44. Dennis says:

    Just return whatever path that the image can be viewed at. The editor doesn’t display images any different than your browser does when you put the correct path in your browser’s address bar. User A debugger to see what path is returned and compare against what it should be.

  45. quatromil says:

    It worked Dennis

    Thanks 😉

  46. Nany says:

    hi,Dennis…

    why i use php post this table,
    output is
    ???

    how delete ‘ \ ‘ ??

    i hope you understand what i said…. thanks

  47. Dennis says:

    You’ll have to post an example of your code or a URL so we can see what the problem is.

  48. Robyn says:

    Hello. I’m getting the same problem that abhishek198 had … the image uploads to my server, and I’ve got the correct path to the image in my $path variable at the end, but the Image URL field does not get updated with the path, nor does the placeholder image get replaced with the uploaded image.

    You can see it at http://dev.gsisd.esc7.net/test.asp . I’ve included a JS alert after the echo “{status: … }” line to show the contents of the $path variable that is being written into that line.

    Any ideas?

Comments are closed.