Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does file_get_contents() return the error "Filename cannot be empty"?

Tags:

php

I'm pretty much a complete newbie to PHP. My background is C/C++ and C#. I'm trying to object orient-ify some simple PHP code, but I'm doing something wrong.

Class code:

class ConnectionString
{
  public $String = "";
  public $HostName = "";
  public $UserName = "";
  public $Password = "";
  public $Database = "";

  function LoadFromFile($FileName)
  {
    $this->String = file_get_contents($Filename);
    $Values = explode("|", $this->String);
    $this->HostName = $Values[0];
    $this->UserName = $Values[1];
    $this->Password = $Values[2];
    $this->Database = $Values[3];
  }
}

Calling code:

$ConnectionString = new ConnectionString();
$FileName = "db.conf";
$ConnectionString->LoadFromFile($FileName);
print('<p>Connection Info: ' . $Connection->String . '</p>');

I'm getting ann error on the file_get_contents($Filename) line stating: Filename cannot be empty. If I hard-code the filename in place of $Filename, then I simply get all empty strings for the fields.

What simple concept am I missing?

like image 946
John Kraft Avatar asked Dec 10 '09 16:12

John Kraft


2 Answers

You've got the case wrong:

file_get_contents($Filename);

should be

file_get_contents($FileName);

You should turn on Notices, either in your php.ini file or using error_reporting()

like image 186
Greg Avatar answered Sep 19 '22 00:09

Greg


Variables in PHP are case-sensitive. You've defined $FileName as a parameter to the LoadFromFile() method, but you used $Filename on the first line of that method. For more information about PHP variables:

http://www.php.net/manual/en/language.variables.basics.php

There are a few things you can do to avoid this problem in the future:

  • Use an IDE, such as Eclipse PDT, that support auto-completion of variables.
  • Configure error_reporting to display all types of errors (E_ALL).
like image 39
Jordan Ryan Moore Avatar answered Sep 21 '22 00:09

Jordan Ryan Moore