If statement not working, but kinda working - php

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

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 - Check if file exists without knowing the extension

I already saw this question, but it didn't work for me.
What I need to do is to check whether a file exists, in PHP, without knowing the extension.
I use this code:
<?php
if (count(glob("/database/".$_REQUEST['thetitle'].".*")) == 0) {
echo 'true';
} else {
echo 'false';
}
?>
EDIT:
Maybe it's relevant saying that the script is located in
[root]/functions/validatefilename.php
and the database in
[root]/database/
But it always returns false, no matter what the filename ($_REQUEST['thetitle']) is.
try:
count(glob("./database/".$_REQUEST['thetitle'].".*"))
Looks to me like it works fine except that you should be specifying the full path:
if (count(glob( "/path/to/" . "database/" .$_REQUEST['thetitle']. ".*")) == 0) {

PHP File Operation

I am trying to create a text file with PHP in fopen("test.txt","a"). I have also tried with fopen("test.txt","w+").
The text file is created but I want to check for some string in test.text, that it exist or in test.txt it will not create duplicate entry. Can someone help me out?
Use this code:
$content = file_get_contents('test.txt');
if (str_pos('YOUR KEYWORD', $content) !== false){
// your keyword exists in the file
}
if (!file_exists("test.txt"))
{
///file does not exist
}
else
{
$f = fopen("test.txt", "a");
fwrite($f, "appending text");
}
searching in file:
$arr = file_get_contents("test.txt");
if (preg_match("/your_rexexp/i", $arr))
{
echo "text found";
}
If I understand you correctly, you want to insert new values into a textfile, but first check if the value already exists in it.
You can use fread() to get the contents of the file, and then through preg_match() you can check for values in the file.
If you are using PHP5 then you can use some of the new easy functions.
file_exists(filename) returns boolean
sayin if the file exists.
file_put_contents(filename,data) returns boolean saying if the write was successful.
file_get_contents(filename) returns the contents of the file (string).

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