Weird PHP Problem

Associate
Joined
27 Apr 2004
Posts
2,377
I've written a script in php that's run from the command line version of php. The script itself runs fine but part of its job is to produce an output which is written to a file.

When the script has finished running, I ask the user to enter a file name to save as using the following:

PHP:
file_put_contents(fgets(STDIN), "(file data goes here)");

However it simply does not work and tells me the filename [fgets(STDIN)] is not valid.

I've tried the following but still get the same error.

PHP:
$filename = fgets(STDIN);
file_put_contentss($filename, "(file data goes here)");

I know that fgets(STDIN) is working because I use it in other parts of the script. What am I doing wrong?

It may be worth me mentioning that I'm using version 4 something, and I'm aware file_put_contents() is new in php 5; however, I define the function file_put_contents() within the script and I know it works.

Thanks, null :)
 
PHP:
	function file_put_contents($file, $string) {
		$file = fopen($file, 'w');
		fwrite($file, $string);
		fclose($file);
	}

Maybe it wasn't clear, it's not taking input and writing it to a file. The file contents is made by the script and I've succesfully tested that part including writing to file.

The problem is when I try and set the filename to save it as by, both when I take a user input (as in the code I quoted):
PHP:
fgets(STDIN)

and when I assign the filename to a variable in the script:
PHP:
$filename = "test";
file_put_contentss($filename, "(file data goes here)");

Hope this is clearer :o

Thanks, null :)
 
Oops mistake on my last post. I said both fgets(STDIN) and $filename = "test" don't work. What I actually meant was that hard coding it *does* work. :o

I've tried var_dump and the problem is it's adding a new line on the end of the inputted filename. However, trim() doesn't seem to do anything :confused:
 
Anything else that could be causing it to start a new line then... though I still can't see why it even does so :confused:

Thanks, null :)

edit - Perhaps a stupid suggestion but could it be caused by pressing enter at the command line to submit the input?
 
Last edited:
Fixed it. Was my mistake. I hadn't fully read up on trim() and assumed it acted on the string you tell it globally, rather than returing a value.

So I was doing this:
PHP:
$filename = fgets(STDIN);
trim($filename);
When it should have been
PHP:
$filename = trim(fgets(STDIN));
So.. my mistake. That's why I keep doing things like this - making random scripts doing random things - I learn best from doing :p

Thanks, null :)
 
Back
Top Bottom