John smith
John smith

Reputation: 1

Opening files via CLI [PHP]

Here is my code

<?php
$file = fopen($argv[0],"r");
echo fgets($file);
fclose($file)
?>

Here is my output

$ php mail.php test.txt
<?php

What i want it to do is display the contents of test.txt.

$ ls | grep test.txt
test.txt

Just to prove i actually have test.txt

I would also like to know how to parse the data from this so, line one would have its own variable.

Upvotes: 0

Views: 142

Answers (1)

CodeBoy
CodeBoy

Reputation: 3300

See http://php.net/manual/en/reserved.variables.argv.php

The first argument $argv[0] is always the name that was used to run the script.

In other words, $argv[0] will be the name of your PHP file, mail.php in your case (echo it out). What you want is $argv[1] as in $file = fopen($argv[1],"r");.

To read the entire file into a string, use file_get_contents() (see doc).

To read the entire file into an array, one line per array entry, use file() (see doc).

Upvotes: 1

Related Questions