Variables are not being rewritten as page is processed - php

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;
?>

Related

How Can I Remove An Index From An Array and Echo It Out?

In PHP I am trying to have it so the user can insert an array of an index that they want removed and then it will echo out that array without the array that they didn't want. Right now the troublesome part of my code for the main file is
include("/opt/lampp/htdocs/upload/styles/styles.php");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//this is the content of the array that the user wants gone//
$want = $_POST['which'];
$file = fopen("/opt/lampp/htdocs/upload/styles/styles.php", "a");
if (in_array($want, $allStyles)) {
$index = array_search($want, $allStyles);
fwrite($file, " unset(\$allStyles[$index]);");
fclose($file);
echo implode(", ", $allStyles);
} else {
echo "error";
}
}
styles.php is
<?php
$allStyles[] = 'one';
$allStyles[] = 'all';
If I insert "all" for $want it will unset the array where it contains "all" and if I do
php styles.php
in my linux terminal it will only echo out "one" but if I do this on my page on my web browser it will echo out both strings. How can I make it so it will only echo the array that wasn't asked to be removed?
not sure if I understood your problem (or what you want to achieve) properly but, try this code:
$file='/opt/lampp/htdocs/upload/styles/styles.php';
include($file);
if(isset($_POST['which'])){
$want=$_POST['which'];
if(in_array($want,$allStyles)){
$index=array_search($want,$allStyles);
unset($allStyles[$index]);
file_put_contents($file,$allStyles);
}else{
echo "error";
}
}
You only want to change the file if $_POST['which'] is set, not on every POST action, I guess.
You just search the index (like you already did the right way) then unset it (what was wrong in your code, I guess) then you write it (file_put_contents() makes the code a bit more readable).
Last thing: I've moved the path to the file in $file in order to make it more maintainable

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?

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.

glob() function only returns empty array in php

I've been trying to make a simple website that lets you specify a directory, and embeds a player for each mp3 in whatever directory the user specifies. The problem is that no matter how I enter the directory name, glob() does not return any files. I've tried this with local folders, server directories, and the same folder as the php file.
'directoryPath' is the name of the text box where the user enters, you guessed it, the directory path. The 'echo $files' statement displays nothing onscreen. The 'echo "test"' statement DOES run, but the 'echo "hello"' statement in the loop does not execute.
Any help is appreciated!
if (!empty($_POST['directoryPath']))
{
$path = ($_POST['directoryPath']);
$files = glob("$path/{*.mp3}", GLOB_BRACE);
echo $files[0];
echo "test";
foreach($files as $i)
{
echo "hello";
echo $files[$i];
?>
<embed src=<?php $files[$i]; ?> width=256 height=32 autostart=false repeat=false loop=false></embed><?php echo $files[$i] ?></p>
<?php;
}
unset($i);
}
Validate the input first:
$path = realpath($_POST['directoryPath']);
if (!is_dir($path)) {
throw new Exception('Invalid path.');
}
...
Additionally check the return value glob returns false on error. Check for that condition (and ensure you are not using one of those systems that even return false when there are no files found).
I hope this is helpful. And yes, check your error log and enable error logging. This is how you can see what is going wrong.
Also see the following related function for a usage-example and syntax of GLOB_BRACE:
Running glob() from an included script returns empty array
One one tool I find very useful in helping debug variables in PHP is var_dump(). It's a function that provides you with information about a variable's type, it's contents, and any useful metadata it can attain from that variable. This would be a very useful tool for you here, because you'll quickly realize what you have in the variable $i is not at all what you expect.
$files = glob("$path/{*.mp3}", GLOB_BRACE);
foreach ($files as $i) {
var_dump($i);
}
/* Here's a hint, $i is not an index to the $files array.
So $files[$i] makes no sense. $i is actually the value not the key.*/
foreach ($files as $key => $value) { // very different from
// $key is the key to the current element of $files we're iterating over
// $value is the value of the current element we're iterating over
}
So in your code $i is the value not the key. See http://php.net/foreach for more information on how the construct works.
Also, what should be noted here is that you are using a relative path, whereas glob will return an absolute path. By relative this means your searching relative to the CWD (Current Working Directory) of your PHP script. To see wha that is you can use the following code.
var_dump(real_path('.'));
// similarly ...
var_dump(getcwd());

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.

Categories