Hi im making a CMS with responsive HTML5 front
this part of the code retrieves the relevant information from url so that the relevant information can be displayed
this is the notice i am getting
Notice: Undefined index: pid in /home/hj016/public_html/SSTW/index.php on line 7
require_once "script/connect_to_mysql.php";
// Determine which page ID to use in our query below
if (!$_GET['pid']) {
$pageid = '1';
} else {
$pageid = ereg_replace("[^0-9]", "", $_GET['pid']);
// filter everything but numbers for security
}
is there any way to hide this ??
try
if (!isset($_GET['pid'])) {
basically you are calling for an undefined index even though you are trying to check if its not defined. The safe way to do this is with isset as it wont error if its not defined, because your checking existence not value.
On a production server you would generally hide notices anyway. But checking using isset($_GET['pid']) would be the preferred approach.
require_once "script/connect_to_mysql.php";
// Determine which page ID to use in our query below
if (!isset($_GET['pid']) || empty($_GET['pid'])) {
$pageid = '1';
} else {
$pageid = ereg_replace("[^0-9]", "", $_GET['pid']);
// filter everything but numbers for security
}
hows that? will make sure its set and not set to just like pid=
Related
I wasn't able to find a solid work-a-round yet for it so I thought I just might ask here.
My error.log says for a good reason
[error] [client xxx.xxx.xxx.xxx] PHP Notice: Undefined index: Variablename
Till now I got rid of it with using a if statement around it like
if (isset($var)) {
if ($var ... ) { ... }
}
But now I got a lil problem so I can't use this "wrap-around" like above easily.
the check_login(...) function will write $_SESSION Variables like ['loginattempts'] or ['captchaattempts'] - now I want to let the login disappear if those attemps reach a specified amount. Like
if ($_SESSION['loginatt'] < x && $_SESSION['capatt'] < x) { echo 'login form...';}
If I would wrap a check if the variable is set around it - the login wouldn't appear if those variables are not set.
Possible work-a-rounds could be
if (!isset($var)) {echo 'login form ...';}
else {echo 'login form...';}
but that would mean I would have to have a duplicate login form in my code
I know could also just change this echo 'login form ...' into a requice_once 'include/loginform.php' - but there would be still a duplicate entry for this require_once command.
I could also set a $testvar like
if (isset($var)) {
if ($var > x) {
echo 'acc. blocked;
$testvar = 0;
}
else {
$testvar = 1;
}
if ($testvar < 1) {
echo 'login form...';
}
So are there any other ways as those ?
If not which way you would suggest to take to keep the code as it should be for "good programming" ?
Any statements are welcome, thanks for helping out
Kris
In my experience, it's always a good idea to output all errors during development and to always have initialized values. It can get rid of some bugs as you will always have a default value to fall back on.
An easy way to fix your problem is to use another variable and to add your $_SESSION variables only if they exist. For instance:
$login_attempts = 0;
if (isset($_SESSION['loginattempts'])) {
$login_attempts = $_SESSION['loginattempts'];
}
Alternatively, a ternary expression is also possible for compactness, although with the long loginattempts index this looks a little harsh, in my opinion.
$login_attempts = (isset($_SESSION['loginattempts'])) ? $_SESSION['loginattempts'] : 0;
Start defining indexes!
you can directly check if session vars are set or not
if (isset ($_SESSION['loginatt'])) { /* action here */ }
if you want to reduce redundancy in use of login form string
you can declare it under a variable, like
$loginform = '<form action="" ...>';
$loginform .= '<input type='"...>';
and echo it anywhere you want.
How to pass an array from one file to another using include using PHP language?
I have one file with some language array(language/langen.php):
global $lang;
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
In other file I have:
include base_url().'language/lang'.$_COOKIE['lang'].'.php';
var_dump($lang);
*(My mistake by coping code - true is var_dump($lang))*
But it shows me an error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: lang
How to solve this problem and what did I do wrong?
First of all:
You should never use cookie value directly in include statement - its pretty easy to make fake cookie and mess up in your application.
I suppose you just don't have cookie with name lang or variable $lang has never been initialized before.
To check if cookie exists and is in correct format you can do like that:
// set default lang code
$langCode = 'en';
// check if cookie exists and if contains string build from 2 characters from range a-z
// check also if file exists
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
include base_url().'language/lang'.$langCode.'.php';
in included file you should check if variable $lang exists
if (!isset($lang)) $lang = array();
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
also I think using global here is pointless as from your example it looks like its the same scope.
anyway for me much cleaner solution would be:
// first_file.php
$langCode = 'en';
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
$lang = include base_url().'language/lang'.$langCode.'.php';
// langen.php
return array(
'Date' => 'Date',
'Here' => 'Here',
);
EDIT
One more thing - If base_url() is returning web URL (like http://example.com...) then it is also wrong (and also can cause problem as langen.php will contain at least Notice message when included this way) - should be included with valid file path
Shouldn't it be?
include base_url().'language/lang'.$_COOKIE['lang']['Here'].'.php';
Or else it would just return array()
First of all, I don't see the point of var-dumping variable $data, if there is no such thing in code you posted. If you have a cookie called "lang" in your browser, then you should be fine. You could always check this by
var_dump($GLOBALS['lang']);
in your code. It should print the array of values from your lang*.php file.
I use the latest code igniter (2.0.3) and php-active 0.0.1.
All are working fine except save();
Code:
if($_POST)
{
$entry= Customers::find_by_routeid('4');
$entry->routeid=5;
$entry->save();
}
Here's my problem: for some reason that I cannot understand the above code does not work, but if I take the code out of if ($_POST), it works fine.
What I am doing wrong?
EDIT:
Thanks Damien Pirsy $this->input->post() does the trick, but when I uncomment the comments in the code the problems returns.
The code now is:
if($this->input->post())
{
$id = $this->input->post('id');
$oldRoute = $this->input->post('oldRoute');
$newRoute = $this->input->post('newRoute');
$entry= Customers::find_by_routeid($this->input->post('oldRoute'));
$entry->routeid=$this->input->post('newRoute');
$entry->save();
/*
if($oldRoute<$newRoute)
{
for ($i=$newRoute; $i>$oldRoute; $i--)
{
$element = Customers::find_by_routeid($i);
echo $element->routeid -= 1;
$element->save();
}
}
*/
}
The elements new IDs ($element->routeid -= 1;) are echoing right, but I have the same problem as in the beginning and neither of two saves work.
You didn't provide much details or debug info, so I'll just guess: try using the CI's native post handler instead. You should have var_dump()ed the $_POST array, see if isset() or not, also, since you're using it as a condition
if($this->input->post())
{
//...
}
UPDATE:
Since we're talking about Post variables, don't assume they're exactly as you want them. Keep in mind that $this->input->post('field') returns FALSE when the index is not present; that might well brake your if condition.
Assuming you need numbers to do this, you can do a check like
if($this->input->post('newRoute') AND is_numeric($this->input->post('newRoute'))
{
$newRoute = $this->input->post('newRoute');
}
else
{
// give it a default value, or raise an error, for example. If you need this
// variables, and need them to be numbers, you cannot go on in case these
// conditions are not met, right?
}
And the same for $oldRoute.
And yeah, OK, maybe you can write a cleaner code than mine, but you get the picture ;)
In my code i am trying to store a variable between two pages but i either get a string return "images" or 0... or nothing- tried casting it.. echoing in on one page works and displays correct number but as soon as you click through the view to the next page- its lost- i tried turning on cs_sessions in the db and made no difference
<?php
public function carconfirm($car_id = '')
{
if(empty($car_id))
{
redirect('welcome');
}
$this->load->model('mcars');
$car = $this->mcars->getCar($car_id);
$data['car'] = $car->row_array();
$car_id = (int) $car_id;
$this->session->set_userdata('flappy', $car_id);
echo $car_id;
//insert details
//display details
$this->load->view('phps/carconfirm',$data);
}
function confirm()
{
//get vars
$time_slot = $this->session->userdata('slot');
$person_id = $this->session->userdata('person_id');
$car_id = $this->session->userdata('flappy');
$insert_array = array( 'slot'=> $time_slot ,
'car'=> $car_id,
'person_id'=> $person_id
);
print_r($insert_array);
$this->load->model('mbooking');
$result = $this->mbooking->addbooking($insert_array);
if($result)
{
redirect('welcome/options');
}
}
?>
the variable I'm losing is flappy- i changed the name to see if that was the problem
Finally, I fixed this. Using this answer in SO too : codeigniter setting session variable with a variable not working, I scan my js/css for missing resources. Turn out that, my thickbox.js refer to loadingAnimation.gif in, yes, images folder. That's where the images come. Having fix the missing file, the sesion variabel working just fine.
Not sure, why CI replace (maybe) last added session variabel using this, but maybe it's because CI is not using $_SESSION global variabel. CMIIW. I use this article as a hint : http://outraider.com/frameworks/why-your-session-variables-fail-in-codeigniter-how-to-fix-them/
this is my front controller
$pages = array("matches", "boards", "search", "articles", "interviews", "userlist", "teams", "servers", "awards", "gallery", "qids");
if (!$_SERVER['QUERY_STRING']) include('home_en.php');
elseif (isset($_GET['matchid'])) include('matchid.php');
elseif (isset($_GET['boardid'])) include('boardid.php');
elseif (isset($_GET['articleid'])) include('articleid.php');
elseif (isset($_GET['interviewid'])) include('interviewid.php');
elseif (isset($_GET['userid'])) include('profi.php');
elseif (isset($_GET['teamid'])) include('teamid.php');
elseif (isset($_GET['serverid'])) include('serverid.php');
elseif (isset($_GET['awardid'])) include('awardid.php');
elseif (isset($_GET['galleryid'])) include('galleryid.php');
elseif (isset($_GET['threadid'])) include('threadid.php');
elseif (isset($_GET['blogid'])) include('blogid.php');
..
elseif (in_array($_GET['content'], $pages)) include($_GET['content']);
else echo "File not found =(";
could i somehow add the identifiers to the array too? but i want the pages as index.php?matchid=9438 and for regular pages: index.php?content=matches
would really aprricate some ideas
thanks!
My Suggestion, From My Comment is this:
In order to check what type of id it is, you should use two $_GET parameters. One is the type (match, award, server, etc), one is the ID. That way you don't have to check for 500 different $_GET parameters, just the value of 2. Much more standardized.
Second, you want to make all of it under 1 file for the ID showing.
In the spirit of writing less code, not more, it would be relatively easy to change the SQL statement to grab the record based on if $_GET['type'] was match, award, team, etc. This is of course given that they will probably look the same. If they don't, instead of writing new code to grab each type, instead write code to display it differently
All Variables in this code much be validated/sanatized beforehand.
// First Get the Type
$type = $_GET['type'];
// Then the ID
$id = $_GET['id'];
// SANITIZE YOUR DATA. Replace this with your sanitization.
die("SANITIZE YOUR DATA HERE");
// Get Data Here
$sql = "SELECT * FROM table WHERE type=".$type." AND id=".$id;
$data = mysql_query($sql);
// Next, Include a template based on the data.
// Global the variable so it can be used in the file
Global $data;
include($type."-template.php");
I agree with Tom -- you should look into using a framework such as Zend, Cake, Symfony, Kohana, CodeIgniter, ez-Components, or Seagull. The advantage of using a framework is that they have already solved a lot of issues for you, including:
1) How to structure your code
2) How to interpret pretty urls (i.e. /x/1/y/2 instead of ?x=1&y=2)
3) Where to put certain types of code (html, php, configs, etc)
4) How to fix something you can't figure out (because these frameworks have communities)
and much much more...
That being said, maybe you don't want all the overhead of using a framework (it does require you to learn a lot). In that case, I recommend Rasmus Lerdorf's "No Framework PHP Framework". Rasmus is the creator of PHP, so you know he knows his stuff.
Lastly, to answer your actual question, here's how I would do it:
could i somehow add the identifiers to the array too?
i want the pages as index.php?matchid=9438
and for regular pages: index.php?content=matches
Sure, but yes, as Chacha102 said, you will need 2 parameters: $area (page) and $id.
Example: index.php?area=articles&id=2345
Then you can re-organize & simplify your 'front controller' this way:
/index.php
/areas/articles.php
/areas/boards.php
etc.
Instead of naming the templates articleid.php, just call it articles.php -- this way your area name also tells you which template to use.
$valid_areas = array("matches", "boards", "search", "articles",
"interviews", "userlist", "teams", "servers",
"awards", "gallery", "qids");
$area = strtolower(trim($_REQUEST['area'])); //if you are not posting any forms, use $_GET instead
$id = (int)$_REQUEST['id']; //if you are not posting any forms, use $_GET instead
if(!$id)
{
include('home_en.php');
}
if(!in_array($area), $valid_areas))
{
echo 'Sorry, the area you have requested does not exist: '.$area;
exit();
}
else
{
$template = '/templates/'.$area.'.php';
if(!file_exists($template))
{
echo 'Sorry, the file you have requested does not exist: '.$area.' '.$id);
}
else
{
include($template);
}
}
It might help to go ahead and use a framework such as Zend:
http://framework.zend.com/
You could do this:
<?php
$controllerDefault = 'home';
function sanitize($str)
{
return str_replace(array('.', '/', '\\'), '', $str);
}
//Prevent of Remote File Inclusion
$controller = sanitize($_GET['controller']);
$id = intval($_GET['id']);
if (empty($controller))
{
$controller = $controllerDefault;
}
if (!empty($id))
{
$controller .= 'id';
}
$controllerFile = $controller . '.php';
if (!file_exists($controllerFile)
|| $controller == 'index') //for not recursive index.php include :)
{
exit('Controller "'.$controllerFile.'" not exists');
}
include($controllerFile);
?>
Using this code you can use your application like:
http://yoursite.com/index.php //include('home.php')
http://yoursite.com/index.php?id=285230 //include('homeid.php')
http://yoursite.com/index.php?controller=matches //include('matches.php')
http://yoursite.com/index.php?controller=matches&id=28410 //include('matchesid.php')
http://yoursite.com/index.php?controller=notexists //ERROR! Controller "notexists" not exists
http://yoursite.com/index.php?controller=../../etc/passwd //ERROR! Controller "etcpasswd" not exists
I hope you like it
PD: the code is not tested, but I hope you catch my idea