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?
Related
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
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;
The code below needs to read the directory uploads/ but he always tells me that the directory is not empty, even when it totally is empty.
<?php
$dir = "uploads/";
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
Is there a error in this code or anything or am I just going crazy?
UPDATED CODE
<?php
echo (count(glob("uploads/*")) === 0) ? 'Empty' : 'Not empty';
?>
FULL PAGE CODE UPDATE
<?php
if (array_key_exists('error', $_GET)) {
echo '<div class="galleryError">That image could not be found, we're sorry!</div>';
} elseif (array_key_exists('unknownerror', $_GET)) {
echo '<div class="galleryError">There went something wrong</div>';
} else {
echo '';
}
if ($handle = opendir('uploads/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<div class='imgbox'><a href='fullscreen.php?token=$entry'><img src='$submap$gallery$entry' class='boximg'></a><p class='boxname'>$entry<br /><a href='?view&token=$entry'><small>View this image</small></a></p></div>";
}
}
closedir($handle);
}
// all the above is working but then we have this lonely code over here which refuses to work.
echo (count(glob("uploads/*")) == 0) ? 'Empty' : 'Not empty';
?>
glob is silently failing. I couldn't tell you why, with file system access it's usually permissions related but there could be other factors - it even says in the documentation that the functionality is partially dependent on your server environment...
On some systems it is impossible to distinguish between empty match and an error.
When there's a glob error it returns false - and count(false) === 1 (also documented) so it's no surprise folks get into confusing situations when they ignore these checks. If you really don't care about errors you can utilise the short-hand ternary operator to make an inline false-check, ensuring an array is always passed to count so it will behave as expected:
$isEmpty = count(glob("uploads/*")?:[]) === 0;
This still doesn't get around the fact that the directory is not being read though - have you tried printing the output of glob when you do have files in the directory? I'd imagine that's borked too. What does the following print? :
var_dump(is_readable('./uploads'));
Does the output of the following match your expected working directory? :
echo realpath('uploads');
FYI use var_dump when debugging, not print_r as suggested in the comments - it will give you more detail about the variables / types / structures / references etc. that you actually need.
In summary - things to consider:
What OS is running on the server? What mode is PHP running in? Is it running under SuPHP / FastCGI or similar context. What user owns the ./uploads directory, what permissions are set on it?
I made a php script to see if what the contents of a txt file are the same as the users input. I wrote an if statement to see if it is correct and if it isn't send it to an else. If i dont send any variables, then it works, and displays
a is b is file is 1
but if i enter the file and the correct contents it displays
a is test.txt b is hello file is hello 0
Here is my code
<?php
session_destroy();
$a=htmlspecialchars($_REQUEST['a']);
$b=htmlspecialchars($_REQUEST['b']);
$my_file = file_get_contents($a);
echo "a is $a\n";
echo "b is $b\n";
echo "file is $my_file\n";
if ( $my_file == $b ) {
echo "1";
}else {
echo "0";
}
?>
Any ideas?
These are un-initialized variables, so if you enter nothing, then you're getting if (false == false) which is true.
This is because php interprets null as being false. It's weird, I acknowledge.
Either check to see if your variables have been set, or initialize them with defaults.
Try using htmlspecialchars function on the content you read from your file as well just to be on the safe side, then use trim on the input you read from a file and on the user input as well
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;
?>