aveeva7 0 Newbie Poster

Magento 1.9 - How to include custom PHP Script into .PHTML file

My magento tracking page:

https://i.stack.imgur.com/3GIoN.png

Back-end magento code :

https://i.stack.imgur.com/ySgMA.png

How can i add my PHP script into this tracking page.

Tracking page code - trackorder.phtml [ https://i.stack.imgur.com/ySgMA.png ]

<?php
    if(Mage::getStoreConfig('trackorder/trackorder_general/enabled')):
    ?>
    <div class="page-title"><h1><?php echo $this->__('Track Your Order ') ?></h1></div>
    <div  class="form-list">
        <form name="track_order" id="track_order" action="" method="post" onsubmit="sendAjax('track_order','<?php  echo Mage::getUrl('*/*/track');?>'); return false;">
        <!--<form name="track_order" method="post" id="track_order" action="<?php echo Mage::getUrl('*/*/view');?>">-->
            <ul class="form-list">
                <li>
                    <label for="order_id" class="required"><em>*</em><?php echo $this->__('Order Id') ?></label>
                    <div class="input-box">
                        <input type="text" name="order_id" id="order_id" value="" title="" class="input-text required-entry" />
                    </div>    
                </li>
                <li>
                    <label for="email_address" class="required"><em>*</em><?php echo $this->__('Email Address') ?></label>
                    <div class="input-box" >
                        <input type="text" name="email" id="email_address" value="" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" />
                    </div>    
                </li>
            </ul>
            <div class="buttons-set">
               <button type="submit" class="button" title="<?php echo $this->__('Track Order') ?>" name="track" id="track">
                    <span><span><?php echo $this->__('Track Order') ?></span></span>
                </button>
            </div>

        </form>
        <div id="loading-details" class="loading-details" style="display:none">
            <div id="loading-mask" >
                <p class="loader" id="loading_mask_loader"><img src="<?php echo $this->getSkinUrl('trackorder/images/ajax-loader-tr.gif') ?>" alt="<?php echo Mage::helper('adminhtml')->__('Loading...') ?>"/><br/><?php echo $this->__('Please wait...') ?></p>
            </div>
        </div>
    </div> 

    <div id="oderinfo" class="order-info-message"></div>

    <script type="text/javascript">
        var validateForm = new VarienForm('track_order', true);
    </script>           
    <script type="text/javascript">

        function sendAjax(frmId,url){
            if (!validateForm.validator.validate()) {
                return;
            }
            var data = $(frmId).serialize(this);
            $("loading-details").show();

        new Ajax.Updater(
                {
                    success:"oderinfo"
                },

                url,
                {
                    asynchronous:true,
                    evalScripts:false,
                    onComplete:function(request, json){
                        $("loading-details").hide();
                        return false;
                    }, 
                    onLoading:function(request, json){},
                    parameters:data
                }
            ); 
            return false;
        }

    </script>
    <?php else: ?>
    <?php
        $url = Mage::getBaseUrl();
        Mage::app()->getFrontController()->getResponse()->setRedirect($url);
    ?>
    <?php endif; ?>

From above code how can i add my own PHP script :

My PHP script :

<!DOCTYPE HTML>
<html>

<body>

    <form action="#" method="POST">
        Select Courier :
        <select name="courier">
            <option disabled='disabled' selected>-- Choose an option --</option>
            <option value="professional_courier">Professional Courier</option>
            <option value="shree_maruti_courier">Shree Maruti Courier</option>
            <option value="india_post_courier">India Post Courier</option>
            <option value="dhl_courier">DHL Courier</option>
            <option value="fedex_courier">Fedex Courier</option>
            <option value="ups_courier">UPS Courier</option>
        </select>

        Trackingid: <input type="text" name="trackingid">
        <input type="submit">

    </form>

    <?php
    if (isset($_POST['courier'])) {
        // Professional Courier
        if ('professional_courier' === $_POST['courier']) {
            header("Location: https://www.tpcindia.com/Tracking2014.aspx?id=" . $_POST["trackingid"] . "&type=0&service=0");
        }
        // Shree Maruti Courier
        else if ('shree_maruti_courier' === $_POST['courier']) {
            header("Location: https://www.shreemaruticourier.com/track-your-shipment/#track-your", "_blank");
        }

        // india_post_courier
        else if ('india_post_courier' === $_POST['courier']) {
            header("Location: https://www.indiapost.gov.in/vas/Pages/IndiaPostHome.aspx/#main-content", "_blank");
        }

        // DHL Courier
        else if ('dhl_courier' === $_POST['courier']) {
            header("Location: https://www.dhl.com/en/express/tracking.html?AWB=" . $_POST["trackingid"] . "&brand=DHL", "_blank");
        }

        // Fedex Courier
        else if ('fedex_courier' === $_POST['courier']) {
            header("Location: https://www.fedex.com/apps/fedextrack/?action=track&trackingnumber=" . $_POST["trackingid"] . "&cntry_code=in&locale=en_IN", "_blank");
        }

        // ups_courier
        else if ('ups_courier' === $_POST['courier']) {
            header("Location: https://www.ups.com/track?loc=en_US&tracknum=" . $_POST["trackingid"] . "&requester=WT/trackdetails", "_blank");
        }
    }
    ?>
</body>

</html>

My Workout in trackorder.phtml getting error : [start & end header added]

<?php
    if(Mage::getStoreConfig('trackorder/trackorder_general/enabled')):
    ?>
    <div class="page-title"><h1><?php echo $this->__('Track Your Order ') ?></h1></div>
    <div  class="form-list" style="float: left;">
        <form name="track_order" id="track_order" action="" method="post" onsubmit="sendAjax('track_order','<?php  echo Mage::getUrl('*/*/track');?>'); return false;">
        <!--<form name="track_order" method="post" id="track_order" action="<?php echo Mage::getUrl('*/*/view');?>">-->
            <ul class="form-list">
                <li>
                    <label for="order_id" class="required"><em>*</em><?php echo $this->__('Order Id') ?></label>
                    <div class="input-box">
                        <input type="text" name="order_id" id="order_id" value="" title="" class="input-text required-entry" />
                    </div>    
                </li>
                <li>
                    <label for="email_address" class="required"><em>*</em><?php echo $this->__('Email Address') ?></label>
                    <div class="input-box" >
                        <input type="text" name="email" id="email_address" value="" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" />
                    </div>    
                </li>
            </ul>
            <div class="buttons-set">
               <button type="submit" class="button" title="<?php echo $this->__('Track Order') ?>" name="track" id="track">
                    <span><span><?php echo $this->__('Track Order') ?></span></span>
                </button>
            </div>

        </form>
        <div id="loading-details" class="loading-details" style="display:none">
            <div id="loading-mask" >
                <p class="loader" id="loading_mask_loader"><img src="<?php echo $this->getSkinUrl('trackorder/images/ajax-loader-tr.gif') ?>" alt="<?php echo Mage::helper('adminhtml')->__('Loading...') ?>"/><br/><?php echo $this->__('Please wait...') ?></p>
            </div>
        </div>
    </div> 

    <!-- Start couier tracking -->

      <div style="float: left;">
        <form action="#" method="POST" style="padding: 28px 15px 21px 196px;">
            Select Courier :
            <select name="courier">
            <option disabled='disabled' selected>-- Choose an option --</option>
            <option value="professional_courier">Professional Courier</option>
            <option value="shree_maruti_courier">Shree Maruti Courier</option>
            <option value="india_post_courier">India Post Courier</option>
            <option value="dhl_courier">DHL Courier</option>
            <option value="fedex_courier">Fedex Courier</option>
            <option value="ups_courier">UPS Courier</option>
        </select>

        Trackingid: <input type="text" name="trackingid">
        <input type="submit">

    </form>

    <?php
    if (isset($_POST['courier'])) {
        // Professional Courier
        if ('professional_courier' === $_POST['courier']) {
            header("Location: https://www.tpcindia.com/Tracking2014.aspx?id=" . $_POST["trackingid"] . "&type=0&service=0");
        }
        // Shree Maruti Courier
        else if ('shree_maruti_courier' === $_POST['courier']) {
            header("Location: https://www.shreemaruticourier.com/track-your-shipment/#track-your", "_blank");
        }

        // india_post_courier
        else if ('india_post_courier' === $_POST['courier']) {
            header("Location: https://www.indiapost.gov.in/vas/Pages/IndiaPostHome.aspx/#main-content", "_blank");
        }

        // DHL Courier
        else if ('dhl_courier' === $_POST['courier']) {
            header("Location: https://www.dhl.com/en/express/tracking.html?AWB=" . $_POST["trackingid"] . "&brand=DHL", "_blank");
        }

        // Fedex Courier
        else if ('fedex_courier' === $_POST['courier']) {
            header("Location: https://www.fedex.com/apps/fedextrack/?action=track&trackingnumber=" . $_POST["trackingid"] . "&cntry_code=in&locale=en_IN", "_blank");
        }

        // ups_courier
        else if ('ups_courier' === $_POST['courier']) {
            header("Location: https://www.ups.com/track?loc=en_US&tracknum=" . $_POST["trackingid"] . "&requester=WT/trackdetails", "_blank");
        }
    }
    ?>

    </div>

    <!-- End couier tracking -->

    <div id="oderinfo" class="order-info-message"></div>

    <script type="text/javascript">
        var validateForm = new VarienForm('track_order', true);
    </script>           
    <script type="text/javascript">

        function sendAjax(frmId,url){
            if (!validateForm.validator.validate()) {
                return;
            }
            var data = $(frmId).serialize(this);
            $("loading-details").show();

        new Ajax.Updater(
                {
                    success:"oderinfo"
                },

                url,
                {
                    asynchronous:true,
                    evalScripts:false,
                    onComplete:function(request, json){
                        $("loading-details").hide();
                        return false;
                    }, 
                    onLoading:function(request, json){},
                    parameters:data
                }
            ); 
            return false;
        }

    </script>
    <?php else: ?>
    <?php
        $url = Mage::getBaseUrl();
        Mage::app()->getFrontController()->getResponse()->setRedirect($url);
    ?>
    <?php endif; ?>

Dani AI

Generated

Short summary and best immediate fix: avoid calling header() from inside a .phtml template — that commonly fails because PHP has already sent page output by the time the template runs. For a quick, non-invasive solution, build the courier URL in the browser and open it in a new tab so Magento’s page and your AJAX track flow remain unchanged. See the PHP "headers already sent" notes and the window.open docs for details. (stackoverflow.com)

Example (client-side, minimal change):

/* attach to the courier form submit; keep mapping server-side or use short keys */
document.getElementById('courierForm').addEventListener('submit', function(e){
  e.preventDefault();
  var courier = this.courier.value;
  var id = this.trackingid.value;
  var map = { professional: 'https://courier.example/track?id=%s' };
  if (!map[courier]) return alert('Select valid courier');
  var url = map[courier].replace('%s', encodeURIComponent(id));
  window.open(url, '_blank');
});

Better, more robust approach (recommended): handle the submit in a controller action. Accept the courier key and trackingid, validate against a server-side allow-list, build the final tracking URL server-side, then redirect from the controller (do not do that redirect inside the template). Also include Magento’s form key in the POST so Magento’s CSRF checks are satisfied. See examples of programmatic redirects and the form-key usage in Magento resources. (magento.stackexchange.com)

Security and UX notes: never redirect to an arbitrary user-supplied URL — use a whitelist (map short courier keys to trusted URL templates) to avoid open-redirect/phishing risks; OWASP recommends allow-listing destinations or showing a leave-site confirmation. If you open a new tab, add the usual safety attributes (rel="noopener noreferrer") and avoid nesting forms in your markup. (cheatsheetseries.owasp.org)

Note for : make the courier UI a separate form (not nested inside the order form), and prefer the controller-or-JS options above rather than sprinkling header() calls into .phtml.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.