0

I have a file in which I store user information. The filename is johndoe (with no extension):

johndoe

John,Doe,JohnDoe,[email protected],abcd1234

I am trying to get John, Doe and JohnDoe from the file in this way:

index.php

$filename = explode("/", $_SERVER["PHP_SELF"])[2];
$userpath = "http://192.168.0.1/member/" . $filename;
$userfile = fopen($userpath,"r");
$username = explode(",",fgets($userfile))[2];
$firstname = explode(",",fgets($userfile))[0];
$lastname = explode(",",fgets($userfile))[1];

where $_SERVER["PHP_SELF"] currently returns /member/johndoe/index.php.

When I print the array explode(",",fgets($userfile)) using print_r(), I get:

Array ( [0] => John [1] => Doe [2] => JohnDoe [3] => [email protected] [4] => abcd1234 )

However, I can't access any of the array elements. For example, echoing explode(",",fgets($userfile))[2] throws an error:

Notice: Undefined offset: 2 in 192.168.0.1/member/johndoe/index.php on line 8

2
  • Why do you read the file multiple times? Read once, store the array resulted by the split in a variable and use it multiple times. fgets will not reset the file, it will try to read the next string. Which will be empty on the second read. Commented Sep 29, 2018 at 20:24
  • Thank you, I didn't know it will read the next line on calling fgets() multiple times. Commented Sep 29, 2018 at 20:30

1 Answer 1

2

After using fgets, the file pointer will move to the byte right next to the last one it just read.

You don't need to call it every time:

$filename = explode("/", $_SERVER["PHP_SELF"])[2];
$userpath = "http://192.168.0.1/member/" . $filename;
$userfile = fopen($userpath,"r");

// Split into parts and assign values to corresponding variables
list($firstname, $lastname, $username) = explode(',', fgets($userfile));

// Alternative syntax (PHP 7.1+)
// [$firstname, $lastname, $username] = explode(',', fgets($userfile));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.