$array = explode('/', $_SERVER['REQUEST_URI']);
$count = count($array);
extract($array, EXTR_PREFIX_ALL, 'var');
can the variables (created using extract function) be isseted automatically? to avoid "Notice: Undefined variable:" errors when error_reporting(E_ALL); is enabled.
thank you
I tried doing something of this sort, still needed to isset() whenever, the variables are used next in the code (when error_reporting(E_ALL); is enabled).
if(isset($var_0))
{
$var_0 = filter_var($var_0, FILTER_SANITIZE_STRING);
}
if(isset($var_1))
{
$var_1 = filter_var($var_1, FILTER_SANITIZE_STRING);
}
if(isset($var_2))
{
$var_2 = filter_var($var_2, FILTER_SANITIZE_STRING);
}
if(isset($var_3))
{
$var_3 = filter_var($var_3, FILTER_SANITIZE_STRING);
}
==========================
Alternatively, tried the one line if condition,
$var_0 = isset($var_0) ? filter_var($var_0, FILTER_SANITIZE_STRING) : '';
$var_1 = isset($var_1) ? filter_var($var_1, FILTER_SANITIZE_STRING) : '';
$var_2 = isset($var_2) ? filter_var($var_2, FILTER_SANITIZE_STRING) : '';
$var_3 = isset($var_3) ? filter_var($var_3, FILTER_SANITIZE_STRING) : '';
while the error got subsided, but, a new problem arises i.e., variables (which are not created by extract function are getting isseted because of this one line if condition approach).
I am posting two of the routing rules (of two urls) in the website.
$pagename = "not-found.php";
//Different Routing Engine Rules follows
if ((isset($var_1)) && (($var_1 == "") || ($var_1 == "index.php"))) {
if((isset($var_2)) || (isset($var_3)) || (isset($var_4)) || (isset($var_5)) || (isset($var_6)) || (isset($var_7)))
{
$pagename = "not-found.php";
}
else
{
$pagename = "default-home.php";
}
}
if (($var_1 == "login"))
{
//echo "Login Page URL\n";
if((isset($var_2)) || (isset($var_3)) || (isset($var_4)) || (isset($var_5)) || (isset($var_6)) || (isset($var_7)))
{
$pagename = "not-found.php";
}
else
{
$pagename = "login.php";
}
}
include "code/" . $pagename;
any help will be appreciated, thank you
If I understand your question correctly then, no. It's still your responsibility to know what variables are available and act accordingly. You can simply disable these notices via error_reporting(E_ALL & ~E_NOTICE) for the portion of code in question.
Edit
Looking at your updated question, I think it would be helpful if you could explain what you're trying to achieve. Personally, I see the use of extract as a bit of a code smell and there may be a better way :)
Related
bit of a strange one that I've not been able to resolve for months so I finally have given in and have come here for the answer. Hopefully.
I have the below shortcode that when ran returns the phone number depending on what variable has a value. This PHP code works as expected, the one thing that doesn't work as expected however, is the first ever page load.
When someone goes to the site for the first time (or in incognito mode) the shortcode doesn't output anything, however, refresh the page just once and it'll display the output of the correct value and I have no idea why.
<?php function gw_cookie($atts) {
extract(shortcode_atts(array(
"value" => ''
), $atts));
$getVariable = isset($_GET[$value]) ? $_GET[$value] : '';
$newGetVariable = str_replace('_', ' ', $getVariable);
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
$acfField = get_field('page_cookie_'.$value.'');
$optionsACF = get_field('options_company_details', 'options');
$area = $optionsACF['options_area'];
$phone = $optionsACF['options_telephone'];
if(!empty($cookiePhone) && $cookiePhone !== 'undefined') { //If cookie is not empty do the following
echo '1';
} elseif(!empty($newGetVariable)) { //If cookie is empty and get variable is not
echo '2';
} elseif($acfField) { //If ACF field is not empty do the following
echo '3';
} elseif ($value == "phone") {
return '4';
}
} add_shortcode("gw-cookie", "gw_cookie");
This codes file is being imported into the functions.php file using the following line:
require_once( __DIR__ . '/shortcodes/gw-cookies.php' );
A cookie itself would be created on the first run and your criteria requires cookiePhone which is why you have to refresh to make it work.
As per the comments, change:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
to:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : NULL;
I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.
I am sorry to ask such a question but am bit confused about this.
I am having simple variables defined.
$a =1;
$b=2;
$c=3;
$d="";
for($i=0;$i<10;$i++)
{
$testa = 1;
$testb = 4;
$testc = 3;
$testd = 7;
if($a!="" || $b!="" || $c!="" || $d!="") {
if($a==$testa && $b==$testb && $c==$testc && $d==$testd) {
echo $testa;
echo $testb;
echo $testc;
echo $testd;
}
}
}
This is sample php code.
what I need is that I have variables defined at top. SO in my loop i want to display result if user has any 1 variable but in below loop display result based on "and" parameter.
I actually want to skip the empty variable. SO in this case, I want as $d is empty, so it should be prevented somehow from if($a==$testa && $b==$testb && $c==$testc && $d==$testd) from here.
Any help is really appreciated.
To skip the empty values from the check, use ||
if ( ... && (empty($d) || $d == $testd)) {
Then if you also want to skip it in your echos :
echo !empty($d) ? $testd : '';
I have a hard time with isset() function. Exactly how do I tell php that only if the data was assigned to my, lets say $_SESSION['msg']; variable, only then activate it and use it... So far I am getting a lot of notices: undefined index and this code doesn't do it also:
if (isset($_SESSION['monster']) &
isset($_SESSION['spol']) &
isset($_SESSION['combat']) &
isset($_SESSION['turns']) &
isset($_SESSION['zmaga']) &
isset($_SESSION['zguba']) &
isset($_SESSION['cekini']) &
isset($_SESSION['post']) )
{
$monster = $_SESSION['monster'];
$spol = $_SESSION['spol'];
$combat = $_SESSION['combat'];
$turns = $_SESSION['turns'];
$zmaga = $_SESSION['zmaga'];
$zguba = $_SESSION['zguba'];
$cekini = $_SESSION['cekini'];
$_POST = $_SESSION['post'];
}
Data was supposed to be asigned to it from a redirecting previous site but that site doesn't always activate so I need an alternative. That's why I am asking this.
EDIT with full code:
session_start();
include 'razno.php';
include 'save.php';
include 'stats.php';
$igralec_ime = $_SESSION['username'];
$monster = prikazi_borba($igralec_ime);
$poskodbe = prikazi_stat('curhp', $igralec_ime);
if (prikazi_stat('curhp', $igralec_ime) == 0)
{
$moznost = 'Tvoje zdravje je resno ogroženo, vrni se domov!';
}
else if (isset($_SESSION['monster']) &&
isset($_SESSION['spol']) &&
isset($_SESSION['combat']) &&
isset($_SESSION['turns']) &&
isset($_SESSION['zmaga']) &&
isset($_SESSION['zguba']) &&
isset($_SESSION['cekini']) &&
isset($_SESSION['post']) )
{
$monster = $_SESSION['monster'];
$spol = $_SESSION['spol'];
$combat = $_SESSION['combat'];
$turns = $_SESSION['turns'];
$zmaga = $_SESSION['zmaga'];
$zguba = $_SESSION['zguba'];
$cekini = $_SESSION['cekini'];
$_POST = $_SESSION['post'];
}
update_save($igralec_ime, 'gozd', $monster);
include '../html/gozd.html';
?>
You'll want to replace & with and:
if (isset($_SESSION['monster']) and isset($_SESSION['spol']) and isset($_SESSION['combat']) and isset($_SESSION['turns']) and isset($_SESSION['zmaga']) and isset($_SESSION['zguba']) &
isset($_SESSION['cekini']) and isset($_SESSION['post']) )
{
$monster = $_SESSION['monster'];
$spol = $_SESSION['spol'];
$combat = $_SESSION['combat'];
$turns = $_SESSION['turns'];
$zmaga = $_SESSION['zmaga'];
$zguba = $_SESSION['zguba'];
$cekini = $_SESSION['cekini'];
$_POST = $_SESSION['post'];
}
You should take a look at logical operators in PHP. In many programming languages (PHP included) & is 'bitwise and' operator (not logical). Since you want logical operator you need to use && or and. Also take a look at other PHP operators, just to get familiar with them and to avoid problems like this.
Also if you are using those values outside the if/then block you should think about cases when your statement will be false and assign some default values to those variables.
What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;