Code to determine folder depth "../" in PHP? - php

Thanks in advance for the help that will be received!
I used to use a code I made when I first started, due to not being able to find a snippet that does what I want. (Maybe to not knowing the terminology) I'm sure there's a more simple way, which is why I'm asking advice.
/EDIT/
The pages that will use this template are temporarily hosted in a subdirectory of another website, and using "/" to start at the root of the page isn't an option I want to go with, due to wanting to effortlessly drop the website on a different hosting server and add a domain name to the pages so the path from root (ex. "/temp-dir/site/images/image.jpg") will need updated, whereas, using a previous directory (ex. "../../../images/image.jpg") will work from existing site and new location upon move.
/endEDIT/
What I am trying to achieve is applying the proper amount of "../" before the file names in a header template using a method like:
<link href="<?php if(isset($pDepth)){ echo $prev; }?>style.css" />
Where $prev will equal previous directory code ranging from "../" to "../../../../" depending on the variable $pDepth on each web page. For example:
if($pDepth == 3){the output of $prev will equal "../../../"}
I seen where the output can change using ++, but you can't add strings can you? I'm thinking something like:
if($pDepth == 4){
$i = 0;
while($i != $pDepth){
// help needed here
// add "../" until $prev = "../../../../"
}
}
I'm still learning to write code, and would appreciate any help. Thanks Again!

$prev = str_repeat('../', $pDepth);

$pDepth = $pDepth . "../";
Should work just fine.

To concatenate strings in PHP, you use the . operator.
Try this:
if($pDepth == 4){
$i = 0;
while($i != $pDepth){
$prev .= '../';
$i++;
}
}

Related

Breadcrumbs with links back to previous folder

Today we are in the process of making a file manager script for our new hosting control panel interface and we want to make breadcrumbs that the user can click on to go back to the path before it. So far they show up like this
Looks alright I suppose. The first three links are static and never change, and the farther off the /home that the user goes, the more links are added to the breadcrumb. Right now if you were in a directory like we are here aka /home/www/usr/ then the url looks something like this:
/filemanager.php?do=browse&dir=www/usr
Then we explode the $_GET['dir'] between all the items separated by a / and add them into an array. Then we loop through the array and foreach one we print out an <li>$i</li> into the breadcrumb area.
The problem now, is how can we make the links for each item in the menu keep its parent folder and / if it has one? When a user clicks on www in this example, it works because it's the same link as the name, but any child li needs www/ added to the front, and any other parents as well. A bit stumped here.
Here's the LI adding process we are using:
if(isset($_GET['dir']) && !empty($_GET['dir'])) {
$breadcrumb_list = array();
$breadcrumb_list = explode("/", $_GET['dir']);
echo "<li>Home</li>\n";
foreach($breadcrumb_list as $i) {
echo "<li>{$i}</li>\n";
}
}
Any and all help will be appreciated! Thanks guys!
Before foreach loop create new variable eg
$path = '';
Then in every iteration add current part of path:
$path .= '/'.$i;
So it will looks like that:
$path = '';
foreach($breadcrumb_list as $i) {
$path .= '/'.$i;
echo "<li>{$i}</li>\n";
}

Possible to use PEAR SearchReplace to replace text within a .php file?

I came across this simple pear tutorial over here: http://www.codediesel.com/php/search-replace-in-files-using-php/
include 'File/SearchReplace.php' ;
$files_to_search = array("fruits.txt") ;
$search_string = "apples";
$replace_string = "oranges";
$snr = new File_SearchReplace($search_string,
$replace_string,
$files_to_search,
'', // directorie(s) to search
false) ;
$snr->doSearch();
echo "The number of replaces done : " . $snr->getNumOccurences();
The writer uses the fruits.txt file as an example.
I would like to do a search and replace on a .php file.
Basically what I am trying to achieve would be this:
On a user interaction, index.php is opened,
$promoChange = "%VARYINGTEXT%";
is searched for and replaced with
$promoChange = "$currentYear/$currentPromotion";
The $current variables will vary, hence the need to change the words inbetween the "" only.
Does anyone have any input on how this type of task could be accomplished?
If anyone knows of any tutorials relating to this subject, that too would be greatly appreciated.
Thank you!
I do have everything else figured out, regarding the template and user interaction, I am just having trouble trying to work out how to accomplish this type of search and replace. I have an understand of how it should be done as I have made something similiar using visual basic. But I am starting to this that my answer for this would be perl? I hope that this is not so...
Okay, my problem is partly solved with this:
// Define result of Activate click
if (isset($_POST['action']) and $_POST['action'] == 'Activate')
{
include ''.$docRoot.'/includes/pear/SearchReplace.php' ;
$files = array( "$docRoot/promotions/index.php" ) ;
$snr = new File_SearchReplace( '$promoChange = "";', '$promoChange = "'.$currentYear.'/'.$currentPromotion.'";', $files) ;
$snr -> doSearch() ;
}
but how do i get it to search and replace something like $promoChange = "%VARYINGTEXT%";
It found and replaced "" with the current session values. But now that is has changed, I need it to replace and text inbetween "AND".
Any ideas anyone?
If you only need to adapt a single file, then do it manually:
$src = file_get_contents($fn = "script.php");
$src = str_replace('"%VARYINGTEXT%"', '"$currentYear/$currentPromotion"', $src);
file_put_contents($fn, $src);
str_replace is sufficient for your case.
Why on earth do you want to do something like that? Frameworks like PHP do exist solely on the base of not having to write a page for each different view of the same interaction. What's wrong with just including the PHP page you now want to change, and set the variables accordingly before calling it?
Ontopic: I don't see why what you're doing is a problem, purely technically speaking. This can be done using PHP. But really, you shouldn't.

URL querystring with a php include

I'm trying to include a file to output in a tab on a page. The file itself will pull up just fine, but when I try to add the required querystring to it, it gives me a "failed to open stream: No such file or directory" error.
I've tried just a straight include and tried setting the querystring as a variable. Here's where I'm at right now.
$listingVars = '?mls=' . $_REQUEST['mlid'] . '&lid=0&v=agent';include("agentview.php$listingVars");
Has anyone successfully done this?
You can't include a query string in an include().
Assuming this is a local script, you could use:
$_REQUEST['mls'] = $_REQUEST['mlid'];
$_REQUEST['lid'] = 0;
$_REQUEST['v'] = 'agent';
include("agentview.php");
if it's a remote script on a different server, don't use include.
I created a variable on the 2nd page - and passed it a value on the first page - and it worked for me:
*Page with include: 'index.php'
<?php $type= 'simple'; include('includes/contactform.php'); ?>
*Page included: 'includes/contactform.php'
switch($type){
case 'simple':
//Do something simple
break;
default:
//Do something else
break;
}
I modify the accepted answer given by Frank Farmer a bit to work for different queries:
Include twice would cause problem:
$_REQUEST['mls'] = $_REQUEST['mlid'];
$_REQUEST['lid'] = 0;
$_REQUEST['v'] = 'agent';
include("agentview.php");
//changing the v to another
$_REQUEST['v'] = 'agent2';
include("agentview.php");
For those who encounter this multiple include problem, you could wrap you code inside "agentview.php" in a function:
Inside agentview.php
function abc($mls,$lid,$v){
...your original codes here...
}
file need to call agentview.php
include_once("agentview.php");
abc($_REQUEST['mlid'], 0, 'agent');
abc($_REQUEST['mlid'], 0, 'agent2');
Hope it helps someone encounter the same problem like me and thanks Frank Farmer for the great solution which saved me alot of time.

Switching languages on a website with PHP

I'm just looking for some advice. I'm creating a website that offers (at least) 2 languages.
The way I'm setting it up is by using XML files for the language, PHP to retrieve the values in the XML nodes.
Say you have any XML file, being loaded as follows:
<?php
$lang = "en";
$xmlFile = simplexml_load_file("$lang/main.xml");
?>
Once the file contents are available, I just output each node into an HTML tag like so:
<li><?php echo $xmlFile->navigation->home; ?></li>
which in turn is equal to : <li>Home</li>
as a nav bar link.
Now, the way in which I'm switching languages is by changing the value of the "$lang" variable, through a "$_POST", like so:
if(isset($_POST['es'])){
$lang = "es";
}elseif(isset($_POST['en'])){
$lang = "en";
}
The value of the "$lang" variable is reset and the new file is loaded, loading as well all the new nodes from the new XML file, hence changing the language.
I'm just wondering if there is another way to reset the "$lang" variable using something else, other than "$_POST" or "$_GET". I don't want to use query string either.
I know I could use JavaScript or jQuery to achieve this, but I'd like to make the site not too dependable on JavaScript.
I'd appreciate any ideas or advice.
Thanks
I would go for session variable.
At the beginning of your pages you'll have:
if (!isset($_SESSION['language']))
$_SESSION['language'] = "en";
Then you'll have some links to change the language
Español
Français
Changelanguage.php simply is something like
$language = $_GET['lang'];
// DO SOME CHECK HERE TO ENSURE A CORRECT LANGUAGE HAS BEEN PASSED
// OTHERWISE REVERT TO DEFAULT
$_SESSION['language'] = $language;
header("Location:index.php"); // Or wherever you want to redirect
Have you thought about using $_SERVER["HTTP_ACCEPT_LANGUAGE"]? Something like this:
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"]) {
$langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
for ($i = 0; $i < count($langs); $i++) {
if ($langs[$i] == "en") {
$lang = "en";
break;
}
elseif($langs[$i] == "es") {
$lang = "es";
break;
}
}
}
Of course, a switch statement might fit a bit better here, and there's more ways to say English than only en, but this should work without the user having to do a thing. If they manually change, store it in a cookie as per Ben's answer.
The most common way would be to use it as part of the url and extract it when a page loads:
http://www.your-site.com/en/somepage
Are you using a framework?
The most common way to pass a language identifier is subdomain.
http://en.wikipedia.com/
both subdomains should point to the same directory and actual language can be easily extracted from the HTTP_HOST
and for storing language files the solution is gettext

Remembering text resizing across different pages on a web site using PHP SESSIONS

So after reviewing some tutorials on how to change text size and creating my own using PHP I was wondering how can I have my text size remembered across many different pages on my web site using PHP SESSIONS?
Here is the PHP text sizer code below.
$size = 100;
if(isset($_GET['i']) && is_numeric($_GET['i'])) {
$s = $_GET['i'];
}
if($s == TRUE){
$size = ($s * 1.2);
}
if(isset($_GET['m']) && is_numeric($_GET['m'])) {
$m = $_GET['m'];
}
if($m == TRUE){
$size = ($m * 0.8);
}
if(isset($_GET['n']) && is_numeric($_GET['n'])) {
$n = $_GET['n'];
}
if($n == TRUE){
$size = 100;
}
Here is the CSS code.
#content {
font-size : <?php echo $size; ?>%;
}
And here is the xHTML.
Increase<br />
Decrease<br />
Normal<br />
First all, make sure you out put session_start() on all pages, before any content is posted.
From here, you're able to set session variables (which will be saved into a session cookie typically).
So when your user clicks a link, PHP should set something like $_SESSION['i'] = $_GET['i']; and then when you visitor comes back to a page, you just see if $_SESSION['i'] has a value - if it does, use this value, if not, revert to default.
Check out this great tutorial: php sessions - why use them?
Just don't use $_GET variables, use $_SESSION vars instead. Be sure to include the relevant session_start() functions and all that.
As mentioned, you'll want to your the $_SESSION object instead of $_GET. You'll need to add a call to session_start() at the start of each page (check the examples on this link; will show you how to use sessions on a basic level). You may also want to take a look at Local Web Storage (browser-based) in HTML5. Check out this tutorial. It's quite easy to implement. Of course, not all browsers implement web storage, but it's pretty ubiquitous (Depending if you want to support < IE8)

Categories