1

I have custom module in magento1, I am getting Forbidden error like below.

Forbidden

You don't have permission to access /index.php/custom/adminhtml_custom/save/id/73/key/46af940903ec3251359c2b5db00e8092/back/edit/ on this server.

This problem is coming after clicking on Save or Save and Continue Edit button.

Here is the controller file which containes save function--

<?php
class Assel_Custom_Adminhtml_CustomController extends Mage_Adminhtml_Controller_Action
{

    protected function _initAction() {
        $this->loadLayout();
        return $this;
    }   

    public function indexAction() {
        $this->_initAction()
            ->_addContent($this->getLayout()->createBlock('custom/adminhtml_custom'))
            ->renderLayout();
    }

    public function editAction() {
        $id     = $this->getRequest()->getParam('id');
        $model  = Mage::getModel('custom/custom')->load($id);

        if ($model->getId() || $id == 0) {
            $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
            if (!empty($data)) {
                $model->setData($data);
            }

            Mage::register('custom_data', $model);

            $this->loadLayout();
            $this->_setActiveMenu('custom/items');

            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
            $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

            $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

            $this->_addContent($this->getLayout()->createBlock('custom/adminhtml_custom_edit'));

            $this->renderLayout();
        } else {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('custom')->__('Item does not exist'));
            $this->_redirect('adminhtml/cms_page/edit/',array('page_id' => $this->getRequest()->getParam('page_id')));
        }
    }

    public function newAction() {
        $this->_forward('edit');
    }

    public function saveAction() 
    {
        $filedata = array();
        $main_image = 'main_image';

        $_helper = Mage::helper('custom');
        if (!empty($_FILES[$main_image]['name'])) {
            try {
                $ext = $_helper->getFileExtension($_FILES[$main_image]['name']);
                $fname = 'File-' . time() . $ext;
                $uploader = new Varien_File_Uploader($main_image);
                #$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));

                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(false);

                $path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;

                $uploader->save($path, $_FILES[$main_image]['name']);

                $filedata[$main_image] = 'assel/custom/' . $_FILES[$main_image]['name'];
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        $backgrounddata = array();
        $background_image = 'background_image';
        if (!empty($_FILES[$background_image]['name'])) {
            try {
                $ext = $_helper->getFileExtension($_FILES[$background_image]['name']);
                $fname = 'File-' . time() . $ext;
                $uploader = new Varien_File_Uploader($background_image);
                #$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));

                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(false);

                $path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;

                $uploader->save($path, $_FILES[$background_image]['name']);

                $backgrounddata[$background_image] = 'assel/custom/' . $_FILES[$background_image]['name'];
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit',array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
                return;
            }
        }

        $thumbdata = array();
        $thumb_image = 'thumb_image';
        if (!empty($_FILES[$thumb_image]['name'])) {
            try {
                $ext = $_helper->getFileExtension($_FILES[$thumb_image]['name']);
                $fname = 'File-' . time() . $ext;
                $uploader = new Varien_File_Uploader($thumb_image);
                #$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));

                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(false);

                $path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;

                $uploader->save($path, $_FILES[$thumb_image]['name']);

                $thumbdata[$thumb_image] = 'assel/custom/' . $_FILES[$thumb_image]['name'];
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
                return;
            }
        }


        $circleimagedata = array();
        $circle_image = 'circle_image';
        if (!empty($_FILES[$circle_image]['name'])) {
            try {
                $ext = $_helper->getFileExtension($_FILES[$circle_image]['name']);
                $fname = 'File-' . time() . $ext;
                $uploader = new Varien_File_Uploader($circle_image);
                #$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));

                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(false);

                $path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;

                $uploader->save($path, $_FILES[$circle_image]['name']);

                $circleimagedata[$circle_image] = 'assel/custom/' . $_FILES[$circle_image]['name'];
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
                return;
            }
        }

        $audiodata = array();
        $audio_file = 'audio';
        if (!empty($_FILES[$audio_file]['name'])) {
            try {
                $ext = $_helper->getFileExtension($_FILES[$audio_file]['name']);
                $fname = 'File-' . time() . $ext;
                $uploader = new Varien_File_Uploader($audio_file);
                $uploader->setAllowedExtensions(array("wmv","mp3"));

                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(false);

                $path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;

                $uploader->save($path, $_FILES[$audio_file]['name']);

                $audiodata[$audio_file] = 'assel/custom/' . $_FILES[$audio_file]['name'];
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
                return;
            }
        }

        if ($data = $this->getRequest()->getPost()) {

            if (!empty($filedata[$main_image])) {
                $data[$main_image] = $filedata[$main_image];
            } else {
                if (isset($data[$main_image]['delete']) && $data[$main_image]['delete'] == 1) {
                    if ($data[$main_image]['value'] != '')
                        $this->removeFile($data[$main_image]['value']);
                    $data[$main_image] = '';
                }else {
                    unset($data[$main_image]);
                }
            }

            if (!empty($backgrounddata[$background_image])) {
                $data[$background_image] = $backgrounddata[$background_image];
            } else {
                if (isset($data[$background_image]['delete']) && $data[$background_image]['delete'] == 1) {
                    if ($data[$background_image]['value'] != '')
                        $this->removeFile($data[$background_image]['value']);
                    $data[$background_image] = '';
                }else {
                    unset($data[$background_image]);
                }
            }

            if (!empty($thumbdata[$thumb_image])) {
                $data[$thumb_image] = $thumbdata[$thumb_image];
            } else {
                if (isset($data[$thumb_image]['delete']) && $data[$thumb_image]['delete'] == 1) {
                    if ($data[$thumb_image]['value'] != '')
                        $this->removeFile($data[$thumb_image]['value']);
                    $data[$thumb_image] = '';
                }else {
                    unset($data[$thumb_image]);
                }
            }

            if (!empty($circleimagedata[$circle_image])) {
                $data[$circle_image] = $circleimagedata[$circle_image];
            } else {
                if (isset($data[$circle_image]['delete']) && $data[$circle_image]['delete'] == 1) {
                    if ($data[$circle_image]['value'] != '')
                        $this->removeFile($data[$circle_image]['value']);
                    $data[$circle_image] = '';
                }else {
                    unset($data[$circle_image]);
                }
            }

            if (!empty($audiodata[$audio_file])) {
                $data[$audio_file] = $audiodata[$audio_file];
            } else {
                if (isset($data[$audio_file]['delete']) && $data[$audio_file]['delete'] == 1) {
                    if ($data[$audio_file]['value'] != '')
                        $this->removeFile($data[$audio_file]['value']);
                    $data[$audio_file] = '';
                }else {
                    unset($data[$audio_file]);
                }
            }

            if($data['block_type'] == 16)
            {
                $page_id=$this->getRequest()->getParam('page_id');
                $url= Mage::helper('cms/page')->getPageUrl($page_id);
                $char = Mage::getModel('character/character') -> getCollection();
                $char->addFieldToFilter('name', $data['character']);
                foreach($char as $character)
                {
                    $id= $character->getData('id');
                }
                if($id)
                {
                    $char = Mage::getModel('character/character')->load($id);
                    $char->setLink($url)->save();
                }
            }

            foreach ($data as $key => $value)             /* save configurable product id in array in database*/
            {
                if (is_array($value))
                {
                    $data[$key] = implode(',',$this->getRequest()->getParam($key)); 
                }
            }   


            $model = Mage::getModel('custom/custom');       
            $model->setData($data)
                ->setId($this->getRequest()->getParam('id'));

            try 
            {
                $read = Mage::getSingleton('core/resource')->getConnection('core_read');
                $write = Mage::getSingleton('core/resource')->getConnection('core_write');
                //$data = $this->getRequest()->getPost();   
                $blockid=$this->getRequest()->getParam('id');
                if(!isset($blockid) || $blockid=='') // check if it is a new block
                {
                    if($data['sort']=='') //check if it contains 'sort' value
                    {
                        $resultArray1 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."'");
                        $totalRow=count($resultArray1);
                        $data['sort']=$resultArray1[$totalRow-1]['sort'];
                        $data['sort']=$data['sort']+1;
                        Mage::log('ashu11'.$data['sort']);
                    }
                    else
                    {
                        $resultArray2 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' and sort>='".$data['sort']."'");
                        if(count($resultArray2)>0)
                        {
                            foreach($resultArray2 as $result)
                            {
                                $write->query("update custom set sort ='".++$data['sort']."' where id='".$result['id']."'"); 
                            }
                        }
                    }
                }
                else
                {
                    if($data['sort']=='') //check if it contains 'sort' value
                    {
                        $resultArray3 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND id='".$blockid."'");
                        $totalRow=count($resultArray3);
                        $data['sort']=$resultArray3[0]['sort'];
                    }
                    else
                    {
                        $resultArray4 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND id='".$blockid."'");
                        $sort1=$resultArray4[0]['sort'];
                        $sort2=$data['sort'];
                        if($sort2>$sort1)//downwoards
                        {
                            $resultArray5 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND sort >'".$sort1."' AND sort<='".$sort2."'");
                            foreach($resultArray5 as $result)
                            {
                                $write->query("update custom set sort ='".--$result['sort']."' where id='".$result['id']."'"); 
                            }
                            $write->query("update custom set sort ='".$sort2."' where id='".$blockid."'"); 
                        }
                        else
                        {

                            $resultArray7 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND sort<'".$sort1."' AND sort>='".$sort2."'");
                            foreach($resultArray7 as $result)
                            {
                                Mage::log($result['id']);
                                $write->query("update custom set sort ='".++$result['sort']."' where id='".$result['id']."'"); 
                            }
                            $resultArray6 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND sort='".$sort2."'");
                            $write->query("update custom set sort ='".$sort1."' where id='".$blockid."'"); 
                        }
                    }

                }

                $model->setData($data)
                ->setId($this->getRequest()->getParam('id'));
                $model->save();

                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('custom')->__('Block was successfully saved'));
                Mage::getSingleton('adminhtml/session')->setFormData(false);

                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $model->getId()));
                    return;
                }
                $this->_redirect('adminhtml/cms_page/index/');
                return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('custom')->__('Unable to find block to save'));
        $this->_redirect('adminhtml/cms_page/index/');
    }

    public function deleteAction()
    {
        if( $this->getRequest()->getParam('id') > 0 && $this->getRequest()->getParam('page_id')) {
            try {


                $read = Mage::getSingleton('core/resource')->getConnection('core_read');
                $write = Mage::getSingleton('core/resource')->getConnection('core_write');
                $sortTobeDelete=$read->fetchOne("select sort from custom where id='".$this->getRequest()->getParam('id')."'");
                Mage::log($sortTobeDelete);

                $resultArray = $read->fetchAll("select * from custom where page_id ='".$this->getRequest()->getParam('page_id')."' and sort >'".$sortTobeDelete."'");
                Mage::log($resultArray);
                if(count($resultArray)>0)
                {
                    foreach($resultArray as $result)
                    {
                        $write->query("update custom set sort ='".--$result['sort']."' where id='".$result['id']."'"); 
                    }
                }


                $model = Mage::getModel('custom/custom');

                $model->setId($this->getRequest()->getParam('id'))
                    ->delete();

                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
                $this->_redirect('adminhtml/cms_page/index/');
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
            }
        }
        $this->_redirect('adminhtml/cms_page/index/');
    }

    public function sortRowAction() {
        $currentIndex=$this->getRequest()->getPost('curId');
        $changedIndex=$this->getRequest()->getPost('chaId');
        $rowId=$this->getRequest()->getPost('rId');
        $pageId=$this->getRequest()->getPost('pageId');


        $output['currentIndex'] = $currentIndex;
        $output['changedIndex'] = $changedIndex;
        $output['rowId'] = $rowId;
        $output['pageId'] = $pageId;
        $output['ashu'] = "sdfds";

        $read = Mage::getSingleton('core/resource')->getConnection('core_read');
        $write = Mage::getSingleton('core/resource')->getConnection('core_write');

        $sort1=$currentIndex;
        $sort2=$changedIndex;

        try
        {   
            if($sort2>$sort1)//downwoards
            {
                $resultArray5 = $read->fetchAll("select * from custom where page_id ='".$pageId."' AND sort >'".$sort1."' AND sort<='".$sort2."'");
                foreach($resultArray5 as $result)
                {
                    $write->query("update custom set sort ='".--$result['sort']."' where id='".$result['id']."'"); 
                }
                $write->query("update custom set sort ='".$sort2."' where id='".$rowId."'"); 
            }
            else
            {

                $resultArray7 = $read->fetchAll("select * from custom where page_id ='".$pageId."' AND sort<'".$sort1."' AND sort>='".$sort2."'");
                foreach($resultArray7 as $result)
                {
                    $write->query("update custom set sort ='".++$result['sort']."' where id='".$result['id']."'"); 
                }
                $write->query("update custom set sort ='".$sort2."' where id='".$rowId."'"); 
            }

        }catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                return;
          }

        $json = json_encode($output);
        $this->getResponse()
                             ->clearHeaders()
                             ->setHeader('Content-Type', 'application/json')
                             ->setBody($json);
    }

    public function removeFile($file) {
        $_helper = Mage::helper('custom');
        $file = $_helper->updateDirSepereator($file);
        $directory = Mage::getBaseDir('media') . DS . $file;
        $io = new Varien_Io_File();
        $result = $io->rmdir($directory, true);
    }

}

This code is running well on my localhost even on another server. but can't find out why it is not working on its actual server.

.htacess--

############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi

#    Action php5-cgi /cgi-bin/php5-cgi
#    AddHandler php5-cgi .php

############################################
## GoDaddy specific options

#   Options -MultiViews

## you might also need to add this line to php.ini
##     cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini

############################################
## this line is specific for 1and1 hosting

    #AddType x-mapp-php5 .php
    #AddHandler x-mapp-php5 .php

############################################
## default index file

    DirectoryIndex index.php

<IfModule mod_php5.c>

############################################
## adjust memory limit

#    php_value memory_limit 64M
    php_value memory_limit 256M
    php_value max_execution_time 18000

############################################
## disable magic quotes for php request vars

    php_flag magic_quotes_gpc off

############################################
## disable automatic session start
## before autoload was initialized

    php_flag session.auto_start off

############################################
## enable resulting html compression

    #php_flag zlib.output_compression on

###########################################
# disable user agent verification to not break multiple image upload

    php_flag suhosin.session.cryptua off

###########################################
# turn off compatibility with PHP4 when dealing with objects

    php_flag zend.ze1_compatibility_mode Off

</IfModule>

<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload

    SecFilterEngine Off
    SecFilterScanPOST Off
</IfModule>

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    ###SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    #BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    #BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    #BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    #SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    #Header append Vary User-Agent env=!dont-vary

</IfModule>

<IfModule mod_ssl.c>

############################################
## make HTTPS env vars available for CGI mode

    SSLOptions StdEnvVars

</IfModule>

<IfModule mod_rewrite.c>

############################################
## enable rewrites

    Options +FollowSymLinks
    RewriteEngine on

############################################
## you can put here your magento root folder
## path relative to web root

    #RewriteBase /magento/

############################################
## uncomment next line to enable light API calls processing
n
#    RewriteRule ^api/([a-z][0-9a-z_]+)/?$ api.php?type=$1 [QSA,L]

############################################
## rewrite API2 calls to api.php (by now it is REST only)

    RewriteRule ^api/rest api.php?type=rest [QSA,L]

############################################
## workaround for HTTP authorization
## in CGI environment

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

############################################
## TRACE and TRACK HTTP methods disabled to prevent XSS attacks

    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
    RewriteRule .* - [L,R=405]

############################################
## redirect for mobile user agents

    #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$
    #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
    #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]

############################################
## always send 404 on missing files in these folders

   RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

</IfModule>


############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead

    AddDefaultCharset Off
    #AddDefaultCharset UTF-8

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires

    ExpiresDefault "access plus 1 year"

</IfModule>

############################################
## By default allow all access

    Order allow,deny
    Allow from all

###########################################
## Deny access to release notes to prevent disclosure of the installed Magento version

    <Files RELEASE_NOTES.txt>
        order allow,deny
        deny from all
    </Files>

############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags

    #FileETag none

Can anyone help me pls to find out the issue.

1

Don't forget the protected function _isAllowed():

Here is an example, which default returns true, but I suggest you research the function and how it should be implemented.

protected function _isAllowed()
{
    return true;
}

ACL explanation by the amazing Alan Storm: https://alanstorm.com/magento_acl_authentication/

IMPORTANT NOTE: Just to be sure that have a new session incorporating any changes, you MUST LOG OUT of admin, clear cache -- just in case, and then log back in.


On another note, be sure that write access has been granted to directories where file writes will occur. Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;, could be a good example of where some double-checking user-group permissions should be done.

  • This question sat unanswered for over 2 years?? wtf? – df2k2 Apr 18 '18 at 18:02
0

Check if you have mod_security installed, it may be configured to filter out certain post requests. See if you can get it to ignore your request path, or you can always turn it off with SecRuleEngine Off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.