php include() won't work? - php

I am having trouble getting my include() function to work in my code. Basically I have a the $order array that has the order that my pages will be shown in.
In this case: page numbers: 1,2,3,4,5,6 as seen in the $order array.
If I just post 6 include() function's with the exact path, the pages are shown, however if I try to include them under this for() loop it doesn't work.
$order Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
$fields = 6;
The weird part is if I make the array 4,5,6,1,2,3 it work's perfectly:
$order Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 1 [4] => 2 [5] => 3 )
Only show's first 3 pages
for($x = 0; $x < $fields; $x++)
{
$page_info = mysql_query("SELECT * FROM pages WHERE id='" . $order[$x] ."'");
$pageInfo = mysql_fetch_array($page_info);
$pageNum = $pageInfo['id'];
if($pageNum <= 6)
{
$pagePath = "page" . $pageNum . ".php";
include($pagePath);
}
}
What is confusing is I know it is reading each $pageInfo['id'] because this is the following output:
Output: 123456
for($x = 0; $x < $fields; $x++)
{
$page_info = mysql_query("SELECT * FROM pages WHERE id='" . $order[$x] ."'");
$pageInfo = mysql_fetch_array($page_info);
echo $pageInfo['id'];
}
This works
include("page1.php");
include("page2.php");
include("page3.php");
include("page4.php");
include("page5.php");
include("page6.php");

You probably have $x set to some number inside one of the includes. If it is only showing the first three, then perhaps in page3.php you have something like $x = 7;.

You obviously have the numbers coming out that you're expecting to see (1-6), because you are printing them to the screen. You've tried a suggestion of using trim which didn't get you any further.
My presumption is that your echo used for debugging is places outside your if statement, and that your if statement isn't running every time you expect it to. Firstly, try putting your echo inside the if statement to make sure that your output is the same, then put var_dump($pagePath); into it as well to ensure that your variable is what you're expecting.
Another thing you could try, you could make sure the file exists:
echo (file_exists($pagePath)) ? 'Exists' : 'Does not exist...';
You could post us the code in your included files to check that you aren't overwriting variables like $x or $pageNum etc from your includes - variables are global between includes and will overwrite eachother.
Finally, I know you'll have a good explanation for this, but this looks pretty longwinded to me, in this particular application, you could just do this:
for($i = 1; $i <= 6; $i++) {
include 'page' . $i . '.php';
}
SIDE NOTES:
mysql_* functions are deprecated and you should be using either PDO or mysqli. Resources:
- http://php.net/manual/en/book.pdo.php
- http://php.net/manual/en/book.mysqli.php
PHP's include function is a language control structure, not a function, so shouldn't be used with brackets: (for you downvoters, I'm not saying it can't, I'm saying it shouldn't)
// good:
include 'filename.php';
// bad:
include('filename.php');

1) I would not recommend fetching the DB on a loop but keeping your example:
You could try inside your loop something like
if($pageNum ){ //lets omit the <=6 for the test.
$pagePath = "page" . $pageNum . ".php";
echo "include($pagePath);";
}
and check the results, maybe you are getting something different to what you are expecting.

Try this
for($x = 0; $x < count($order); $x++)
{
$page_info = mysql_query("SELECT * FROM pages WHERE id=" . $order[$x]);
$pageInfo = mysql_fetch_array($page_info);
foreach($pageInfo as $p_info)
{
$pageNum = $p_info['id'];
break;
}
if($pageNum <= 6)
{
$pagePath = "page" . $pageNum . ".php";
require_once($pagePath);//If it can't find the file then it will kill page and show corresponding error
}
}

Related

PHP counting varibles and redirecting

I've been scratching my head on the best way to accomplish this.
I'm getting 8 variables from a url:
a=imagine
b=lead
c=champion
d=champion
e=champion
f=champion
g=lead
h=champion
In this example there's 5 "champion" so I'd redirect to my champion page.
I've added them into an array:
$a = $_GET["a"]; $b = $_GET["b"]; $c = $_GET["c"]; $d = $_GET["d"]; $e = $_GET["e"]; $r = $_GET["r"]; $g = $_GET["g"]; $h = $_GET["h"];
$info = array($a,$b,$c,$d,$e,$f,$g,$h); print_r(array_count_values($info));
and then printed: Array ( [imagine] => 1 [lead] => 2 [champion] => 5 )
Am I doing it right? How can I use those values to redirect to my champion page as that's the highest count?
First, I agree that array_count_values is a good tool for this, but you don't need to make a new array with all the $a, $b, etc. variables. You can just do
$info = array_count_values($_GET);
After you have that, you can sort the array in descending order and take the first key to find the page you want to redirect to.
arsort($info);
$location = key($info);
I agree with the other answer that redirecting to a page based on user input is risky, and you should not redirect without first verifying that the location is valid. If you only have a few valid locations, this could be as simple as:
if (in_array($location, ['champion', 'lead', 'imagine'])) {
header("Location: yourdomain/$location");
}
If I understand you correctly:
$list = ['imagine' => 1 ,'lead' => 2, 'champion' => 5 ];
// find the highest count
$highest = max($list);
// check what page it is
foreach($list as $page=>$count){
// redirect
if($count === $highest){
header('Location: ' . $page);
exit();
}
}
Beware that relying on the user input is not safe. I'd also look up a white list for the pages.

Question on searching through a php array and return a value

Wondering how I can search through the following array for [law] and just return [fine] for that law?
Array ( [0] => Array (
[law] => Unroadworthy Vehicle
[fine] => 500
[jail] => 0
[statute] => Any registered vehicle that is lacking headlights, taillights, windshields, has extensive damage, or deemed unsafe to operate, can be considered unroadworthy. Vehicles to do not return a registration shall also be considered unroadworthy. )
[1] => Array (
[law] => Headlights Required
[fine] => 500
[jail] => 0
[statute] => Failure to use headlights after dark or in poorly lit areas or roadways )
..(array continues through 108 unique items)
I have this to loop through and display the law in a dropdown
echo "<select name=\"charge\">";
$strJsonFileContents = file_get_contents("./includes/laws.json");
$issue = json_decode($strJsonFileContents, true);
$arrlength = count($issue);
for ($x = 0; $x < $arrlength; $x++)
{
$law = $issue[$x][law];
echo "<option name=\"law\" value=\"$law\">$law</option>";
}
echo "</select><br><br>";
I'm actually not going to do the hidden element part.
I want to search through json_decode for [law] and return it's [fine]
If all you need to do is pass the fine, then this would work:
echo "<select name=\"charge\">";
$strJsonFileContents = file_get_contents("./includes/laws.json");
$laws = json_decode($strJsonFileContents, true);
foreach ($laws as $law) {
echo '<option name="law" value="' . $law['fine'] . '">' . $law['law'] . '</option>';
}
echo "</select><br><br>";
If you need to pass the law and the fine, then you'd need to use some javascript to store the json object, listen for the select field to change and then add the fine to a hidden field when it is changed by looping through the json object and grabbing the fine based on which law was chosen.
Your $law variable has not the expected value and you should get an error like this:
Use of undefined constant law - assumed 'law'
echo "<select name=\"charge\">";
$strJsonFileContents = file_get_contents("./includes/laws.json");
$issue = json_decode($strJsonFileContents, true);
$arrlength = count($issue);
for ($x = 0; $x < $arrlength; $x++)
{
$law = $issue[$x]['law'];
echo "<option name=\"law\" value=\"$law\">$law</option>";
}
echo "</select><br><br>";
About the hidden [fine] element you can have a look to this question and do something like this:
$('#mySelect').change(function(){
var id = $(this).find(':selected')[0].id;
$('#hiddenFineInput').val(id);
})
I was way overthinking it.. seems this will achieve what I was after.
$arrlength = count($issue);
for ($x = 0; $x < $arrlength; $x++) {
if($issue[$x]['law'] == $law) { $fine = $issue[$x]['fine']; }
}

Removing a certain number out of a session array in PHP

I have a button next to all my 'shop items' that can remove one of the shop item, however i need it to just remove one, and not rid the entire array of the number, i thought this was possible by using a break statement when i found the number i want to remove, but it removes all of the numbers.
if (isset($_GET['remove']) && isset($_SESSION['shopitems'])) {
if (in_array($_GET['remove'], $_SESSION['shopitems'])) {
for ($i = 0; $i < sizeof($_SESSION['shopitems']); $i++) {
if ($_SESSION['shopitems'][$i] == $_GET['remove']) {
$shopArray = $_SESSION['shopitems'];
if(sizeof($shopArray) == 1) {
$_SESSION['shopitems'] = null;
$_SESSION['added'] = null;
} else {
array_splice($shopArray, $i, $i);
$_SESSION['shopitems'] = $shopArray;
}
break;
}
}
}
}
Here i check if the URL contains the remove variable and the session is set, once i have done this, i check if the array contains the number that is put in the URL, if so i'll start a for loop and check if the key index of the session shop items is equal to the URL variable, if so i want to remove it, however if i use array_splice, suddenly they are all gone, is this because of the function i am using? Or is the break not executing correctly?
Why don't you try array_search() and unset()? It's easier, have a look at the code below and adapt it to your situation:
$array = [1, 5, 6, 12];
$wantToRemove = 5;
$key = array_search($wantToRemove, $array);
unset($array[$key]);
var_dump($array);
You can format your $_SESSION['shopitems'] like this :
$_SESSION['shopitems'] = array (
"item_id" => "item_info",
"item2_id" => "item2_info",
...
)
and do unset($_SESSION['shopitems'][$_GET['remove']]).
Your code could be :
if (isset($_GET['remove']) && isset($_SESSION['shopitems']))
if (isset($_SESSION['shopitems'][$_GET['remove']]))
unset($_SESSION['shopitems'][$_GET['remove']])

Arrays inside array to hold filenames

This is for the front page of a website, which is supposed to display the newest/latest post at the very top, as you scroll down and goto the next pages, the posts get older.
There is a folder the contains lots of ini files with only numbers in the names. What i'm trying to do is load all the posts names (and only names - not their contents) into an array then sort those out to other arrays. I thought maybe using a multidimensional array would be a good idea. For example (if im understanding this right), $usePage[1][2] would have the number of the second post on page one. Is even the best way to do this?
Here is the relevant bit of code:
$ppp = 4;
$totalposts = 0;
$posts = array();
foreach (scandir($postsLoc) as $file) {
if (is_file($postsLoc . "/" . $file)) {
$totalposts++;
array_push($posts, $file);
}
}
natsort($posts);
array_values($posts);
$posts = array_reverse($posts);
print_r($posts);
$currPage = -;
$usePage = array(array());
$done = 0;
for ($i = $totalposts; $i != 0; $i--){
if ($done >= $ppp){
//Next page
$currPage++;
$done = 0;
$usePage[$currPage] = array();
}
$done++;
array_push($usePage[$currPage][$done], $i);
}
print_r($usePage);
So far, I've managed to confuse myself.
Thanks for any help in advance!
the below code results in a multi dimenstional $postsInPage array, the first dimension being the page ref, the second being the posts for that page. You should then be able to use this array pull out the relevant posts dependant on your pageId:
Array
(
[1] => Array
(
[0] => .
[1] => ..
[2] => email_20131212_2c7a6.html
[3] => email_20131212_98831.html
)
[2] => Array
(
[0] => errFile_20140110_940ad.txt
[1] => errFile_20140110_2021a.txt
[2] => errFile_20140110_2591c.txt
[3] => errFile_20140110_43280.txt
etc, etc. The code (haven't included the is_file check)
// load all the posts into an array:
$allPosts = array();
foreach (scandir("temp") as $file) {
$allPosts[] = $file;
}
//sort the array (am making an assumption that $file structure will natsort sensibly
natsort($allPosts);
$allPosts = array_values($allPosts);
//split into posts per page.
$ppp = 4;
$pageId = 1;
$totalposts = 1;
$postsInPage = array();
foreach ($allPosts as $post) {
$postsInPage[$pageId][] = $post;
if (($totalposts % $ppp) == 0) { //i.e. 4 per page
$pageId++;
}
$totalposts++;
}

Unable to change session variables in zend .. is the approach wrong?

Here are the steps that i have followed till now :
Firstly i have initialized the namespace for my session
$guest_events = new Zend_Session_Namespace('guest_events');
then added an array to the session
$guest_events-> events = array();
then i added some events to the array.
which looks like :
Array
(
[amount_0] => 1
[event_id_0] => 69
[event_title_0] => Sunday Collection
[amount_1] => 11
[event_id_1] => 78
[event_title_1] => Test event
)
Now in my another controller when i try to implement edit amount functionality through ajax :
$event_id = $this-> getRequest()-> getParam('event_id');
$edit_amount = $this-> getRequest()-> getParam('edit_amount');
$event_title = $this-> getRequest() -> getParam('event_title');
$guest_events = new Zend_Session_Namespace('guest_events');
$event_array = $guest_events-> events;
for ($i = 0; $i < 5; $i ++)
{
if (array_key_exists('event_id_'.$i, $event_array))
{
if ($event_array['event_id_'.$i]==$event_id && $event_array['event_title_'.$i]==$event_title)
{
// unset the amount and replace with new one
unset($guest_events-> events-> amount_0);
$guest_events-> events-> amount_0 = $edit_amount;
}
}
}
i have tried everything but the session variables remain unchanged .. can anyone tell why ?? :(
If the element events is an array in your Zend_Session_Namespace object, then you should be setting it like this:
$guest_events-> events['amount_0'] = $edit_amount;
instead of like:
$guest_events-> events-> amount_0 = $edit_amount;
Also, since you are in a loop which finds the correct numeric value, I think it should actually be:
$guest_events-> events['amount_' . $i] = $edit_amount;
I figured out the problem .. it isn't going inside the inner if loop .. i.e :
if ($event_array['event_id_'.$i]==$event_id && $event_array['event_title_'.$i]==$event_title)
{
// unset the amount and replace with new one
unset($guest_events-> events-> amount_0);
$guest_events-> events-> amount_0 = $edit_amount;
}
still cant figure out why this is happening though :/

Categories