Lea
Lea

Reputation: 934

Ajax image upload form returns forbidden 403 Error

HI all,

I am currently tinkering with this pre-authored ajax/php image uploading script, but after almost 2 days of trying to figure out why it throws 403 forbidden error(You don't have permission to access /ajaxupload.php on this server), I am out of options but to ask the gurus here.

I suspect it has something to do with my hosts server settings, but before I hassle them(takes a day usually for them to get back with answers), I thought I might double check with you guys, in case I am missing something because I am new to using ajax, and i suspect that this is where the script is faulting.

Thanks to anyone who can suggest what I am doing wrong.

Cheers, Lea.

HTML: upload form:

<form action="http://www.mysite.com/ajaxupload.php" method="post" name="sleeker" id="sleeker" enctype="multipart/form-data">
    <input type="hidden" name="maxSize" value="9999999999" />
    <input type="hidden" name="maxW" value="200" />
    <input type="hidden" name="fullPath" value="http://mysite.com/uploads/" />
    <input type="hidden" name="relPath" value="../uploads/" />
    <input type="hidden" name="colorR" value="255" />
    <input type="hidden" name="colorG" value="255" />
    <input type="hidden" name="colorB" value="255" />
    <input type="hidden" name="maxH" value="300" />
    <input type="hidden" name="filename" value="filename" />
    <p><input type="file" name="filename" onchange="ajaxUpload(this.form,'http://mysite.com/uploader.php?filename=name&amp;maxSize=9999999999&amp;maxW=200&amp;fullPath=http://mysite.com/uploads/&amp;relPath=../uploads/&amp;colorR=255&amp;colorG=255&amp;colorB=255&amp;maxH=300','upload_area','File Uploading Please Wait...&lt;br /&gt;&lt;img src=\'../images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' /&gt;','&lt;img src=\'../images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /&gt; Error in Upload, check settings and path info in source code.'); return false;" /></p>
</form>

JS: ajaxupload.js

function $m(theVar){
    return document.getElementById(theVar)
}
function remove(theVar){
    var theParent = theVar.parentNode;
    theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
    if(obj.addEventListener)
        obj.addEventListener(evType, fn, true)
    if(obj.attachEvent)
        obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
    if(obj.detachEvent){
        obj.detachEvent('on'+type, fn);
    }else{
        obj.removeEventListener(type, fn, false);
    }
}
function isWebKit(){
    return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
function ajaxUpload(form,url_action,id_element,html_show_loading,html_error_http){
    var detectWebKit = isWebKit();
    form = typeof(form)=="string"?$m(form):form;
    var erro="";
    if(form==null || typeof(form)=="undefined"){
        erro += "The form of 1st parameter does not exists.\n";
    }else if(form.nodeName.toLowerCase()!="form"){
        erro += "The form of 1st parameter its not a form.\n";
    }
    if($m(id_element)==null){
        erro += "The element of 3rd parameter does not exists.\n";
    }
    if(erro.length>0){
        alert("Error in call ajaxUpload:\n" + erro);
        return;
    }
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id","ajax-temp");
    iframe.setAttribute("name","ajax-temp");
    iframe.setAttribute("width","0");
    iframe.setAttribute("height","0");
    iframe.setAttribute("border","0");
    iframe.setAttribute("style","width: 0; height: 0; border: none;");
    form.parentNode.appendChild(iframe);
    window.frames['ajax-temp'].name="ajax-temp";
    var doUpload = function(){
        removeEvent($m('ajax-temp'),"load", doUpload);
        var cross = "javascript: ";
        cross += "window.parent.$m('"+id_element+"').innerHTML = document.body.innerHTML; void(0);";
        $m(id_element).innerHTML = html_error_http;
        $m('ajax-temp').src = cross;
        if(detectWebKit){
            remove($m('ajax-temp'));
        }else{
            setTimeout(function(){ remove($m('ajax-temp'))}, 250);
        }
    }
    addEvent($m('ajax-temp'),"load", doUpload);
    form.setAttribute("target","ajax-temp");
    form.setAttribute("action",url_action);
    form.setAttribute("method","post");
    form.setAttribute("enctype","multipart/form-data");
    form.setAttribute("encoding","multipart/form-data");
    if(html_show_loading.length > 0){
        $m(id_element).innerHTML = html_show_loading;
    }
    form.submit();
}

PHP: ajaxupload.php

<?php
    function uploadImage($fileName, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH = null){
        $folder = $relPath;
        $maxlimit = $maxSize;
        $allowed_ext = "jpg,jpeg,gif,png,bmp";
        $match = "";
        $filesize = $_FILES[$fileName]['size'];
        if($filesize > 0){  
            $filename = strtolower($_FILES[$fileName]['name']);
            $filename = preg_replace('/\s/', '_', $filename);
            if($filesize < 1){ 
                $errorList[] = "File size is empty.";
            }
            if($filesize > $maxlimit){ 
                $errorList[] = "File size is too big.";
            }
            if(count($errorList)<1){
                $file_ext = preg_split("/\./",$filename);
                $allowed_ext = preg_split("/\,/",$allowed_ext);
                foreach($allowed_ext as $ext){
                    if($ext==end($file_ext)){
                        $match = "1"; // File is allowed
                        $NUM = time();
                        $front_name = substr($file_ext[0], 0, 15);
                        $newfilename = $front_name."_".$NUM.".".end($file_ext);
                        $filetype = end($file_ext);
                        $save = $folder.$newfilename;
                        if(!file_exists($save)){
                            list($width_orig, $height_orig) = getimagesize($_FILES[$fileName]['tmp_name']);
                            if($maxH == null){
                                if($width_orig < $maxW){
                                    $fwidth = $width_orig;
                                }else{
                                    $fwidth = $maxW;
                                }
                                $ratio_orig = $width_orig/$height_orig;
                                $fheight = $fwidth/$ratio_orig;

                                $blank_height = $fheight;
                                $top_offset = 0;

                            }else{
                                if($width_orig <= $maxW && $height_orig <= $maxH){
                                    $fheight = $height_orig;
                                    $fwidth = $width_orig;
                                }else{
                                    if($width_orig > $maxW){
                                        $ratio = ($width_orig / $maxW);
                                        $fwidth = $maxW;
                                        $fheight = ($height_orig / $ratio);
                                        if($fheight > $maxH){
                                            $ratio = ($fheight / $maxH);
                                            $fheight = $maxH;
                                            $fwidth = ($fwidth / $ratio);
                                        }
                                    }
                                    if($height_orig > $maxH){
                                        $ratio = ($height_orig / $maxH);
                                        $fheight = $maxH;
                                        $fwidth = ($width_orig / $ratio);
                                        if($fwidth > $maxW){
                                            $ratio = ($fwidth / $maxW);
                                            $fwidth = $maxW;
                                            $fheight = ($fheight / $ratio);
                                        }
                                    }
                                }
                                if($fheight == 0 || $fwidth == 0 || $height_orig == 0 || $width_orig == 0){
                                    die("FATAL ERROR REPORT ERROR CODE [add-pic-line-67-orig] to <a href='http://www.atwebresults.com'>AT WEB RESULTS</a>");
                                }
                                if($fheight < 45){
                                    $blank_height = 45;
                                    $top_offset = round(($blank_height - $fheight)/2);
                                }else{
                                    $blank_height = $fheight;
                                }
                            }
                            $image_p = imagecreatetruecolor($fwidth, $blank_height);
                            $white = imagecolorallocate($image_p, $colorR, $colorG, $colorB);
                            imagefill($image_p, 0, 0, $white);
                            switch($filetype){
                                case "gif":
                                    $image = @imagecreatefromgif($_FILES[$fileName]['tmp_name']);
                                break;
                                case "jpg":
                                    $image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
                                break;
                                case "jpeg":
                                    $image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
                                break;
                                case "png":
                                    $image = @imagecreatefrompng($_FILES[$fileName]['tmp_name']);
                                break;
                            }
                            @imagecopyresampled($image_p, $image, 0, $top_offset, 0, 0, $fwidth, $fheight, $width_orig, $height_orig);
                            switch($filetype){
                                case "gif":
                                    if(!@imagegif($image_p, $save)){
                                        $errorList[]= "PERMISSION DENIED [GIF]";
                                    }
                                break;
                                case "jpg":
                                    if(!@imagejpeg($image_p, $save, 100)){
                                        $errorList[]= "PERMISSION DENIED [JPG]";
                                    }
                                break;
                                case "jpeg":
                                    if(!@imagejpeg($image_p, $save, 100)){
                                        $errorList[]= "PERMISSION DENIED [JPEG]";
                                    }
                                break;
                                case "png":
                                    if(!@imagepng($image_p, $save, 0)){
                                        $errorList[]= "PERMISSION DENIED [PNG]";
                                    }
                                break;
                            }
                            @imagedestroy($filename);
                        }else{
                            $errorList[]= "CANNOT MAKE IMAGE IT ALREADY EXISTS";
                        }   
                    }
                }       
            }
        }else{
            $errorList[]= "NO FILE SELECTED";
        }
        if(!$match){
            $errorList[]= "File type isn't allowed: $filename";
        }
        if(sizeof($errorList) == 0){
            return $fullPath.$newfilename;
        }else{
            $eMessage = array();
            for ($x=0; $x<sizeof($errorList); $x++){
                $eMessage[] = $errorList[$x];
            }
            return $eMessage;
        }
    }

    $filename = strip_tags($_REQUEST['filename']);
    $maxSize = strip_tags($_REQUEST['maxSize']);
    $maxW = strip_tags($_REQUEST['maxW']);
    $fullPath = strip_tags($_REQUEST['fullPath']);
    $relPath = strip_tags($_REQUEST['relPath']);
    $colorR = strip_tags($_REQUEST['colorR']);
    $colorG = strip_tags($_REQUEST['colorG']);
    $colorB = strip_tags($_REQUEST['colorB']);
    $maxH = strip_tags($_REQUEST['maxH']);
    $filesize_image = $_FILES[$filename]['size'];
    if($filesize_image > 0){
        $upload_image = uploadImage($filename, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH);
        if(is_array($upload_image)){
            foreach($upload_image as $key => $value) {
                if($value == "-ERROR-") {
                    unset($upload_image[$key]);
                }
            }
            $document = array_values($upload_image);
            for ($x=0; $x<sizeof($document); $x++){
                $errorList[] = $document[$x];
            }
            $imgUploaded = false;
        }else{
            $imgUploaded = true;
        }
    }else{
        $imgUploaded = false;
        $errorList[] = "File Size Empty";
    }
?>
<?php
    if($imgUploaded){
        echo '<img src="../images/success.gif" width="16" height="16" border="0" style="marin-bottom: -4px;" /> Success!<br /><img src="'.$upload_image.'" border="0" />';
    }else{
        echo '<img src="../images/error.gif" width="16" height="16px" border="0" style="marin-bottom: -3px;" /> Error(s) Found: ';
        foreach($errorList as $value){
                echo $value.', ';
        }
    }
?>

Upvotes: 3

Views: 14692

Answers (6)

Hamidreza Shafiei
Hamidreza Shafiei

Reputation: 1

This error sometimes relate to mod_security configuration on your server. You can ask your host manager to disable it. If it works, Be sure your configuration on mod_security be compatible for your codes.

Upvotes: 0

webdevdoug
webdevdoug

Reputation: 21

<input type="hidden" name="fullPath" value="http://mysite.com/uploads/" />

The "http://" value in the POST is cause the server to restrict access. Just remove the "http://" from the value above and add it on the php side of things and you should be good to go.

Upvotes: 1

Corne
Corne

Reputation: 1

in the form action on onchange code, add http://localhost/ before you specify ajaxupload.php

Upvotes: 0

Will
Will

Reputation:

The problem is probably because you are using www.mysite.com and mysite.com... They are probably being considered two different domains and you are technically doing cross site scripting with your request. make sure you use the same base url for all your calls...

Upvotes: 0

Abu Aqil
Abu Aqil

Reputation: 804

403 forbidden error(You don't have permission to access /ajaxupload.php on this server)

from above error u need to check your document root folder for your domain/url. check the ownership and read write permissions. sometime your web server running as a normal user

eg: www-user

maybe you created files eg. ajaxupload.php as a root user (if it is in unix/linux environment). either the file or folder dost not allowed the access. check the ownership and permission of the ajaxupload.php file and the document root folder.

one way to test it out if u r in linux/unix env just do

chmod 755 -R /your/doc/root/folder

and try to trigger back your page.

ok make sure u have this configured for your doc root folder in your apache conf

<Directory "/your/doc/root/folder">
        Options +Indexes FollowSymLinks +ExecCGI
        AllowOverride AuthConfig FileInfo
                Order allow,deny
        Allow from all
</Directory>

if cannot access to httpd/apache conf ile you can always use .htaccess file.

create .htaccess file in /your/doc/root/folder/.htaccess

inside this file add as follows:

Options +Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all

more details info about your system will help a lots.

Upvotes: 0

wookiehangover
wookiehangover

Reputation: 430

make sure that the file permissions for your upload directory are set to 777 and in the correct group. In Linux this is easily done with

chmod -R 777 /path/to/uploads

and to check what their permissions are already, just call this

ls -al

in the directory above uploads.

Most 403 Forbidden's are caused by permissions issues. Hope this helps.

Upvotes: 1

Related Questions