Do I need to use substr() to bring up a directory or can I another code?

413 views Asked by At

Everything in this file is set up in a way in which $_GET['q'] brings up the main domain name and the other directories in the website are brought up in this manner: else if (substr($_GET['q'], 0, 7) == 'quotes/') If I wanted to have a folder called: ultimate-deals-and-low-prices, would I use

else if (substr($_GET['q'], 0, 30) == 'ultimate-deals-and-low-prices/')

Does that make sense, or would I call my directory in another manner, without having to ask php to call a substring of the directory file name. I understand that is what substring does, but I've only seen it be used for characters less than 10. If my directory has more characters, would I still use substring?

This is the beginning of the if statement in this document:

require_once(getcwd() ."/db/db_pagetitle.php");
print get_page_title($_GET['q']);
if (isset($_GET['q']) && $_GET['q']) {
    if (file_exists(getcwd() .'/pages/'. $_GET['q'] .'.php')) {
        require_once(getcwd() .'/pages/'. $_GET['q'] .'.php');

than it goes into

else if (substr($_GET['q'], 0, 7) == 'quotes/') 

How do I call my directory?

Thanks?

3

There are 3 answers

0
deviousdodo On

You can still use substr, there's no problem with having more than 10 characters :) In other words, you can use exactly the code you've posted (if you don't mind the typing): else if (substr($_GET['q'], 0, 30) == 'ultimate-deals-and-low-prices/')

But, if there is some of common logic for all folders (like, cd-ing into it or searching for a file in it) you don't have to write an else branch for each folder, you can just use something like:

if (isset($_GET['q']) && $_GET['q']) {
    if (file_exists(getcwd() .'/pages/'. $_GET['q'] .'.php')) {
        require_once(getcwd() .'/pages/'. $_GET['q'] .'.php');
    } else if (is_dir(getcwd() . '/pages/' . $_GET['q'])) {
        // do whatever you want to do with the folder
    }
}

If you would write more of your code it'd be easier to understand what you're trying to do.

0
Adam Fowler On

You could use a detection system if you are going to use multiple keywords.

$match[]='ultimate-deals-and-low-prices/';
$match[]='users/';
$match[]='imgs/';
foreach($match as $k=>$v){
$l=strlen($v);
$s=substr($_GET[q],0,$l);
if ($v==$s) //Code to run...
}
0
rodneyrehm On

Whatever happened to strpos?

<?php

if (file_exists($sanitizedPath)) {

} elseif (strpos($_GET['q'], "ultimate-deals-and-low-prices/") === 0) {

} elseif (strpos($_GET['q'], "some-other-directory/") === 0) {

}

less to type, less error-prone, faster.