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

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.

Related

PHP If-Else does not work for comparing filecontents

I am trying to make a PHP application which searches through the files of your current directory and looks for a file in every subdirectory called email.txt, then it gets the contents of the file and compares the contents from email.txt with the given query and echoes all the matching directories with the given query. But it does not work and it looks like the problem is in the if-else part of the script at the end because it doesn't give any output.
<?php
// pulling query from link
$query = $_GET["q"];
echo($query);
echo("<br>");
// listing all files in doc directory
$files = scandir(".");
// searching trough array for unwanted files
$downloader = array_search("downloader.php", $files);
$viewer = array_search("viewer.php", $files);
$search = array_search("search.php", $files);
$editor = array_search("editor.php", $files);
$index = array_search("index.php", $files);
$error_log = array_search("error_log", $files);
$images = array_search("images", $files);
$parsedown = array_search("Parsedown.php", $files);
// deleting unwanted files from array
unset($files[$downloader]);
unset($files[$viewer]);
unset($files[$search]);
unset($files[$editor]);
unset($files[$index]);
unset($files[$error_log]);
unset($files[$images]);
unset($files[$parsedown]);
// counting folders
$folderamount = count($files);
// defining loop variables
$loopnum = 0;
// loop
while ($loopnum <= $folderamount + 10) {
$loopnum = $loopnum + 1;
// gets the emails from every folder
$dirname = $files[$loopnum];
$email = file_get_contents("$dirname/email.txt");
//checks if the email matches
if ($stremail == $query) {
echo($dirname);
}
}
//print_r($files);
//echo("<br><br>");
?>
Can someone explain / fix this for me? I literally have no clue what it is and I debugged soo much already. It would be heavily gracious and appreciated.
Kind regards,
Bluppie05
There's a few problems with this code that would be preventing you from getting the correct output.
The main reason you don't get any output from the if test is the condition is (presumably) using the wrong variable name.
// variable with the file data is called $email
$email = file_get_contents("$dirname/email.txt");
// test is checking $stremail which is never given a value
if ($stremail == $query) {
echo($dirname);
}
There is also an issue with your scandir() and unset() combination. As you've discovered scandir() basically gives you everything that a dir or ls would on the command line. Using unset() to remove specific files is problematic because you have to maintain a hardcoded list of files. However, unset() also leaves holes in your array, the count changes but the original indices do not. This may be why you are using $folderamount + 10 in your loop. Take a look at this Stack Overflow question for more discussion of the problem.
Rebase array keys after unsetting elements
I recommend you read the PHP manual page on the glob() function as it will greatly simplify getting the contents of a directory. In particular take a look at the GLOB_ONLYDIR flag.
https://www.php.net/manual/en/function.glob.php
Lastly, don't increment your loop counter at the beginning of the loop when using the counter to read elements from an array. Take a look at the PHP manual page for foreach loops for a neater way to iterate over an array.
https://www.php.net/manual/en/control-structures.foreach.php

name of images from folder not printed on screen in php

I have an html file and i have done the code for printing the names of images from a folder in PHP , but it is not printing the values to screen. if i echo any other thing it is printed on screen.
i have the set the server using xampp.
how to correct this, i make the names of images from that folder printed on screen?
do i need to do anything extra
im a newbie in php. how can i achieve this?
<?php
function findImagesInFolder()
{
$folder = $_GET['C:\xampp\htdocs\firstsite'];
$images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
echo json_encode($images);
exit();
}
?>
It seems you have misused the $_GET variable.
I thing you want to just use the string value, ie.:
$folder = 'C:\xampp\htdocs\firstsite';
And note, the exit() terminates whole script after printing the json_encoded string.
So, to make the function reusable change it to get the path as a parameter $folder:
<?php
function findImagesInFolder($folder, $filter = '*.*')
{
// note, here we expect the path does not trail with backslash
$images = glob($folder . '\\' . $filter, GLOB_BRACE);
return json_encode($images);
}
// call the function with actual path to scan:
$path = 'C:\xampp\htdocs\firstsite';
$filter = '{*.png,*.jpg,*.jpeg,*.gif}';
echo findImagesInFolder($path, $filter);
?>
Note: output as [] means empty array encoded to JSON.

include if value in array defined on included file

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;

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

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