PHP - Include/require Vs Creating Your Own Custom Function
I need to include a pagination file in multiple pages or create a custom function but not sure which one to use.
For example: Code: [Select] <?php function test() { echo "Hello PHP Freaks!"; } ?> Or I can create a separate file that echos this statement and include it. When do you use include/require and when do you create your own custom function? Similar Tutorialstrying to use a require but not working properly Fatal error: require() [function.require]: Failed opening required 'get_extra.php?id=1' (include_path='.') first thing set on page is.. page is profile.php?id=1 $userid = $_GET['id']; code is:require "get_extra.php?id=$userid"; what can i do to fix this? thanks Hello. Include is identical to require, only require stops any further script execution. Just wondering if anyone could give me a good example, where 'require' should be used instead 'include'. Thanks. Why would I want to use include() vs. require() ?? (It seems like most people use "include()", but I would think "require()" would be better/safer...) TomTees is there a way to do an include or require to a whole directory? I have only done includes and requires with single files in the past, but have a situation where this could save me a lot of time. Php Folks, As you know, typing the same code over and over again on all files is daunting. I was wondering, if I can have an error_reporting.php file and then put:
include('error_reporting.php');
at the top of all my php files as header, where the error_reporting.php would have this content: <?php error_reporting(E_ALL); ini_set('error_reporting','E_ALL'); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); ?> Q1. Is that ok or not ?
Q2. Usually, I have a conn.php with content like this: <?php $conn = mysqli_connect("localhost","root","","db_database"); $db_server = 'localhost'; $db_user = 'root'; $db_password = ''; $db_database = 'test'; $conn->set_charset('utf8mb4');//Always use Charset. if (!$conn) { //Error Message to show user in technical/development mode to see errors. die("Database Error : " . mysqli_error($conn)); //Error Message to show User in Layman's mode to see errors. die("Database error."); exit(); } ?>
And then, on all my php files, I just reference to the conn.php by putting the following line on the header: include('conn.php');
Or:
require('conn.php');
And on each php file, just before dealing with mysql, I have a line like this: mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); $conn->set_charset("utf8mb4"); Now, I am wondering, why should I write the above 2 lines on all my php files that deal with mysql ? To keep things short, why don;t I just add those 2 lines in the error_reporting.php ? So, it looks like this:
error_reporting.php
<?php ini_set('error_reporting','E_ALL');//error_reporting(E_ALL); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); $conn->set_charset("utf8mb4"); ?>
I am very confused in between these three terms INCLUDE, REQUIRE, HEADER... Can anyone tell me the difference between these three terms... I just want to run a php file in the if condition.. Basically i do not want to open i just want to run ... for ex. Code: [Select] <?php if(condition) { // run mail.php file } ?> Hello, I have a small and annoying problem. Imagine that I have a main folder on my FTP server which has index.php and I then have a php folder for all of my small scripts and an includes folder for misc files. So, for instance http://www.somedomain.com/index.php http://www.somedomain.com/php/somescript.php http://www.somedomain.com/includes/somefile.html Inside somescript.php, I need to use one of the files from the includes folder, like this for example: require('../includes/somefile.html'); This is all fine, but the problem is when I include the PHP file on my index.php page. Then I am telling PHP to go one step back to find the includes folder, but the problem is that it only needs to go one step back if it PHP script is not included on some page outside of the php folder. If I run php/somescript.php, there is no problem, but if I include php/somescript.php on my index.php, then there is trouble! I hope you guys understand what I mean. Thanks in advance! PS - I would appreciate if the solution is not about moving php/somescript.php or using full URLs in my includes. I am using php require to input a page of code. I am including (require) that file several times within the page. I am guessing that it executes the file every time, and does not save any page loading time, and in fact probably slowing it down because it has to make the request every time.
Just wanted an expert to confirm or deny my educated guess. Would it be the same if it were including an html file instead of a php file?
<?php require ("$base_path/main_page_rotation/content4.php"); ?> Hello all, i just joined today, because am going nuts with php and the include or require statement/function I want to use them to link to a header. Nothing hard about that , I would say. But my bit of code below just does not work. I am running them in a test area on my server. Just to be safe The file L2.php is in the same directory/folder ( showing my age).
I should say that am have been programming a while but only using php for about 4 weeks and this normal simple bit of code has me stumped. I am building the site in visual studio and atom. any pointer would be received with joy
The content of L" is also below . Danler
<?php include_once('L2.php'); ?> centents of l2.php below <h3> line 2 <br><H2>Hello world AM TRYING 6</h2> </h3>
Hello, Is this a sound explanation of require and include.. Lets say i have "X" application with an index.php file. in a folder on my domain like so: www.xxx.com/Application X folder/index.php. // the index.php calls to multiple files with-in the "Application X folder" and database. What if i move the index.php to another location all together like so: http://www.xxx.com/notXsubfolder1/notXsubfolder2/notXsubfolder3/index.php //the X application index file.. and then edit the require and include links in the index.php file to paths like this (just example might not be accurate): require_once '../../../../application X Folder/include/required_file.php'; My question:?? What i want to know is: if the required_file.php has includes of its own, will it take the includes that it requires from its original folder where the Required_file.php is located? or will its paths change the the new index.php location?? . 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; ?>
hey, i have been trying all day to get something to work that will allow me to replicate the / part of an href Code: [Select] <a href="/images/blah.jpg"> to go from the root folder in php. i thought the easiest way to do this is to use php to get the domain address. require($_SERVER['SERVER_NAME']."/header.php"); i have gotten to this part but am still getting the error that the file doesnt exist probably because there is no http:// in front of it but i do not want to turn allow_url_includes on in the php.ini file. How can i acheive this? Thanks Is there a way to use PHP to edit html without having to store it in my DB? For example I would like someone to be able to edit a paragraph on the page, its wrapped in a <div class="editable"> now is there a way to have PHP detect that div and have an textarea to edit it directly without having to store anything in a DB? I hope that makes sense if it doesn't let me know! Thanks Hi All, I have a page where people can enter the name of food, like you would order in a restaurant (would appear on the menu). They can set if the food is gluten free, nut free, vegan etc. I am wanting to use buttons that can be clicked going red if they are not gluten free or not vegetarian and green if they are vegan or vegetarian. I have working code that does this but i dont feel like i am being efficient with how i am writing it as it is turning into a lot of repeated code. I would appreciate some help pointing me in the right direction. function popManageMenuModal($conn, $miid){ $stmt = $conn -> prepare(' SELECT menu_item_name, menu_item_is_vegan, menu_item_is_vegitarian, menu_item_is_gf, menu_item_is_nf, menu_item_is_df FROM ssm_menu_items WHERE menu_item_id = ? '); $stmt -> bind_param('i', $miid); $stmt -> execute(); $stmt -> bind_result($miname, $miisvegan, $miisveg, $miisgf, $miisnf, $miisdf); $stmt -> fetch(); if($miisvegan == '1'){ $vegansel = 'btn-success'; $vegan = 'Vegan'; $veganop = 'Is'; }else{ $vegansel = 'btn-danger'; $vegan = 'Vegan'; $veganop = 'Not'; } if($miisveg == '1'){ $vegsel = 'btn-success'; $vegi = 'Vegi'; $vegop = 'Is'; }else{ $vegsel = 'btn-danger'; $vegi = 'Vegi'; $vegop = 'Not'; } $output = ""; $output .= "<form><div class='form-group'><label>Menu Item Name</label><textarea class='form-control'>$miname</textarea></div>"; $output .= "<div class='form-inline'>"; $output .= "<div class='drButton btn $vegansel' data-value='$miisvegan'>{$veganop} {$vegan}</div>"; $output .= "<div class='drButton btn $vegsel' data-value='$miisveg'>{$vegop} {$vegi}</div>"; $output .= "<div>$miisvegan, $miisveg, $miisgf, $miisnf, $miisdf</div>"; $output .= "</form>"; return $output; } $(document).on('click','.drButton', function(){ var polarity = $(this).data("value") if(polarity == '0'){ $(this).addClass("btn-success") $(this).removeClass("btn-danger") $(this).data("value", '1') return } if (polarity == '1'){ $(this).addClass("btn-danger") $(this).removeClass("btn-success") $(this).data("value", '0') return } });
I'm gonna be perfectly honest, I have no idea what's wrong with this code, I'm not even entirely sure what it all means, I just need to make it work. -.- I get this error: Parse error: syntax error, unexpected '}' in Z:\www\cms\includes\functions.php on line 25 From this code: Code: [Select] <html> <body> <?php include('includes/dbvars.php'); function displayVideos($dbc){ mysqli_connect('DB_HOST', 'DB_USER', 'DB_PW', 'DB_NAME'); //Query $query = "SELECT * FROM videos"; //Execute $result = mysqli_query($dbc, $query) or die ("Error querying database."); While ($row = mysqli_fetch_assoc($result)) { echo '<h2>' . $row['Title'] . '</h2>'; echo '<b>Director</b>:' . $row['Director'] . '<br />'; echo '<b>Description</b>:<br />' . $row['Description']; echo '<hr>'; } mysqli_close($dbc) } ?> </body> </html> Any help very much appreciated Hi all. Here is my scripts which allow user to check multiple rows of data and delete it , but it require select data and click for twice to delete the rows , what should be the error? Code: [Select] <form name="frmSearch" method="post" action="insert-add.php"> <table width="600" border="1"> <tr> <th width="50"> <div align="center">#</div></th> <th width="91"> <div align="center">ID </div></th> <th width="198"> <div align="center">First Name </div></th> <th width="198"> <div align="center">Last Name </div></th> <th width="250"> <div align="center">Mobile Company </div></th> <th width="100"> <div align="center">Cell </div></th> <th width="100"> <div align="center">Workphone </div></th> <th width="100"> <div align="center">Group </div></th> </tr> </form> <? echo "<form name='form1' method='post' action=''>"; while($objResult = mysql_fetch_array($objQuery)) { echo "<tr>"; echo "<td align='center'><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"$objResult[addedrec_ID]\"></td>"; echo "<td>$objResult[addedrec_ID] </td>"; echo "<td>$objResult[FirstName]</td>"; echo "<td>$objResult[LastName] </td>"; echo "<td>$objResult[MobileCompany] </td>"; echo "<td>$objResult[Cell] </td>"; echo "<td>$objResult[WorkPhone] </td>"; echo "<td>$objResult[Custgroup] </td>"; echo "</tr>"; } echo "<td colspan='7' align='center'><input name=\"delete\" type=\"submit\" id=\"delete\" value=\"Delete\">"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) // from button name="delete" { $checkbox = ($_POST['checkbox']); //from name="checkbox[]" $countCheck = count($_POST['checkbox']); for($d=0;$d<$countCheck;$d++) { $del_id = $checkbox[$d]; $sql = "DELETE from UserAddedRecord where addedrec_ID = $del_id"; $result2=mysql_query($sql) or trigger_error(mysql_error());;; } if($result2) { $fgmembersite->GetSelfScript(); } else { echo "Error: ".mysql_error(); } } echo "</form>"; Thanks for every reply. I have three tables that I can link up via mysql and get the results I need, but I could also query just the one table and get the info from the other two via a function, my question is which is the faster and/or better way and why? Thanks Hey there, I guess, theres something wrong with this page, 'cause it isnt loading the page I'm trying to include, please take a look: <? require "/backend/functions.php"; $con = mysql_connect('localhost', 'mdown', 'e5r8htt9'); mysql_select_db("actual", $con); dbconn(true); ?> <html> <body BGCOLOR="#000000"> [...] </style> <div class="wrapper"> <div class="rec"> <img src=test/recs.png border=0> </div> <div class="hormenu"> <img src=test/hormenu.png border=0> </div> <div class="cpanel"> <img src=test/cpanel.png border=0> </div> <div class="menu"> <img src=test/menu.png border=0> </div> <div class="baresq"> <img src=test/baresq.png border=0> </div> <div class="table"> <? include 'home/newtable.php'; ?> </div> <div class="bardir"> <img src=http://mdown.org/tretas/teste.V4/bardir.png border=0> </div> </div> </body> </html> Now the page with this code isnt showing anything inside the TABLE div and I guess it should display the content of newtable.php. The newtable.php is working perfectly and the is just the data selected from a table. Any idea about where did I messed up? thanks |