I have sth like this:
<?php
$body = $_GET["body"];
if ($body=="")
{
include("includes/desktop.php");
}
else
{
if (is_file("includes/$body.php"))
{
include("includes/$body.php");
}
else
{
include("includes/desktop.php");
}
}
?>
How to make that this notice will disappear?
It happens only when $_GET["body"] is empty.
Notice: Undefined index: body in C:\wamp\www\admin\index.php on line
106
change
$body = $_GET["body"];
To
$body = isset($_GET["body"]) ? $_GET["body"] : '';
You can find almost all symbols and operators in php here
It's happening because there is no index body in the superglobal $_GET array. In other words, you're not passing $_GET['body'].
Instead use:
if (isset($_GET['body']) && $_GET['body']) {
That checks for both the index and a meaningful (non-falsy) value.
Try
if (!isset($_GET['body']) || empty($_GET['body'])) {
include("includes/desktop.php");
} else {
...
}
http://www.php.net/isset
On a side note: You should never trust user input. Directly passing the body GET parameter to your include() call allows a malicious user to include files you never intended to load.
It is warning you that body is not sent via $_GET. You need to do something like this
<?php
if (isset($_GET["body"])) {
$body = $_GET["body"];
if ($body=="")
{
include("includes/desktop.php");
}
else
{
if (is_file("includes/$body.php"))
{
include("includes/$body.php");
}
else
{
include("includes/desktop.php");
}
}
}
?>
Related
I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.
I have this code:
print_r(array_keys($variables));
if (array_key_exists('form', $variables)) {
print "YES!";
}
$imgs = $variables['form']['field_images'];
It's a part of the code that I use to theme a form page in Drupal. YES is printed out, however, drupal reports undefined index for that. Thanks for your generous help
$variables['form'] does exist, but $variables['form']['field_images] probably not. That's why you get the notice about undefined index.
So you should make sure that the subkey also exists before you are calling it.
as an example implemenation of Ikke`s answer:
if ( !array_key_exists('form', $variables) ) {
echo 'missing parameter form';
}
else if ( !array_key_exists('field_images', $variables['form']) ) {
echo 'missing parameter field_images';
}
else {
$imgs = $variables['form']['field_images'];
}
Try this:-
PHP throws the notice. You can add an isset() or !empty() check to avoid the error, like such:
if(isset($variables)) ) && !empty($variables)) ))
{
if (array_key_exists('form', $variables)) {
print "YES!";
}
$imgs = $variables['form']['field_images'];
}
ok so im here trying to practice some php (im a super beginner) and so long story short,
i put form elements in one page, passed it to the process php.
Im just messing aound trying to see what ive learned so far. i dont get any errors, just dont understand why it doesnt work.
<?php
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
$response = array("please enter correct information","hmm" . "$yourname");
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
?>
<?php nametest(); ?>
what im trying to do is, that if the name isnt set, to make a variable equal to a value inside response.
Try
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1];
}
return $yourname;
}
print nametest();
The function needs to return a value to be printed. I also noticed you have two ;; behind line 5.
Because you are assigning $yourname and $compname in the first two lines:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
UPDATE You can check if these are set in POST, and therefore not need to check them later:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
They will always be set, even if NULL or empty. So, your later calls to isset() will always be true.
Instead, you may check if they are empty with the empty() function:
UPDATE Not necessary according to corrections in comments. Your isset() should work.
// Check with empty()
// but still won't work properly. keep reading below...
function nametest() {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
However, there is another problem here of variable scope. The variables are not available inside the function unless you either pass them in as parameters or use the global keyword:
// $yourname is passed as a function argument.
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
Getting there... Now your function assigns $yourname, but it doesn't return or print any value. Add a return statement, and then you can echo out the result:
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
// Add a return statement
return $yourname;
}
// Now call the function, echo'ing its return value
echo nametest($yourname, $response);
Variable Scope is the biggest mistake here, your function can not 'see' the variables that you created outside of it, do this:
<?php
.
.
.
function nametest($yourname, $response) { // This creates two new variables that
// are visible only by this function
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1]; // Get rid of the extra semicolon
}
return $yourname; // This $yourname is only visible by this function so you
// need to send it's value back to the calling code
}
?>
<?php nametest($yourname, $response); ?> // This sends the values of the
// variables that you created at the
// top of this script
<h1><?php echo $GLOBALS['translate']['About'] ?></h1>
Notice: Undefined index: About in page.html on line 19
Is it possible to "catch" an undefined index so that I can create it (database lookup) & return it from my function and then perform echo ?
The easiest way to check if a value has been assigned is to use the isset method:
if(!isset($GLOBALS['translate']['About'])) {
$GLOBALS['translate']['About'] = "Assigned";
}
echo $GLOBALS['translate']['About'];
You can check if this particular index exists before you access it. See the manual on isset(). It's a bit clumsy as you have to write the variable name twice.
if( isset($GLOBALS['translate']['About']) )
echo $GLOBALS['translate']['About'];
You might also consider changing the error_reporting value for your production environment.
that wouldn't be the right thing to do. i would put effort into building the array properly. otherwise you can end up with 1000 db requests per page.
also, you should check the array before output, and maybe put a default value there:
<h1><?php echo isset($GLOBALS['translate']['About'])?$GLOBALS['translate']['About']:'default'; ?></h1>
try something like:
if ( !isset($GLOBALS['translate']['About']) )
{
$GLOBALS['translate']['About'] = get_the_data('About');
}
echo $GLOBALS['translate']['About'];
Yes. Use isset to determine if the index is defined and then, if it isn't, you can assign it a value.
if(!isset($GLOBALS['translate']['About'])) {
$GLOBALS['translate']['About'] = 'foo';
}
echo "<h1>" . $GLOBALS['translate']['About'] . "</h1>";
You need to define your custom error handler if you want to catch Undefined index
set_error_handler('exceptions_error_handler');
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
try{
}catch(Exception $e){
echo "message error";
}
I have an Elseif statement, which gets a template name and includes the template PHP file which contains a large array, it outputs the result on the page.
$template = str_replace("-","_","{$_GET['select']}");
if ($template == "cuatro"){
include("templates/cuatro.php");
echo $page_output;
} elseif ($template == "ohlittl"){
include("templates/ohlittl.php");
echo $page_output;
} else {
echo "Sorry, template not found.";
}
$page_output = "You've chosen $template_select[0].";
From there, I get a notice saying it couldn't find the $page_output variable.
Notice: Undefined variable: page_output in C:\ ... \template.php on line 10
It can find it if I put the variable in the included file though. But I'm trying to get this variable to remain on this page. How do I complete this?
You are defining $page_output after you are echoing it. At the time you call echo $page_output it doesn't exist yet.
Try:
$page_output = "You've chosen {$template_select[0]}.";
$template = str_replace("-","_","{$_GET['select']}");
if ($template == "cuatro"){
include("templates/cuatro.php");
echo $page_output;
} elseif ($template == "ohlittl"){
include(dirname(__FILE__) . "/templates/ohlittl.php");
echo $page_output;
} else {
echo "Sorry, template not found.";
}
Although I have no idea how you are setting $template_select and if you are aware it will always say the same template name?
An alternative approach that I believe achieves what you want:
$templates = array('cuatro', 'ohlittl');
$selectedTemplate = strtolower(str_replace("-","_",$_GET['select']));
foreach ($templates as $template)
{
if ($template === $selectedTemplate) {
include(dirname(__FILE__) . "/templates/" . $template . ".php");
echo "You've chosen {$template}.";
}
}
Either your template
Outputs the text directly (echo)
Stores the result in a global (e.g. $page_output) or a local variable (in the include happens inside a function, but that's transparent for the template).
Returns the output (yes, includes can return values).
You seem to want option 2, yet your templates are not defining any $page_output variable. You could also output the text directly in the templates, buffer the output, and assign it to $page_output:
ob_start();
include "file.php.inc";
$page_output = ob_get_contents();
ob_end_clean();