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:
- Don’t forget to create the directory that the images will be stored in.
- 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.
..it worked! Thanks alot!! 🙂
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.
I tried it everything is good but when I click “upload Image” it is not doing anything.
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?
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’}”;
}
}
}
?>
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.
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.
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.
@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.
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!!
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
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.
cool tricks !! its work… thank you very much.. the best extension ever.. i wonder why the yui team didnt think of it
yes
very profissional work
i’m doing an editor too
put
i intend to make it simlpler
thanks
Dennis,
It appears that the js file you have provided does not work with the simple editor. Can you confirm?
Thank you,
Christian
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.
Gotcha. I will try getting this one to work instead, then.
Thank you for the quick response. It is appreciated.
There is an update post too for YUI 2.5.x:
http://allmybrain.com/2008/02/25/image-upload-with-yui-editor-250/
Dennis,
Is this the latest client code then?
http://allmybrain.com/wp-content/uploads/2007/10/yui-image-uploader.js
Thank you,
Christian
That is correct.
Dennis,
This truly saves my skin. Once again, it is truly appreciated.
Christian
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!
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.
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!
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.
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
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
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
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 ..
I could certainly take a quick look at something, just post the URL of the example not working.
Hi Dennis,
Kindly find the URL below:
http://pangaaday.com/RTE/test1.php
Thanks
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
In your PHP script, the trailing curly bracket on line 26:
24. fwrite($hout,$image);
25. fclose($hout);
26. }
should not be there.
Fixed. Thanks. The actual script I’m using had that commented out.
so, is it mean that we read RTE from yahoo server? thanks
Not sure exactly what you mean Hans.. You can of course, use the Yahoo RTE directly from the Yahoo servers.
I wanted to store all the matter I typed in text box as htm page. How to get it?
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.
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 🙁
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
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
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?
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? 🙂
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 😉
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.
It worked Dennis
Thanks 😉
hi,Dennis…
why i use php post this table,
output is
???
how delete ‘ \ ‘ ??
i hope you understand what i said…. thanks
You’ll have to post an example of your code or a URL so we can see what the problem is.
http://allmybrain.com/wp-content/uploads/2007/12/editor_images/1515923135.jpg
how can i delete ‘\’ ….
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?