Undefined index: page in - php

Ok I have the above error on my page, I am using PHP 5.3 for the first time, and have used this code before but never had this notice, so I was hoping for some guidance. I have looked at some questions but when I try to apply the solution to my bit of code it doesn't seem to work.
This code is a PHP pagination script from paper mashup and so if I can find the answer it may help anybody else who is also using this code and experiences the same problem.
the piece of code which is generating the notice is this -
$page = mysql_escape_string($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
From what I have read it was suggested to add isset and so changed the code to look like it does below, however i still get the same error.
$page = mysql_real_escape_string($_GET['page']);
if(!isset($page)){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
Any advice would be appreciated.
Thanks
Stan

The 'undefined index' error is basically telling you that you tried to get something from an array using an index for which there is no matching element.
In this case, the problem is in the line above your isset() call. The index 'page' is not defined in your $_GET array. So you need to first check if $_GET['page'] is set:
if (isset($_GET['page'])) {
$page = mysql_real_escape_string($_GET['page']);
// do more stuff
}

i got some issue.. this is the best and shortest solution i've got..
$page = (isset($_GET["page"]) ? $_GET["page"]:$config["per_page"] ='');
or
$page = (isset($_GET['page'])) ? $_GET['page'] : 0;

The error is on your first line
do
$page = isset($_GET['page']) ? mysql_real_escape_string($_GET['page']) : 0;

In your code you check wether the page is not set, and then use the page, resulting in the same notice. Simply remote the exclamation mark. Try this:
$page = mysql_real_escape_string($_GET['page']);
if(isset($page)){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}

Although I can't see it in your code, I would be willing to bet that you have an empty variable $_GET['page'] in your code. When you do a pagination, you need to keep appending the variable to the anchor tags if you are using the <a href="somePage.php?page=4 style of link.
Check your links to make sure that you keep passing it back all the time.
The error message undefined index appears when you try to access an array element that doesn't exist - and in this case, it is almost certainly the $_GET array.

Hope this will help
<?php
# default page
$default = 'home.php';
# set document root path
$base = $_SERVER['DOCUMENT_ROOT'].'/redirect/';
# list of all site pages + the id they will be called by
$pages = array('home' => 'home.php','about' => 'about.php','contact' => 'contact.php');
if (isset($_GET['page'])) {
$page = mysql_real_escape_string($_GET['page']);
if(array_key_exists($_GET['page'], $pages))
{
foreach($pages as $pageid => $pagename) {
if($_GET['page'] == $pageid && file_exists($base.$pagename))
{
/* if somebody's making a request for ?page=xxx and
the page exists in the $pages array, we display it
checking first it also exists as a page on the server */
include $base.$pagename;
}
} // end foreach
}
else {
/* if the page isn't listed in $pages, or there's no ?page=xxx request
we show the default page, again we'll also just make sure it exists as a file
on the server */
if(file_exists($base.$default)) include $base.$default;
}
} else {
header ("Location: index.php?page=home");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Website</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<body>
<div style="height:50px;border:1px solid #000;margin-bottom:10px">
</div>
<div style="float:left;width:15%;border:1px solid #000">
<ul style="margin-left:10px;list-style-type:none">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<div style="float:right;width:80%;border:1px solid #000">
<div style="padding:4px">
<!-- content here -->
</div>
</div>
</body>
</html>

You should do it like this
if(isset($_GET['page']){
$page = mysql_real_escape_string($_GET['page']);
if(!isset($page)){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
}
Undefined index: page refers to some array specific error. In your code the array with index value page is $_GET so it should be the first line of your code that needs some protection.

Related

Display static items according to page accessed, in PHP

I need to include some js, css type items in specific pages.
So far I've done the following:
define("DIR_ADMIN", "admin");
function fusion($location, $page, $type) {
$dirAdmin = DIRECTORY_SEPARATOR.DIR_ADMIN;
$change = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $location);
$changed = ucfirst($change);
$result = $dirAdmin.$changed;
if($type=='js'){
echo "<script src='$result'></script>\n";
} elseif($type=='css'){
echo "<link rel='stylesheet' href='$result' />";
} elseif($type=='favicon'){
echo "<link rel='shortcut icon' href='$result' />";
} elseif($type=='logo'){
echo "<img src='$result' alt='logo'>";
} else {
echo $result;
}
}
In HTML I called the function like this:
<?php fusion("/assets/vendors/js/vendor.bundle.base.js", "clients", "js"); ?>
First is the file URL, then the page, and finally the file type.
What I'm not able to come up with is the part that receives the value $page.
I created a routing system in php, so all files are accessed like this: index.php?page=clients, except in the case of the homepage which is just index.php.
I need that when the value of $page is set for example with clients it should load all items that have this same when the clients route is accessed.
In some cases the route may have another word attached, for example: index.php?page=clients-add, in which case it should check if there is only the word clients in $_GET.
And if I set the value of $page to all, it should display on all pages. How can I do this?
Within your fusion function you need to pick up which page you're on and then including the displaying of content after that.
Use this snippet to help dictate the page you're on.
$curr_page = "home";
if ( isset( $_GET["page"] ) ) {
$curr_page = $_GET["page"];
}
if ( $page == "all" || $page == $curr_page ) {
//echo items here
}

PHP include() wiping rest of HTML document?

So I have a simple html page that looks like this.
<html>
<head>
<?php include("scripts/header.php"); ?>
<title>Directory</title>
</head>
<body>
<?php include("scripts/navbar.php"); ?>
<div id="phd">
<span id="ph">DIRECTORY</span>
<div id="dir">
<?php include("scripts/autodir.php"); ?>
</div>
</div>
<!--Footer Below-->
<?php include("scripts/footer.php"); ?>
<!--End Footer-->
</body>
</html>
Now, the problem is, when I load the page, it's all sorts of messed up. Viewing the page source code reveals that everything after <div id="dir"> is COMPLETELY GONE. The file ends there. There is no included script, no </div>'s, footer, or even </body>, </html>. But it's not spitting out any errors whatsoever. Just erasing the document from the include onward without any reason myself or my buddies can figure out. None of us have ever experienced this kind of strange behavior.
The script being called in question is a script that will fetch picture files from the server (that I've uploaded, not users) and spit out links to the appropriate page in the archive automatically upon page load because having to edit the Directory page every time I upload a new image is a real hassle.
The code in question is below:
<?php
//Define how many pages in each chapter.
//And define all the chapters like this.
//const CHAPTER_1 = 13; etc.
const CHAPTER_1 = 2; //2 for test purposes only.
//+-------------------------------------------------------+//
//| DON'T EDIT BELOW THIS LINE!!! |//
//+-------------------------------------------------------+//
//Defining this function for later. Thanks to an anon on php.net for this!
//This will allow me to get the constants with the $prefix prefix. In this
//case all the chapters will be defined with "CHAPTER_x" so using the prefix
//'CHAPTER' in the function will return all the chapter constants ONLY.
function returnConstants ($prefix) {
foreach (get_defined_constants() as $key=>$value) {
if (substr($key,0,strlen($prefix))==$prefix) {
$dump[$key] = $value;
}
}
if(empty($dump)) {
return "Error: No Constants found with prefix '" . $prefix . "'";
}
else {
return $dump;
}
}
//---------------------------------------------------------//
$archiveDir = "public_html/archive";
$files = array_diff(scandir($archiveDir), array("..", "."));
//This SHOULD populate the array in order, for example:
//$files[0]='20131125.png', $files[1]='20131126.png', etc.
//---------------------------------------------------------//
$pages = array();
foreach ($files as $file) {
//This parses through the files and takes only .png files to put in $pages.
$parts = pathinfo($file);
if ($parts['extension'] == "png") {
$pages[] = $file;
}
unset($parts);
}
//Now that we have our pages, let's assign the links to them.
$totalPages = count($pages);
$pageNums = array();
foreach ($pages as $page) {
//This will be used to populate the page numbers for the links.
//e.g. "<a href='archive.php?p=$pageNum'></a>"
for($i=1; $i<=$totalPages; $i++) {
$pageNums[] = $i;
}
//This SHOULD set the $pageNum array to be something like:
//$pageNum[0] = 1, $pageNum[1] = 2, etc.
}
$linkText = array();
$archiveLinks = array();
foreach ($pageNums as $pageNum) {
//This is going to cycle through each page number and
//check how to display them.
if ($totalPages < 10) {
$linkText[] = $pageNum;
}
elseif ($totalPages < 100) {
$linkText[] = "0" . $pageNum;
}
else {
$linkText[] = "00" . $pageNum;
}
}
//So, now we have the page numbers and the link text.
//Let's plug everything into a link array.
for ($i=0; $i<$totalPages; $i++) {
$archiveLinks[] = "<a href='archive.php?p=" . $pageNums[$i] . "'>" . $linkText[$i] . " " . "</a>";
//Should output: <a href= 'archive.php?p=1'>01 </a>
//as an example, of course.
}
//And now for the fun part. Let's take the links and display them.
//Making sure to automatically assign the pages to their respective chapters!
//I've tested the below using given values (instead of fetching stuff)
//and it worked fine. So I doubt this is causing it, but I kept it just in case.
$rawChapters = returnConstants('CHAPTER');
$chapters = array_values($rawChapters);
$totalChapters = count($chapters);
$chapterTitles = array();
for ($i=1; $i<=$totalChapters; $i++) {
$chapterTitles[] = "<h4>Chapter " . $i . ":</h4><p>";
echo $chapterTitles[($i-1)];
for ($j=1; $j<=$chapters[($i-1)]; $j++) {
echo array_shift($archiveLinks[($j-1)]);
}
echo "</p>"; //added to test if this was causing the deletion
}
?>
What is causing the remainder of the document to vanish like that? EDIT: Two silly syntax errors were causing this, and have been fixed in the above code! However, the links aren't being displayed at all? Please note that I am pretty new to php and I do not expect my code to be the most efficient (I just want the darn thing to work!).
Addendum: if you deem to rewrite the code (instead of simply fixing error(s)) to be the preferred course of action, please do explain what the code is doing, as I do not like using code I do not understand. Thanks!
Without having access to any of the rest of the code or data-structures I can see 2 syntax errors...
Line 45:
foreach ($pages = $page) {
Should be:
foreach ($pages as $page) {
Line 88:
echo array_shift($archiveLinks[($j-1)];
Is missing a bracket:
echo array_shift($archiveLinks[($j-1)]);
Important...
In order to ensure that you can find these kinds of errors yourself, you need to ensure that the error reporting is switched on to a level that means these get shown to you, or learn where your logs are and how to read them.
See the documentation on php.net here:
http://php.net/manual/en/function.error-reporting.php
IMO all development servers should have the highest level of error reporting switched on by default so that you never miss an error, warning or notice. It just makes your job a whole lot easier.
Documentation on setting up at runtime can be found here:
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
There is an error in scripts/autodir.php this file. Everything up to that point works fine, so this is where the problem starts.
Also you mostlikely have errors hidden as Chen Asraf mentioned, so turn on the errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Just put that at the top of the php file.

Include CSS/JS only when necessary

My menu system all comes from the index file. A simplified example:
#index.php
...
<div id="container">
include($inc_file) //index.php?site=news will show news.php
</div>
...
My question is: how can I only include some js-files and css-files when they are needed. For example, I have a file with a slider. I would like only to include the js/css-files related to the slider when visiting that page.
I know that I can make if/else clauses, but I find that a bit ineffective. Is it possible to place a session containing an array with all the files that should be included on the frontpage?
Here is what I would use:
<?php
$path_parts = pathinfo(__FILE__);
$filename = $path_parts['filename'];
if ($filename === "somepage") {
?>
<script src=""></script>
<link ...>
<?php } ?>
I would just have a preset array for each page with an array of css/js files it would need to include.
eg.
settings.php
<?php
$pages = array();
$pages['index'] = array(
"css" => array("main.css","index.css"),
"js" => array("jquery.min.js","someotherjs.js")
);
$pages["about"] = array(
...
);
index.php
<?php
include('settings.php');
?>
...
<head>
<?php
foreach($pages['index']['css'] as $css)
echo "<link rel='stylesheet' type='text/css' href='$css'>";
?>
...
<?php
foreach($pages['index']['js'] as $js)
echo "<script src='$js'></script>";
</body>
</head>
This may not be the answer you were expecting but did you know that the browser does not download css or js files that have not changed since the last time they were downloaded. They are cached on the client PC and only refreshed if the copy on the server has changed.
Theerfore you may not need to be so selective about what you load on each page as it probably wont cause a fresh download of a css or js file.
Prepare an object where you can add style or js files as you need, here a little example.
class head {
private styles = array();
private scripts = array();
public function __construct() {}
// add script in page
public function add_script(filepath){
array_push($this->scripts, filepath);
}
// add style in page
public function add_style(filepath){
array_push($this->styles, filepath);
}
// get html <link> for styles
public function get_styles(){
$html = '';
$len = count($this->styles);
for($i=0; $i < $len; $i++){
$html .='<link rel="stylesheet" type="text/css" href="'.$this->styles[$i].'">';
}
return $html;
}
// get html <script> for scripts
public function get_scripts(){
$html = '';
$len = count($this->scripts);
for($i=0; $i < $len; $i++){
$html .='<script type="text/javascript" src="'.$this->scripts[$i].'"></script>';
}
return $html;
}
}
// destruct ...
in your controller :
require('/class/head.php');
$head = new head();
$head->add_style('/css/myStyle.css');
$head->add_script('/js/myScript.js');
in head
<?php echo $head->get_styles(); ?>
<?php echo $head->get_scripts(); ?>

Colour Extract Script - ForEach Error

So I downloaded and edited a script off the internet to pull an image and find out the hex values it contains and their percentages:
The script is here:
<?php
$delta = 5;
$reduce_brightness = true;
$reduce_gradients = true;
$num_results = 5;
include_once("colors.inc.php");
$ex=new GetMostCommonColors();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Colour Verification</title>
</head>
<body>
<div id="wrap">
<img src="http://www.image.come/image.png" alt="test image" />
<?php
$colors=$ex->Get_Color("http://www.image.come/image.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
$success = true;
foreach ( $colors as $hex => $count ) {
if ($hex !== 'e6af23') {$success = false; }
if ($hex == 'e6af23' && $count > 0.05) {$success = true; break;}
}
if ($success == true) { echo "This is the correct colour. Success!"; } else { echo "This is NOT the correct colour. Failure!"; }
?>
</div>
</body>
</html>
Here is a pastebin link to the file colors.inc.php
http://pastebin.com/phUe5Pad
Now the script works absolutely fine if I use an image that is on the server, eg use /image.png in the Get_Color function. However, if I try and use an image from another website including a http://www.site.com/image.png then the script no longer works and this error appears:
Warning: Invalid argument supplied for foreach() in ... on line 22
Is anyone able to see a way that I would be able to hotlink to images because this was the whole point of using the script!
You must download a file to the server and pass its full filename to the method Get_Color($img) as $img parameter.
So, you need to investigate another SO question: Download File to server from URL
The error indicates that the value returned by Get_Color is not a valid object that can be iterated on, probably not a collection. You need to know how the Get_Color works internally and what is returned when it doesn't get what it wants.
In the mean-time, you can download [with PHP] the image from the external url into your site, and into the required folder and read the image from there.
$image = "http://www.image.come/image.png";
download($image, 'folderName'); //your custom function
dnld_image_name = getNameOfImage();
$colors=$ex->Get_Color("/foldername/dnld_image_name.png");
By the way, did you confirm that the image url was correct?

Execute PHP on clicking a link

My website's pages are (or will) all be identical, except for the content of the #main div. So I was thinking in the <head> I could do <?php $page = "home.html"?>, where home.html is the bare contents (not a full html page - no <html>, <head> etc.) of the main div for the home page. So then inside <div id="main"> and </div> I could have <?php include($page);?>. Then the reason I'm asking this question is I want to change $page when a link is clicked. How can I do this? Thanks.
You could make the links be like this:
Other Page
Then also in the top of the page where you set page to the value of $_GET['page']
<?php
if (isset($_GET['page']))
{
$page = $_GET['page'] . ".html";
} else {
$page = "home.html";
}
?>
Your link has to be like:
home.php?page=test
You will get the value in your page variable like this:
if(isset($_GET['page']))
$page = $_GET['page'].'.html';
else
$page = 'index.html';
You can do something like:
http://yoursite.com/index.php?page=test.html or http://yoursite.com/index.php?page=test (and append .html later).
For instance:
<?php $page = preg_replace('/[^A-Za-z]/','', $_GET['page']);
$path = 'pages/'.$page.'.html'
if (file_exists($path)){ $output = file_get_contents($path); }
else { header("HTTP/1.0 404 Not Found");
$output = file_get_contents('pages/404.html'); }
?>
(Putting the rest of your file after the php, for the 404 header to work.)
Then, you also can use apache rewrites:
Rewrite Engine On
Rewrite Rule ^([A-Za-z]+)$ index.php?page=$1
Then use links like http://mysite.com/page_name
Then in the main div:
<?php echo $output; ?>

Categories