Only first elseif in if/elseif/else statement is working - php

Only the elseif (isset($foo['read'])) on line 37 is working, the if and first elseif work, when I try to call the second elseif, it returns the first elseif statements output. I have even swapped the two elseif statements and it still only returned the first elseif statement output when calling the second elseif statement.
<?php
$nh = "true";
$foo = file_get_contents("php://input");
//$stuff = json_decode($foo, true);
function savetxt($sttext)
{
$filename = 'test.txt';
$somecontent = $sttext;
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
}
else {
echo "The file $filename is not writable";
}
}
if (strpos($foo, 'write:') !== false) {
echo 'Attempting to write!';
$stext = substr($foo, 6);
savetxt($stext);
}
elseif ($foo == "read"){
echo file_get_contents( "test.txt" );
}
elseif ($foo == "test){
echo 'Working!';
}
else {
echo 'Didn't get test.';
}
?>

try this(you must replace else if with elseif)
else if ($foo && $foo=='read')
and
else if ($foo && $foo=='test')
and at end
else if (!$foo || $foo=='')

Related

How to skip fwrite() for x lines

I'm creating PHP program which should find in *.txt file line that starts with word "tak" and skip that program from rewriting it to the next *.txt file. So what I want to achieve now is prevent it from writing, for example, 2 more lines after line that started with "tak" word. Here is my CODE:
<?php
$file2 = fopen("out.txt", "w") or die("Unable to open file!");
$handle = fopen("plik.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (strpos($line, 'tak') === 0) {
echo 'found<br/>';
}
else {
fwrite($file2, $line);
}
}
fclose($handle);
echo 'OK';
}
else {
echo "can't read the file";
}
?>
I think using file, a for loop, and file_put_contents would work and be simpler.
$file2 = "out.txt";
//$file = file($file2) or die("Unable to open file!");
$file = array('asdf',
'asdf',
'asdf',
'tak',
'1',
'2',
'3',
'4');
file_put_contents($file2, ''); // truncate file;
for($i = 0; $i < count($file); $i++) {
$line = $file[$i];
if (strpos($line, 'tak') === 0) {
echo 'found<br/>';
$i = $i + 2;
} else {
// file_put_contents($file2, $line, FILE_APPEND | LOCK_EX);
echo $line;
}
echo 'ok';
}
Demo: https://eval.in/597694
Output (kinda messy but gets the point tak, 1, and 2 skipped):
asdfokasdfokasdfokfound<br/>ok3ok4ok
You can do it by keeping boolean and integer variable to count the number of occurrence. Like this,
<?php
$file2 = fopen("out.txt", "w") or die("Unable to open file!");
$handle = fopen("plik.txt", "r");
if ($handle) {
$stopWriteLines=false;
$max_line_skip=2;
// Taking above two variables for our logic.
while (($line = fgets($handle)) !== false) {
if($stopWriteLines) {
$max_line_skip--;
}
// Above condition check if we found tak in line then decrements the skip lines count.
if (strpos($line, 'tak') === 0) {
echo 'found<br/>';
$stopWriteLines=true; // Setting Boolean variable to skip writing lines.
}
else {
if(!$stopWriteLines) { // will write only if Boolean variable is set to true.
fwrite($file2, $line);
}
}
if($max_line_skip==0) {
$stopWriteLines=false;
}
// Above condition will make Boolean variable false after skipping 'n' lines.
}
fclose($handle);
echo 'OK';
}
else {
echo "can't read the file";
}
?>
Please check the explanations in code for better understanding of respected code sections.

ASP to PHP conversion, what did I do wrong?

I'm pretty new to PHP and trying to convert an asp file handling "function" to php, but for some reason the page just turns up blank when I try to run it with the PHP part (if I remove it the site fires up perfectly, without the functionallity ofcourse.
So my question is: What did I do wrong here?
<?php
if (!$_GET['page'] == "")
if (!$_GET['page'] == "gaestebog")
If (file_exists($_GET['page'] && ".html"))
$f=$file=fopen($_GET['page'] && ".html", r);
print $f;
fclose($file);
Else
print("Siden kunne ikke findes");
End If
elseif ($_GET['page'] == "gaestebog")
print "<a href='default.php?page=gaestebog'>Der kan i øjeblikket ikke oprettes nye indlæg</a><br /><br />"
end if
elseif ($_GET['page'] == "")
If (file_exists("forside.html"))
$f=$file=fopen("forside.html", r);
print $f;
fclose($file);
Else
print("Siden kunne ikke findes");
End If
end if
?>
if ( isset($_GET['page']) )
{
$page = $_GET['page'];
if ( $page != "gaestebog" )
{
$filename = sprintf('%s.html', $page);
if ( file_exists($filename) )
{
if( $handle = fopen($filename, 'r') )
{
echo fread($handle, filesize($filename));
fclose($handle);
}
}
else
{
echo "Siden kunne ikke findes";
}
}
else if ( empty($page) )
{
if ( file_exists("forside.html") )
{
if( $handle = fopen("forside.html", 'r') )
{
echo fread($handle, filesize("forside.html"));
fclose($handle);
}
}
else
{
echo "Siden kunne ikke findes";
}
}
}
Try this:
<?php
if (isset($_GET['page']) && !empty($_GET['page'])) {
if ($_GET['page'] !== "gaestebog") {
if (file_exists($_GET['page'] . ".html")) {
$file = fopen($_GET['page'] . ".html", "r");
$contents = fread($file, filesize($_GET['page'] . ".html"));
echo $contents;
fclose($file);
} else {
echo "Siden kunne ikke findes";
}
} else if ($_GET['page'] == "gaestebog") {
echo "<a href='default.php?page=gaestebog'>Der kan i øjeblikket ikke oprettes nye indlæg</a><br /><br />";
} else if (empty($_GET['page'])) {
if (file_exists("forside.html")) {
$file = fopen("forside.html", "r");
$contents = fread($file, filesize("forside.html"));
echo $contents;
fclose($file);
}
}
echo "Siden kunne ikke findes";
}
?>

How to check if file exist in zip archive

i have zip archive and after extract him i need to check if moduleConfig.xml exist inside zip archive. How i can do that.
I try this
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
if(file_exists($zip->getFromName('moduleConfig.xml')))
{
echo "Config exists";
// Do somthing
}
}
else {
echo 'Failed code:'. $res;
}
It should be like this:
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
if ($zip->locateName('moduleConfig.xml') !== false)
{
echo "Config exists";
}
}
else {
echo 'Failed code:'. $res;
}
try:
if ($zip->locateName('moduleConfig.xml') !== false)
{
echo "Config exists";
}
You can do this by using getFromName
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
if($zip->getFromName('moduleConfig.xml') != false)
{
echo "Config exists";
// Do somthing
}
}
else {
echo 'Failed code:'. $res;
}

PHP condition is being output randomly?

I'm having an issue with one of my conditional statements. The code below is a single text search where the user can enter a string and check a set of files within a directory. The code is working great, although I'm just having a small output glitch.
The 2nd conditional below (just before find_files function) is displaying one echo statement in the middle of my search results. In other words, my results are displaying perfectly, although that 2nd conditional statement appears once within the search results.
Even more weird is that the conditional does works when it's supposed to (i.e. when I enter a string and the string "is not found" within the files), so I'm confused. And I know the conditional is not included in a loop, so why would it display at all during the search?
This is the one last glitch I need to work out and this will work great. Any help would be appreciated.
<?php
$query = $_POST['query'];
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
elseif ((isset($query)) && (!find_files('.'))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
find_files('.');
function find_files($seed) {
if(! is_dir($seed)) return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if(is_dir($path)) { $dirs[] = $path; }
else { if(preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) { check_files($path); }}
}
closedir($dh);
}
}
}
function check_files($this_file)
{
$query = $_POST['query'];
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) { echo("<p style=\"color:darkgray; font-
family:arial\">Could not check $this_file</p>\n"); }
else { if(stristr($content, $str_to_find)) { echo("<p style=\"color:darkgray; font-
family:arial\">$this_file -> contains $str_to_find</p>\n"); }}
unset($content);
}
?>
Simply adding return, won't help. this modified code works and displays no error me
if (!isset($_REQUEST['query']))
{
//Ask for query here :)
//echo "<p style=\"color:darkgray; font-family:arial\">No query specified.</p>";
exit;
}
$query = isset($_REQUEST['query']) ? $_REQUEST['query'] : '';
if (empty($query))
{
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
exit;
}
$filesFound = find_files('.');
if (!$filesFound)
{
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
function find_files($seed)
{
if (!is_dir($seed)) return false;
$found = false;
$dirs = array($seed);
while (NULL !== ($dir = array_pop($dirs)))
{
if ($dh = opendir($dir))
{
while (false !== ($file = readdir($dh)))
{
if ($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path))
{
$dirs[] = $path;
}
else
{
if (preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path))
{
if (!$found)
{
$found = check_files($path);
}
}
}
}
closedir($dh);
}
}
return $found;
}
function check_files($this_file)
{
$query = $_REQUEST['query'];
$str_to_find = $query;
if (($content = file_get_contents($this_file)) === false)
{
echo("<p style=\"color:darkgray; font-family:arial\">Could not check $this_file</p>\n");
return false;
}
else
{
if (stristr($content, $str_to_find))
{
echo("<p style=\"color:darkgray; font-family:arial\">$this_file -> contains $str_to_find</p>\n");
return true;
}
}
}
In your second condition, you are checking to see if the condition: !find_files('.') matches. In order to check that condition, PHP is actually running the function at that time to get its return value, which it then checks for the condition.
On top of that, the find_files() function returns false when it is provided with incorrect input, but does not send a return value when it is successful. That means it does not provide the conditional statement with a value that evaluates to positive, so !find_files('.') evaluates to true, and the echo statement runs.
To fix this, you should just add a return true; as the very last line of your find_files() function.
But I'd also recommend fixing the fact that you're running the function twice. Use something like:
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
else {
$success = find_files('.');
if ((isset($query)) && (!$success)) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
}
Instead of:
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
elseif ((isset($query)) && (!find_files('.'))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
find_files('.');

PHP Repeating Print Statement

I'm having an issue with a PHP print statement that repeats the output continuously for about 40 or 50 times, then stops. I thought it was supposed to print only one line. I'm still somewhat new to PHP, so I don't understand what I'm doing wrong. The code in question is located at the bottom of the snippet.
Thanks in advance.....
<?php
$query = $_POST['query'];
find_files('.');
function find_files($seed) {
if(! is_dir($seed)) return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs))) {
if($dh = opendir($dir)) {
while( false !== ($file = readdir($dh))) {
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if(is_dir($path)) {
$dirs[] = $path;
} else {
if(preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
closedir($dh);
}
}
}
function check_files($this_file) {
$query = $_POST['query'];
$str_to_find = $query;
if ((isset($str_to_find)) && (empty($str_to_find))) {
print '<p>Your search produced no results</p>';
} else {
if(!($content = file_get_contents($this_file))) {
echo("<p>Could not check $this_file</p>\n");
} else {
if(stristr($content, $str_to_find)) {
echo("<p>$this_file -> contains $str_to_find</p>\n");
}
}
unset($content);
}
}
?>
'Your search produced no results' will be printed out once for every file that your loop sees. You should do the check before you call find_files():
if (!isset($str_to_find) || empty($str_to_find)) {
print '<p>Your search produced no results</p>';
} else {
find_files('.');
}
You can then remove that bit of code from check_files().
You have the print statement inside of the check_files() function, which is being called from inside your while... loop. So, yes, it's going to be executed each time that loop executes and the conditions match.
By !== you maybe meant !=?

Categories