1

I'm trying to make a php site, but I have a problem where I can't use included variables in included files!

index.php

<?php
require 'core/init.php';
?>

init.php

<?php
require 'config.php';

require 'db/connect.php';
?>

config.php

<?php
// Config
// The Title of the site
$site_title = 'php-site';
$site_desc = 'A awesome PHP site!';
$site_keywords = 'php, html5, css3, awesome';
$site_author = 'erty5000';

// Database - MySQL
// MySQL host
$db_host = 'localhost';

// MySQL username
$db_username = 'myuser';

// MySQL password
$db_password = 'mypassword';

// MySQL database
$db_database = 'mydb';

// Error to display at the top of the page if a connection problem occured
$db_connect_error = 'Sorry, we\'re experiencing connection problems.';
?>

connect.php

<?php
mysql_connect($db_host, $db_username, $db_password) or die($db_connection_error);
mysql_select_db($db_database) or die($db_connection_error);
?>

The errors I get is

Notice: Undefined variable: db_host in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2

Notice: Undefined variable: db_username in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2

Notice: Undefined variable: db_password in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2

Warning: mysql_connect(): Access denied for user ''@'localhost' (using password: NO) in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2

Notice: Undefined variable: db_connection_error in C:\xampp\htdocs\w\php-site\core\db\connect.php on line 2

Sorry for such a long post, but I'm really hoping someone could help me!

5
  • 3
    And what's in db\connect.php? Commented Mar 10, 2013 at 22:12
  • Sorry added connect.php now Commented Mar 10, 2013 at 22:14
  • What if you replace require 'config.php'; by require __DIR__ . '/config.php';? Commented Mar 10, 2013 at 22:15
  • Worked!! Thank you very much Niko!! :) Commented Mar 10, 2013 at 22:17
  • You're welcome! I've posted an answer with a bit more of an explanation. Commented Mar 10, 2013 at 22:20

1 Answer 1

1

You seem to have another file named config.php either on the include path or in the directory of index.php. A explained in the documentation:

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.

This problem can be easily solved by specifying the absolute path to the file, i.e.:

require(__DIR__ .'/config.php');
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.