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'];
}
Related
look at this syntax of variable name modifying:
${'a' . 'b'} = 'hello there';
echo $ab;
this returns "hello there"
But i want do declare defined variables dynamical.
$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};
It return error, i want to generate E404 dynamical on php codes and get its value.
I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research.
You need to call constant() to retrieve the value of a constant from a string. Your example should look like:
$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");
and it will display Not found.
<?php
$ErrorCode = $_GET['error_code']; // Where error_code = 404
$Errors = array(); // here we are creating a new array.
$Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable
print_r($Errors); // Would return Array( [404] => Whatever);
echo $Errors["404"]; // Would return Whatever
?>
Well Php has a feature called variable variables. See this link: http://php.net/manual/en/language.variables.variable.php. It allows a variable name to be assigned to a variable.
I get the error undefined variable err. I've tried isset here but maybe my code is wrong.
if(err ==1)
{
$record = $_POST;
foreach($record as $key=$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
make sure that you have defined "err" as constant somewhere or use $err instead of err.
There is Two mistrake in your code
1. Forget $ sign which is neccessary in PHP
2. Wrong syntax for foreach loop there will be => sign instead of =
// so right code is
if($err ==1)
{
$record = $_POST;
foreach($record as $key=>$val)
$record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
in php variable have prefix $ symbol or err must be constant,but it is good practice to use constant name as Capital letters
try this code
if( isset($err) && $err == 1 )
{
$record = $_POST;
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
EDIT
try to check variable is exist or not using isset()
The reason you are getting undefined is because where you define your err variable you are forgetting to create it as $err.
You need to change every place in your code where you have err variable to $err, not just in the place you have shown in this question. That's why you're still getting undefined after trying the solutions here, because you're only changing to $err in one place.
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");
}
}
}
?>
<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";
}
when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}