include if value in array defined on included file - php

I want to check if the page name is a value in an array defined on the included file and, if so, include it.
<?php
// parent page that includes the files
$pageLabel = 'three';
if (in_array('pageLabel', $multicats)) {
include $filename;
}
?>
<?php
// example for a file to be included
$multicats = array('one', 'three', 'five');
$filename = $_SERVER['PHP_SELF'];
echo 'Hello World of one, three and five';
?>
However an error says it expects $multicats to be an array, which it is, meaning it doesn't check the included file for it.
What to do?

You have to have array of multicats somewhere in parent page before condition. If you have it in included file, it's init after using in condition. Or you can check if it exist with isset, as Captain Crunch said.
Note: in condition in_array you have string 'pageLabel' and not var $pageLabel, is it correct?

first, you should pass: $pageLabel var, and not 'pageLabel' string (see line 4 in your code).
second, i advise you use "isset":
if ( isset($multicats) && isset($multicats[$pageLabel]) && isset($filename) )
include $filename;

Related

PHP Delete File if other file exists

Note: The file number is just so I can refer to each file easier
I am testing some code in which I have a file called first.txt (file 1) and and file called tom-first.php (file 2), file 2 file checks for the file 1's existence and sets a variable, then in my index.php(file 3), I require file 2 and if the variable is 1, I redirect to startup.php(file 4). File 4 deletes a text file called text.txt
My error is when I run the code, no matter what happens, test.txt is always deleted
tom-first.php
<?php
if (file_exists('first.txt')) {
$first = '1';
} else {
$first = '0';
}
echo $first;
?>
index.php
<?php
require 'tom-first.php';
if($first = '1')
{
header("Location: startup.php");
}
else
{
echo 'HI';
}
?>
Startup.php
<?php
unlink('text.txt')
?>
First.txt is Empty
I feel like the error is to do with setting variables on file 2 although echoing out $first shows the right number.
Any help is appreciated, even a completely different method of this would be useful, I am basically trying to make a system where it has a setup that runs on first time use.
You have a typo in index.php file.
Equality comparison operator in PHP is '==', not '='.
Your if statement below assigns value '1' to $first variable and always evaluates to '1'.
index.php
<?php
require 'tom-first.php';
if($first = '1') // this should be $first == '1'
{
header("Location: startup.php");
}
else
{
echo 'HI';
}
?>
With = you make an assignment (you assign a value to a variable). But == is a comparison operator. In your case you're evaluating 1 which is always TRUE. Another thing is, why so verbose and so many files if you can just write:
$first = file_exists('first.txt') ? 1 : 0;
and then the rest. Or even better...
if (file_exists('first.txt') {
unlink('first.txt');
// and do some other stuff
}
echo 'whatever';
But... :)
If you have to do something like this, it very much smells.
Why would you check for the presence of a file only to delete it right away?

i need to get the name of a variable from a file

As the title said i need a way to set the variable name depending of what the name of the picture is (i got over 100 different pictures)
Since i got custom classes in another php file for each picture (like tags) like for example:
$picture1 = "hillside sunset";
$picture2 = "beach cyprus";
and so on, so i need to fetch each variable for each picture
Heres the current loop where the div class is going to be each pictures name ($PICTURENAME is just to define where this code goes and is irelevant codewise):
<?php
foreach (glob("img/*.jpg") as $filename)
{
$path = $filename;
$file = basename($path);
$file = basename($path, ".jpg");
echo '<div class="'.$PICTURENAME.'" id="'.$file.'"><img src="'.$filename.'"> '.$file.' </div>';
}
?>
Don't use 100+ variables. Using a database would make far more sense, but if you don't want to get into learning that (you should, though), using a data structure would still make far more sense.
You could create one array (and use it as a map), and have the filename as the key, and the value would be the tags.
In PHP, you can address a variable using another variable:
$name = "foo";
${$name} = "bar";
echo $foo; // prints "bar"
echo ${$name}; // the same as above
However, as Kitsune already recommended, you are better off using something else, e.g., an array.

Parse array from php file

The .php file contains code like:
<?php
return array(
// commments...
'some_item' => 'abc',
// commments...
'some_other_item' => array(1, 2, 3),
...
);
What's the best way to "parse" this file somehow from within my PHP application, and be able to update data in it, without breaking formatting, code etc. ?
$content = require($file); will get the file's content (beware of relative paths and requirevs include semantics).
file_put_contents($file, '<?php return ' . var_export($content, true) . ';'); will write the content back to the file, but formatting will change. If you really need to keep the formatting, you could look into PHP Beautifier. It's not a perfect solution though.
simply include() the file:
$my_array = include 'myarray.php';
See example #4 at http://php.net/manual/en/function.include.php and http://php.net/manual/en/function.return.php
The best way is to include it; yes, include returns a value!
$data = include 'someData.php';
Assuming that your array has only two items
<?php
$myArray=include 'data.php';
$myArray[count($myArray)]='Item-3';
echo $myArray[2]; // Item-3
?>
Are you trying to load filenames which are contained in an array? If so:
$array_of_files = array('header.php','database.php','../inc/other_stuff.php');
foreach($array_of_files as $file)
{
include $file;
}

PHP: How do I prevent include/require to add numbers in a loop?

Every time I try to assign an include/require to a variable, it adds a number at the end.
I would like to do it without that stupid number.
I tried file_get_contents but it does not work the same way.
If it's not possible to do it with require, is there an EASY and SHORT (Single function and single line of code) way to do it with another function?
Please help me, because it's driving me crazy.
For example:
FILE 1 (div.php):
<div><?php echo $x; ?></div>
FILE 2:
<?php
$x = "Example 1";
$file = include('div.php');
echo $file;
$x = "Example 2";
$file = include('div.php');
echo $file;
?>
OUTPUT:
Example 1
1
Example 2
1
This is because the default return value of include and require is true, or 1.
When you include the file, it automatically outputs your content in the included file. When you echo $file, you are echoing the return value of the include, which is true.
As a note, if you put return false; or return "<div>$x</div>"; in your included file, that would then become the value of $file. Whatever you return from your included file, that is passed to the variable.
For example:
FILE 1 (monkey_do.php):
<?php
return "I am a monkey";
FILE 2 (main.php):
<?php
$monkey_see = include 'monkey_do.php';
echo $monkey_see; // prints "I am a monkey"
You could use output buffering:
$x = 'Example 1';
ob_start();
include ('div.php');
$file = ob_get_contents();
ob_end_clean();
echo $file;
EDIT: I just saw this example in the manual that defines a function to do this: http://php.net/manual/en/function.include.php#example-131
If you use FILE1 as the template, just include it. Also you can use output buffering as #grossvogel answered.
<?php
$x = "Example 1";
include('div.php');
$x = "Example 2";
include('div.php');
?>

Variables are not being rewritten as page is processed

I have a php script that checks to see if a particular file exists. This name of the file is defined by the 'compartment' variable. When the script is copied and pasted again into a separate block, changing only the compartment variable it runs into a problem...
Say for example 1.jpeg exists but 2.jpeg doesn't. The first block displays a link to this file, but so does the second block when it should be displaying the upload form as 2.jpeg doesn't exist.
It's as though the $currentfile or $filename variables are being carried over into the blocks below them.
Please find an example of my problem below...
<?php
$compartment = "1";
foreach (glob("$compartment.*") as $filename) {
$currentfile = "$filename";
}
if (file_exists($currentfile)) {
echo "
/* If the file exists, it will display a link to the file. */
<a href='$currentfile' target='_blank'>LAUNCH PREVIEW</a>
";
} else {
echo "
/* Here is an uploader form that would transform foobar.jpeg into $compartment.jpeg. */
";
}
?>
<?php
$compartment = "2";
foreach (glob("$compartment.*") as $filename) {
$currentfile = "$filename";
}
if (file_exists($currentfile)) {
echo "
/* If the file exists, it will display a link to the file. */
<a href='$currentfile' target='_blank'>LAUNCH PREVIEW</a>
";
} else {
echo "
/* Here is an uploader form that would transform foobar.jpeg into $compartment.jpeg. */
";
}
?>
Thank You.
Maybe your file_exists() must be inside of foreach otherwise $currentfile always be the last file found in the directory.
$filename isn't containing path variable
Your logic seems a little bit weird for me. You iterate through a dir and checks every file inside if file_exists or not. Because no other checking (against a prepopulated array for example) happens this will always return true.
foreach will fail to execute (and should yell at you) if you provide a non-array variable.
Therefore since 2.jpeg doesn't exist, glob() will return NULL making foreach not execute. However, you are assigning $currentfile within a foreach that never executes so $currentfile will keep its old value "1.jpeg".
The reason this might appear to work the other way around (when $compartment = 1) is because $currentfile is initialized with garbage on first use which is in if(file_exists($currentfile)). This of course evaluates to false so execution jumps to the else part.
HTH
place whole if/else block inside foreach and replace file_exists($currentfile) with file_exists($filename);
Seperate sections in a .php file are part of the same namespace / block / execution. If you use a variable in your first section, it will still be defined and and still have the same value in your second section.
There is no difference between
<?php
$MyValue = 'Value';
?>
<?php
echo $MyValue;
?>
and
<?php
$MyValue = 'Value';
echo $MyValue;
?>

Categories