PHP - Include Or Require Directory?
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.
Similar TutorialsHey all, I've been having an issue with require_once from another sub-directory. Origionally I had all my php files in the same spot but I wanted to make a library to clean things up a bit. Atm I am trying to access my /subFolder/frame_work/sql/dbconnect.rem.php with require once from /subFolder/frame_work/account_data/accountHandler.rem.php. I have looked around a little bit and i know requires\includes looks in relative directorys. So one obvious solution would be to include the entire path name. "var/www/subFolder/frame_work/sql/dbconnect.rem.php". My problem is I will be accessing this from multiple directories and on localhost the root directory is var opposed to my server which is public_html. I like to edit my stuff in localhost before going public with it and it is going to be a real pain if I have to keep switching var to public_html in every file before I upload. Is there any other solutions I could approach? Any responses would be much appreciated. Thank you for your time. 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 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 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 } ?> 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"); ?>
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>
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"); ?> 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? I was under the impression this was a simple thing to do and I'm fairly certain I've done it before, but it isn't working for some reason. Under the root directory of my project I have two subfolders called "inc" and "lib". lib contains third-party scripts for use in my project. The one in question is phpmailer (lib/class.phpmailer.php). Now, in inc I have a file that needs to include PHPMailer. Inside my script in inc I have this: require_once('../lib/class.phpmailer.php'); It errors out saying it can't find it. I thought that was supposed to go down one directory then back up into lib. The file does indeed exist. What am I doing wrong? This seems like a stupidly simple thing... 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?? . I am trying to include a inc.php file within a normal .php file from a single directory as I am using it in several directories but cannot get it to work and have tried many different techniques. Any ideas on the coding that would work would be appreciated? Alternatively, I would be happy to set the constants in a mysql db but am unsure how I would unpack/read it so as to get it in the php program as code i.e. mysql db field 1 field 2 name $name Program <?php $name; ?> I am trying to use the following code to include a directories contents and was wondering what im doing wrong, because its not working? Code: [Select] if ($handle = opendir('../configs')) { while (false !== ($FILEZ = readdir($handle))) { include "$FILEZ"; } closedir($handle); } Hi, I have a file structure for all my files on my website that works fine for the most part. The basic layout would be something similar to the following. - root folder - sub_folder1 - folder1 - folder2 -sub_folder2 - folder1 - folder2 Each of the folders would contain relative .php files carrying out specific functions etc. The issue I am having is as follows. If I am on a webpage that is located in either of the folder1/folder2 folders, and I need to redirect somebody to a file located in the root folder, I am not able to do this without the page not being displayed correctly. On the file located in the folder1 folder, I have a <? php include("page1.php");?> which works fine. Trying to access a file to redirect to from this folder, I have tried, <? php include("../page1.php");?>, but this only bring me up one level, <? php include("../../page1.php");?> which I think is wrong anyway, and doesn't work, and also <? php include("./page1.php");?>, again does not work. Does anyone know if it is possible to get the file from the subfolders to access a file located directly in the root? Sorry if I'm not being clear explaining the layout etc. Thanks. How do you include files from a higher up directory? I'm currently working on a file in public_html/Directory/otherdirectory and want to include a config file that's in public_html/Directory so how would I include public_html/Directory/config.php in the public_html_Directory/otherdirectory/index.php file? I've tried using ../ and ../Directory/ in the includes line but got errors both times Edited April 11, 2020 by Nematode128Hello, I've got what should be a simple solution here. I've tried many things but it just won't work for me. This is what I have. I've got a wysiwyg editor setup to write to a file called news.php. The file that has the editor is edit/index.php. It's just a simple textarea. The textarea is supposed to include news.php. For some reason, it won't let me include that file that is in a lower directory. The file that writes to news.php is called edit/write.php. edit/write.php doesn't write to news.php instead it writes to edit/news.php. The only reason I want to include the lower directory is so that I can put a .htaccess password protection on the edit directory. I'll include some code below. Code: (edit/index.php) [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head> <title>Editing News</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <script type="text/javascript" src="nicEdit.js"></script> <script type="text/javascript"> bkLib.onDomLoaded(function() { nicEditors.allTextAreas() }); </script> <form method="post" action="write.php"> <p> <textarea name="content" style="width:100%;height:1000px;"><?php include '../news.php';?></textarea> <input type="submit" value="Save" /> </p> </form> </body> </html> Code: (edit/write.php) [Select] <?php $File = "../news.php"; $Handle = fopen($File, 'w'); $Data = $_POST['content']; fwrite($Handle, $Data); fclose($Handle); header("Location: index.php"); ?> index.php is just a simple include news.php. Am I missing an easy step? Any help would be great!! Thanks! Hey all, I viewed this tutorial and the guy used $_SERVER['DOCUMENT_ROOT'] to reference a view layout for his specific index file. So I tried to imitate and did exactly what he did, but for me I got the following error: Code: [Select] Warning: include(/Users/jmerlino/Sites/mark/public/diet/views/layouts/shop.php) [function.include]: failed to open stream: No such file or directory in /Users/jmerlino/Sites/diet/index.php on line 22 Warning: include() [function.include]: Failed opening '/Users/jmerlino/Sites/mark/public/diet/views/layouts/shop.php' for inclusion (include_path='.:/usr/lib/php') in /Users/jmerlino/Sites/diet/index.php on line 22 This is the php code that is causing this error: include($_SERVER['DOCUMENT_ROOT'].'/'.'diet/views/layouts/'.$controller.'.php'); I'm not sure why it's going to: /Users/jmerlino/Sites/mark/public/diet/views/layouts/shop.php instead of: /Users/jmerlino/Sites/diet/views/layouts/shop.php Thanks for any response trying 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 Hi guys, I've been working on a script for a while now, and I'm sure it doesn't look great and all, and it's probably really messed up.. But right now I've finally got it working! There's only 1 thing I'd really like to add.. Searching through & listing of remote directories! The directories I'm trying to list have directory listings enabled, and I think it *should* be possible. I just have no clue how. Here's my current code in a beautiful mix of HTML and PHP: <? $border_size = "0"; function returner($what) { $what=explode("/",$what); $tps=count($what); $what=$what[$tps-1]; return $what; } $page_url= ""; $home_url=returner(__FILE__); if(isset($_GET['q'])) { $qtext=$_GET['q']; } else { $qtext=""; } function getdirsize($directory, $format=FALSE) { $size = 0; if(substr($directory,-1) == '/') { $directory = substr($directory,0,-1); } if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return -1; } if($handle = opendir($directory)) { while(($file = readdir($handle)) !== false) { $path = $directory.'/'.$file; if($file != '.' && $file != '..') { if(is_file($path)) { $size += filesize($path); } elseif(is_dir($path)) { $handlesize = getdirsize($path); if($handlesize >= 0) { $size += $handlesize; } else { return -1; } } } } closedir($handle); } if($format == TRUE) { if($size / 1048576 > 1) { return round($size / 1048576, 1).' MB'; } elseif($size / 1024 > 1) { return round($size / 1024, 1).' KB'; } else { return round($size, 1).' bytes'; } } else { return $size; } } if(isset($_GET['type'])){ $type=$_GET['type']; } else { $type="new"; } $textures=0; $models=0; $avatars=0; $seqs=0; $sounds=0; foreach (glob("textures/*.jpg") as $texture){ $textures++; } foreach (glob("models/*.zip") as $model){ $models++; } foreach (glob("avatars/*.zip") as $avatar){ $avatars++; } foreach (glob("seqs/*.zip") as $seq){ $seqs++; } foreach (glob("sounds/*.zip") as $sound){ $sounds++; } ?> <!DOCTYPE html> <html> <head> <title>ObjectPath Search</title> <style type="text/css"> #wrapper { width: 850px; margin: 30px auto 30px auto; padding: 10px; } body { color:#C6C6C6; background:#1E1E1E; /* margin:0; padding:0; */ overflow-x:hidden; } #tabs { font: 85% "Trebuchet MS", sans-serif; } .left { float: left; } .right { float: right; } a:link, a:visited, a:active { color: #3DB015; text-decoration: none; } a:hover { color: #00E0FF; } h2 { color: #3DB015; padding-bottom: 0.2em; font-size: 110%; } ul#icon {margin: 0; padding: 0;} ul#icon li {margin: 1px; position: relative; padding: 1px 0; cursor: pointer; float: left; list-style: none;} ul#icon span.ui-icon {float: left; margin: 0 1px;} </style> <link type="text/css" href="http://objects.jk-hosting.com/search/css/black-tie/jquery-ui-1.8.2.custom.css" rel="stylesheet" /> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-ui-1.8.2.custom.min.js"></script> <script type="text/javascript"> function formHandler(form){ var URL = document.form.site.options[document.form.site.selectedIndex].value; window.location.href = URL; }; $(function(){ // Tabs $('#tabs').tabs(); }); </script> </head> <body> <div id="wrapper"> <div id="tabs"> <!-- Tabs start --> <ul> <li><a href="#tab-search">Search</a></li> <li><a href="#tab-list">List Objects</a></li> <li><a href="#tab-info">OP info</a></li> </ul> <div id="tab-search"><!-- Searchtab start --> Please enter a string to search for, and choose a folder to search in. <br /><br /> <form name="Search"> <input type='hidden' value='search' name='type'> <input value='<? print $qtext; ?>' type='text' name='q'> <select name='map'> <option selected='selected' value='models'>Models</option> <option value='avatars'>Avatars</option> <option value='textures'>Textures</option> <option value='seqs'>Seqs</option> <option value='sounds'>Sounds</option></select> <input type='submit' value='Search'> </form> </div> <!-- Searchtab end --> <div id="tab-list"><!-- Listtab start --> Please pick a folder to browse. <br /><br /> <form name="form"> <select name="site" onChange="javascript:formHandler()"> <option value="#">Look in folder...</option> <option value="<? print $page_url; ?>?type=list&map=models">Models</option> <option value="<? print $page_url; ?>?type=list&map=avatars">Avatars</option> <option value="<? print $page_url; ?>?type=list&map=textures">Textures</option> <option value="<? print $page_url; ?>?type=list&map=seqs">Seqs</option> <option value="<? print $page_url; ?>?type=list&map=sounds">Sounds</option> </select> </form> </div> <!-- Listtab end --> <div id="tab-info"><!-- Info tab start --> The OP currently contains: <br /><br /> <table> <tr><td><b><? echo $models; ?></b></td> <td>Models</td></tr> <tr><td><b><? echo $avatars; ?></b></td> <td>Avatars</td></tr> <tr><td><b><? echo $textures; ?></b></td> <td>Textures</td></tr> <tr><td><b><? echo $seqs; ?></b></td> <td>Seqs</td></tr> <tr><td><b><? echo $sounds; ?></b></td> <td>Sounds</td></tr> </table> </div> <!-- Info tab end --> </div> <!-- Tabs end --> </div> <!-- Start PHP generated content --> <? if($type=="search" || $type=="list") { $M=$_GET['map']; if($type=="search") { $Q=$_GET['q']; $empty="Nothing found with <b>\"" . $Q . "\"</b> in it's name.<br />\nPlease make a more general search query, or try a different folder.\n\n"; } else { $Q=""; $empty='This folder is empty'; } if($M=="textures") { $ext="jpg"; } else { $ext="zip"; } $i=0; print "<hr>\n"; $endfile=array(); $endsize=array(); $endsize2=array(); foreach (glob($M."/*".$Q."*.".$ext) as $filename) { $filename = explode(".", $filename); $filename=$filename[0]; $filename = explode("/", $filename); $filename=$filename[1]; $i++; $endfile[$i]=$filename; if($ext=="jpg") { $endfile[$i]="<a name='".$endfile[$i]."' href='".$pageurl."?type=view&name=".$endfile[$i]."&folder=".$M."&from=".$type."&addon=".$Q."'>".$endfile[$i]."</a>"; } $endsize[$i]=$size; $endsize2[$i]=$size2; } if($i != 1) { print "<b>".$i."</b> items were found.\n<hr>\n"; } else { print "<b>".$i."</b> item was found.\n<hr>\n"; } echo("<table width='100%' border='" . $border_size . "' cellspacing='0' cellpadding='0' >\n"); if($i!=0) { for ($t = 1; $t < $i; $t++) { $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } if($t=="1") { echo("<tr><td width='10%'>Number</td><td width='3%'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></td><td width='60%'>Name</td></tr>\n"); } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); flush(); } $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); } print "</table>\n"; if($i=="0") { print $empty; } } elseif($type=="view") { $filename=$_GET['name']; $folder=$_GET['folder']; if($_GET['from']=="list"){ $addon="?type=list&map=".$folder."#".$filename; } if($_GET['from']=="search"){ $addon="?type=search&q=".$filename."&map=".$folder."#".$filename; } print"<center><a href='".$home_url."'>Home</a></center>"; print "<hr>\n<center><img src='".$folder."/".$filename.".jpg'></img></center>\n<hr>\n<br />\n<a href='".$page_url."".$addon."'>Previous Page</a>\n"; } $htmlshow=""; if($_GET['type']=="returnOPfile") { if(isset($_GET['split'])) { $splitter=$_GET['split']; } else { $splitter=" | "; } if(isset($_GET['html'])) { $htmlshow="<br />"; } foreach (glob("textures/*.jpg") as $texture){ if(isset($_GET['size'])) { $size=$splitter.filesize($texture); } $texture = explode("/", $texture); $texture=$texture[1]; print "textures".$splitter.$texture.$size."\n".$htmlshow; } foreach (glob("models/*.zip") as $model){ if(isset($_GET['size'])) { $size=$splitter.filesize($model); } $model = explode("/", $model); $model=$model[1]; print "models".$splitter.$model.$size."\n".$htmlshow; } foreach (glob("avatars/*.zip") as $avatar){ if(isset($_GET['size'])) { $size=$splitter.filesize($avatar); } $avatar = explode("/", $avatar); $avatar=$avatar[1]; print "avatars".$splitter.$avatar.$size."\n".$htmlshow; } foreach (glob("seqs/*.zip") as $seq){ if(isset($_GET['size'])) { $size=$splitter.filesize($seq); } $seq = explode("/", $seq); $seq=$seq[1]; print "seqs".$splitter.$seq.$size."\n".$htmlshow; } foreach (glob("sounds/*.zip") as $sound){ if(isset($_GET['size'])) { $size=$splitter.filesize($sound); } $sound = explode("/", $sound); $sound=$sound[1]; print "sounds".$splitter.$sound.$size."\n".$htmlshow; } } ?> <!-- End PHP generated content --> </body> </html> So right now my question to you PHP freaks is, can you please help me edit my script so I can search through a remote directory? *This* is one of the directories I wish to be able to search through & list.. Thanks in advance. Edit; It might help if you know what the site currently looks like. *Click* i have made an delete files script which works for only one directory but not sub directory so i want to delete files of same extention from directory and subdirectory. My current code is Code: [Select] <? $dir = 'hmm/'; function scanr($dir){ $arr = glob($dir.'/*.jpg'); foreach($arr as $vv){ //check if $vv is a file if(is_file($vv)){ //if file, get the filename $vx=explode('/',$vv); $file=$vx[count($vx)-1]; // if no extension delete the file unlink($vv); // print the deletion message echo $vv." deleted!<br>";}else{ // if $vv is a dir then scan it again for files scanr($vv); }} } scanr($dir); ?> |