Extraneous blank lines in output of PHP terminal program - php

I am a beginner in PHP. I am writing a file program, but before I could properly use the logic and code it, I got stuck here.
I am writing this PHP program in Linux Ubuntu Terminal. Please don't worry about what I am trying to do with the program. Just helping me understand the error itself would be a great help.
I have a PHP file(a.php) with the following contents:
<?php
$input=fopen($argv[1],"r");
$col=$argv[2]-1;
while(!feof($input))
{
$x=fgets($input);
$array=explode("\t",$x);
}
fclose($input);
?>
Now when I give this in the command prompt:
php a.php 1
I should be getting nothing as an output, but I get around 3 to 4 blank lines. Can anybody tell me why?

The problem must be your file path that is $argv[1].
Try this
$filePath = 'Your file path here';
if( !#$input = fopen($filePath, "r") ) {
die("Could not open $filePath");
}
while(!feof($input))
{
$x=fgets($input);
$array=explode("\t",$x);
}
fclose($input);

Related

PHP doesn't save to files

I have Apache 2 and PHP installed on a Raspberry Pi 1 B+ (RASPBIAN STRETCH LITE
). I have a website running on it with a textbox and a PHP script that is supposed to save the contents of the textbox to a text file on the server when the user submits.
I tryed basically everything but the php script just wont save.
PHP does get the textbox-content (I tested it - it works just fine).
This is my PHP:
<?php
include "code/multiPage/topBar.html";
$dir = "/data/searches.txt";
if ($_REQUEST) {
$input = $_REQUEST["search"];
file_put_contents($dir, $input, FILE_APPEND);
}
?>
PHP is working properly aside from this problem.
The folder has read-write permissions for everyone.
I have also tryed to let PHP create its own folder with code similar to this:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
PHP can't even do that.
Thanks in advance for any help!
I figured it out. The problem was that the webserver didn't have permission to write to the directory. problem solved by running sudo chown -R www-data var/www/html/data thanks for the help! Have a nice day :D
First just try this separately from other code
<?php
file_put_contents("/data/searches.txt", "bla", FILE_APPEND);
?>
if it's not working try to get a last error
echo print_r( error_get_last ( ), true)
In order to make sure that you can write to the file you can always check if it's writable
if(is_writable($dir))
Also for debugging it's nice to see how much bites was written by file_put_contents
so the final code easy to debug will be like this:
<?php
include "code/multiPage/topBar.html";
$dir = "/data/searches.txt";
if(!is_writable($dir)){
echo "cannot write to file";
}
if (!empty($_REQUEST["search"])) {
$input = $_REQUEST["search"];
$bitecount = file_put_contents($dir, $input, FILE_APPEND);
}
echo $bitecount . " bites were written to the file";
?>
There is a thing. If $_REQUEST["search"]="" or $_REQUEST["search"]=null the if($_REQUEST) will be TRUE anyway

Creating a txt file using php in linux

We have few fields in the HTML page and this is being written into a file using php.
The file has the data, however, running a bash script which takes this file with a .txt as extension is not working.
When the file is opened and re-saved manually the bash script will work properly!
I've tried changing the permissions of the file but the bash script is still not using this file. Any help on this is greatly appreciated.
PHP Script:
$name = "test.txt";
$handle = fopen($name, "w");
fwrite($handle, "my message");
fclose($handle);
Bash Script:
INPUT="$1"
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read message number ; do
echo $message # or whaterver you want to do with the $line variable
#j=$[$(line)]
echo $number
echo "$message" | gnokii --sendsms $number --smsc $SMSC
done < $INPUT
IFS=$OLDIFS
You probably want to use fclose($handle) rather than unlink()
Edit OK then, "Because..."
fclose($handle) closes the file referenced by the handle: $handle
unlink() takes a file path string as a parameter, rather than a resource.
If used as intended, unlink() will actually delete the file.
unlink() as mentioned would delete the file. Just created a plain script like this
<?php
$name = "/var/www/test.txt";
$handle = fopen($name, "w");
fwrite($handle, "test,9944");
fclose($handle);
?>
This script works f9 with storing the data. But running bash script on this with the file input as test.txt does nothing. But again opening and saving with the same file name and it works.
finally got the answer its the end of file that is missing in text file that is created by php. anyway thank you all for contributing.

Compile a .php file which takes in 4 parameter from another php file?

I have a script which when compiled from the terminal passing the parameters something like this "php compile.php arg1 arg2 arg3 arg4" on the terminal starts displaying the output result which is something like 1)file created 2) file inclusion. etc.
Now I am trying to use system(php compile.php arg1 arg2 arg3 arg4) from another php file, but it will not execute the php file or will not show an output.
For example i even tried to create hello.php------
and tried using system(php hello.php); but it did not output anything on the browser.
Can anyone please help me out, I am new to php. Thanks.
make sure you react on errors from the system call. Your actual code might also help. The following example works without problems on my box.
<?php
$file = fopen('/tmp/written.php', 'w');
fwrite($file, '<?php echo "Hello from written.php\n"; ?>');
fclose($file);
echo "calling written.php\n";
if (!system('php /tmp/written.php'))
die("something wrong\n");
else
exit("all good\n");
?>

Can't execute external process with PHP

I have the following code
function generate_pdf() {
$fdf_data_strings = $this->get_hash_for_pdf();
#$fdf_data_names = array('49a' => "yes");
$fdf_data_names = array();
$fields_hidden = array();
$fields_readonly = array();
$hud_pdf = ABSPATH.'../pdf/HUD3.pdf';
$fdf= forge_fdf( '',
$fdf_data_strings,
$fdf_data_names,
$fields_hidden,
$fields_readonly );
/* echo "<pre>";
print_r($fdf);
echo "</pre>";
die('');
*/
$fdf_fn= tempnam( '.', 'fdf' );
$fp= fopen( $fdf_fn, 'w' );
if( $fp ) {
fwrite( $fp, $fdf );
//$data=fread( $fp, $fdf );
// echo $data;
fclose( $fp );
header( 'Content-type: application/pdf' );
header( 'Content-disposition: attachment; filename=settlement.pdf' ); // prompt to save to disk
passthru( 'pdftk HUD3.pdf fill_form '. $fdf_fn.' output - flatten');
unlink( $fdf_fn ); // delete temp file
}
else { // error
echo 'Error: unable to open temp file for writing fdf data: '. $fdf_fn;
}
}
}
is there anything wrong with it?
the problem is, I have installed pdftk
runing whereis pdftk gives me '/usr/local/bin/pdftk'
physically checked the location, pdftk is there at the said location..
using terminal, if i run pdftk --version or any other command, it runs
if I use php like passthru('/usr/local/bin/pdftk --version') nothing is displayed
if I used php like system("PATH=/usr/local/bin && pdftk --version"); it says '/usr/local/bin /pdftk :there is no directory of file '
when I run this function script , prompt for file download pops, but when i save it, nothng is saved,
i have checked permission for this folder and changed it 0755, 0766, 0777, 0666 i have tried all, nothng works
For 3 days, i am striving to get over it, and I have asked question regarding this too, but Can't figure out what the hell is going on with me.
Can somebody help me before i strike my head with wall?
The pasthru function does not execute the program through the shell.
Pass the exact path into the passthru command.
E.g.
passthru( '/usr/local/bin/pdftk HUD3.pdf fill_form '. $fdf_fn.' output - flatten');
or
passthru( '/usr/local/bin/pdftk' . $hud_pdf . 'fill_form '. $fdf_fn.' output - flatten');
If this still doesn't work test using
<?php passthru("/path/to/pdftk --help"); ?> where /path/to/pdftk is your path returned by which or where is, to ensure path is correct.
If path is correct then the issue may be related to permissions either on the temporary directory you tell pdftk to use or the permissions on the pdftk binary with regards to the apache user.
If these permissions are fine you can verify the pdftk starts up from php but hangs from running your command, then might be able to try the workaround listed here.
Further documentation on passthru is avaliable passthru PHP Manual.
As a side note, the putenv php function is used to set environment variables.
E.g. putenv('PATH='.getenv('PATH').':.');
All 3 PHP functions: exec(), system() and passthru() executes an external command, but the differences are:
exec(): returns the last line of output from the command and flushes nothing.
shell_exec(): returns the entire output from the command and flushes nothing.
system(): returns the last line of output from the command and tries to flush the output buffer after each line of the output as it goes.
passthru(): returns nothing and passes the resulting output without interference to the browser, especially useful when the output is in binary format.
Also see PHP exec vs-system vs passthru SO Question.
The implementation of these functions is located at exec.c and uses popen.
I had the same issue and this is working after lots of experiments :
function InvokePDFtk($pdf_tpl, $xfdf,$output){
$params=" $pdf_tpl fill_form $xfdf output $output flatten 2>&1";
$pdftk_path=exec('/usr/bin/which /usr/local/bin/pdftk');
$have_pdftk= $pdftk_path=='/usr/local/bin/pdftk' ;
$pdftk_path=$have_pdftk ? $pdftk_path : 'pdftk ';
exec($pdftk_path.$params,$return_var);
return array('status'=> $have_pdftk,
'command' =>$pdftk_path.$params, 'output'=>$return_var);
}
hope this might give you some insight . (change according to your needs)
Completing Appleman answer, those 3 functions can be considered as dangerous, because they allow you execute program using php, thus an attacker that exploited one of your script if you are not careful enougth. So in many php configuration that want to be safe they are disabled.
So you should check for the disable_functions directive in you php.ini(and any php configuration file) and see if the function you use is disabled.
Perhaps you should keep fclose out of the if statement, make sure you have it directed to the right file! :)
Is your web server chrooted? Try putting the executable into a directory that is viewable by the server.
Play around around with safe mode and definitely check your web server log file, normally in:
/var/log/apache2/error.log

Gettin error when running simple php script

I'm trying to run this simple script:
<?php
$PHP_PATH = "c:\Program Files (x86)\PHP\\";
$CLIENTPATH = dirname(__FILE__)."\Client.php";
$SERVER = "http://localhost:8080/mobile/Server";
$handle = popen("C:\WINDOWS\system32\cmd /C start ".$PHP_PATH." -f ".$CLIENTPATH." ".$SERVER, 'r');
?>
But I always get this Windows messagebox error:
Windows cannot find c:\program. Please make sure you typed the name correctly and then try again.
Searching on google I also find this thread about this error, but the meassures are I litlle drastic I guess.
So the problem its in my code ? Or there can be something else wrong ?
Thanks.
You need to escape the whitespaces in $PHP_PATH = "c:\Program Files (x86)\PHP\\";!

Categories