Jump to content

array problem, I think


genovauk

Recommended Posts

<?php

require_once('inc/db.php');
$page = $_GET['page'];

$linkcellaosa = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$linkcellaosa) {
die('Failed to connect to server: ' . mysql_error());
}
$dbcellaosa = mysql_select_db(DB_DATABASE_SA);
if(!$dbcellaosa) {
die("Unable to select database");
}


$qry_pages = "SELECT * FROM allowed_pages";
$result_pages = mysql_query($qry_pages);


while($row_pages = mysql_fetch_array($result_pages)) {
$pages = $row_pages['pages'];
}
$allowed = array ( $pages );


if(in_array($page, $allowed)) {
$page .= '.php';
include($page);
} else {
echo "<h1>Page does not exist or is not allowed</h1>";
}

?>

 

The above script is my attempt to create a index.php?page=somepage url with a bit of security to prevent unauthorised pages being added unless it's in the list of allowed pages.

 

The table consists of :

 

ID    Pages

-------------

1    news

2    about

3    contact

 

At the moment only the last item in the page column is allowed to be displayed, The contact form (contact.php) If anyone could please help where i'm goin wrong.

 

If I change

 

$allowed = array ( $pages );

 

to

 

$allowed = array ('news','about','contact');

 

everything works as it should, But I want to pull the pages from a mysql table instead of having to edit this script with all the pages I want to allow.

 

Link to comment
https://forums.phpfreaks.com/topic/127355-array-problem-i-think/
Share on other sites

well this is how i would do it.

 

<?php
//get all the allowed pages from db
$query = //query to get all the pages
$result = mysql_query($query);

// create an empty array to fill with acceptable url's
$url_array = array();

// put each 'url' into an array
foreach($result as $url) {
$url_array[] = $url['pages'];
}

//check the array for allowed pages
if (in_array($_GET['page'], $url_array)) {
$this_page = $_GET['page'] . '.php';
} else {
$this_page = 'index.php';
}

?>

 

hope this helps/works

Please try this

 

<?php
$allowed = array();
while($row_pages = mysql_fetch_array($result_pages)) {
  $pages = $row_pages['pages'];
  array_push($allowed, $pages);
}
?>

 

Worked like a dream thanks, I'm only a beginner at this stuff and iv'e kinda thrown myself into the deep end but I'm getting there slowly.  ;D

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.