Jump to content

[SOLVED] Ripping my hair out over this mis-functional code


.evo.

Recommended Posts

Ok so I've seen a bunch of tutorials and stuff on using if/else statements and $_GET variables. And I've developed my own dynamic content code, so that if the URL is "index.php?act=test" it would show "content/test.php", but if it didn't exist it would show a 404 error. I had that working fine and everything, but then I tried to make it so if the act= part wasn't set, it would automatically show "content/home.php", and this is where I got stuck. I cannot get it to work no matter what I do. If I get the main function (content + 404 error) of the code to work then the home part will not work, and when I edited the code to try and make it work, it gave the 404 error no matter what. EDIT: Also, it's not a syntax error or anything, I have validated the code using phpDesigner, it's just not functioning properly.

 

// this was a solution to a problem on another forum so I thought it wouldn't hurt to add it
setlocale(LC_ALL, 'en_US.UTF8'); 

$idx = "/index.php";
$cur = $_SERVER['REQUEST_URI'];
$act = $_GET['act'];
$filename = "content/$act.php";

if (is_null($act)){
$act = "home";
}

function show_content(){
if (file_exists($filename)){ 
	include($filename);
} else { 
	include("content/404.php");
}
} 

 

This was in my "functions.php" which I include on my "index.php", then where I want my content I just put "show_content()".

 

This is my first serious PHP code so I thought I might share with more experienced coders. Any help or suggestions will be great.

You need to pass the value of "$filename" to your function. Variables inside a function are local in scope unless they are set to GLOBAL. Also, you're setting the value of $filename before checking for null.

 

Try this:

<?php
function show_content($act){
        $f = (file_exists("content/$act.php"))?"content/$act.php":"content/404.php"
include($filename);
}

$idx = "/index.php";
$cur = $_SERVER['REQUEST_URI'];
$act = (isset($_GET['act']))?$_GET['act']:'home';
show_content($act);
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.