Manual wp_install() difficulties - php

I am trying to automatically install a WordPress distribution in PHP with the following code:
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
When I manually run wp_install() [/wp-admin/includes/upgrade.php], I get this error:
Fatal error: Call to a member function flush_rules() on a non object in /home/username/public_html/wp-admin/includes/upgrade.php on line 85
After looking at the WordPress source code, it appears that $wp_rewrite is trying to call flush_rules() when $wp_rewrite itself doesn't exist.
Another strange twist is that this is virtually the same code as wordpress-cli-installer. My wp-config.php file is automatically generated and ready.
How come wordpress-cli-installer's code works but mine does not?
EDIT:
After a lot of trial and error, I found out that my code was not working because it was defined and executed in a function. After I separated the code from the function and executed it, it worked. However, that raises another question. Is it even possible to execute the above code inside of a function? I have tried using the $GLOBALS += get_defined_vars(); hack after the require_once statements, but that doesn't seem to do anything. In other words:
<?php
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
// ^ This works.
// v This won't work.
function run(){
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
}
run();
?>

How do I use the require_once inside of a function while still being able to access and manage the globals?
That idea is wrong in general. You can make global only required variables (which might change from version to version). But the 'dirty' way is
function make_global()
{
$test_var = "I'm local";
$GLOBALS += get_defined_vars();
}
var_dump(isset($test_var));
make_global();
var_dump(isset($test_var));

Related

Joomla Call to a member function get() on null

I have very little php knowledge. I know I'm doing something wrong, but what?
I'm adding the sass compiler from Joomla Master Bootstrap template into my own Joomla template. It works, but not as it should. I can't turn it on or off in the backend.
The code in Masterbootstrap is this:
include 'includes/params.php';
if ($params->get('compile_sass', '0') === '1') {
require_once "includes/sass.php";
}
In my template I don't have params.php, but /functions/tpl-init.php. I added the variable $compile_sass there. My code looks like this:
require_once __DIR__ . '/functions/tpl-init.php';
if ($params->get('compile_sass', '0') === '1') {
require_once "includes/html/sass.php";
}
Doesn't work. I get the error: Call to a member function get() on null
So I changed this into:
require_once __DIR__ . '/functions/tpl-init.php';
require_once "includes/html/sass.php";
That works, but now the compiler is permanently on.
What should I do to correct this?
To get template params from outside the template you need to do this
Template parameters from outside a template
$app = JFactory::getApplication('site');
$temp = $app->getTemplate(true);
$param = $temp->params->get('compile_sass', '0');
Remember the Masterbootstrap template should be active.
To get any template param you need to do this
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query ->select('params')
->from('#__template_styles')
->where('`template` = ' . $db->q('masterbootstrap')) // Check Spelling of template
->where('client_id = 0'); // client_id = 0 for Site and client_id = 1 for Admin
$db->setQuery($query);
$params = json_decode($db->loadResult());
echo $params->compile_sass;
Better is to create a similar param in your own template using your templateDetails.xml file rather than depending on the external template.
I got help from a friend. He solved it in a minute. It's so simple... it usually is, after you found the solution:
require_once __DIR__ . '/functions/tpl-init.php';
if ($compile_sass === '1')
{
require_once "includes/html/sass.php";
}

'require' work but 'require_once' doesn't work

When I use require_once or include_once to include a file it does not work, while when I use require or include it works fine.
public function ParseURL() {
require_once (APP_PATH . "config/config.php");
$this->url_as_parts = explode('/', $this->url);
$class = isset($this->url_as_parts[0]) ? $this->url_as_parts[0] : $config['default_controller'];
$method = isset($this->url_as_parts[1]) ? $this->url_as_parts[1] : "index";
$parms = isset($this->url_as_parts[2]) ? $this->url_as_parts[2] : "";
if (!class_exists($class)) {
trigger_error("The class {$class} not exists <br/>");
exit;
}
$controller = Object::get($class);
if (!method_exists($controller, $method)) {
header('HTTP/1.0 404 Not Found');
include(SYSTEM_PATH . "languages/" . $config['system_language'] . "/errors/404_not_found.html");
exit;
}
if (empty($parms)) {
$controller->{$method}();
} else {
$parms_array = array_slice($this->url_as_parts, 2);
call_user_func_array(array($controller, $method), $parms_array);
}
}
The following line does not produce an error and the path is correct
require_once (APP_PATH . "config/config.php"); but I cant access $config['system_language'] which is inside the file config.php.
Note that when I change the require_once to require or include, everything is OK.
As comes from require_once description - file required only once
Any other require_once of this file will not work.
And you obviously run you function ParseURL more than once. So, your require_once not working on second and consecutive calls.
So, you can use just require or, as I see this is part of a class, create, for example, a wrapper method which will assign config data to your class variable. I.e:
public function getConfig()
{
$this->config = require_once('FILE');
}
In this case your config file should return array or object of config variables.
Can it be that something else includes config/config.php, and then redefines/overwrites the variable $config?
The difference between require_once() and is regular counterparts (include() etc) is that require_once() only includes (and executes, if applicable) something if it hasn't been included before.
This might be because you are already loading config/config.php somewhere before in your code.
Calling require_once(APP_PATH . "config/config.php"); checks that the file config.php already is included and hence does not include it inside that function.
That is the reason your function does not have access to $config variable.
Hope that helps.

Undefined variable error on a variable inside an included file

I'm including this file to collect one of its variables. File path is correct and i don't get file include errors. But when i try to print a variable inside that file it gives undefined variable error. Following is the code.
include_once($path . "folder/file.php");
echo($code);
There is a php class. inside the class there is a login function . Within that function I'm including another file assume it's funtions.php.
functions.php has above code in it.
Inside functions.php file i include this file which contains the variable i'm looking for (assume it's test.php).
test.php looks like this (inside php tags)
$code="something";
$another_variable="something else";
so now like i said before when i include this inside functions.php and print $code it why does it gives an undefined error?
Full code
function log($user, $pass) {
global $config;
$this->get_available_accounts();
if (isset($this->Users_obj[$user])) {
if ($this->Users_obj[$user]->userName == $user && $this->Users_obj[$user]->passWord == $pass) {
delete_cache_full();
$_SESSION['username'] = $user;
$_SESSION['log'] = true;
$_SESSION['usergroup']=$this->Users_obj[$user]->level;
$this->set_permission_session($_SESSION['usergroup']);
include_once $config->path . 'config.php';
$newUpdate2=showUpdates2();
if(!empty($newUpdate2)){
$_SESSION['updateremindlater']=$newUpdate2['date'];
}
//file
include_once $config->path . 'functions.php';
$func = new UserFuncs();
$func->validate();
include_once $config->path . 'view/ViewDashboard.php';
return true;
}
}
thats the function im including this file into. include_once $config->$path . 'functions.php'; includes functions.php file
functions.php looks like this
include_once($path. "folder/config.php");
echo($code);
and config.php looks like
$code = "ERGERW2342HV3453WERWEER";
$host_name = "SERV345WERFDGDDFGDGF";
$return_code = "DFGDFSDGFS";
$vurl = "YUIYUJHGJ";
$next_val ="AWERFDFVDV";
$val_exp = "NMGHJGJGH";
Help much appreciated!
Just guessing that you've included config.php somewhere else before, and that it's not being included again due to include_once. Therefore the variables are not created in the scope you're including it in the second time.
This could be a problem with variable scope, where you are trying t access the variable from somewhere (e.g. a function) where it is not available to that particular object (you did mention that you included the file within a class).
I agree with deceze and hakre, it's very hard to answer this question without seeing your code.

Require_once doesn't seem to affect all functions?

Everything was working fine in my little project, until I decided to clean up a little bit and moved database-related php-files to their own folder. Then things went strange.
I am trying to use two functions here:
function getEntries () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error);
echo $dbHost; // prints host
return $result;
}
function getBiggestMonth () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
echo $dbHost; // prints nothing! why?
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error); // this line does not run, of course.
return $result;
}
I use another function in a different file (and folder) to call these functions, that starts like this:
function listTasks() {
require_once("db/mysqliFunctions.php");
// Get entries using mysqli.
$tasks = getEntries();
echo "<pre>";
var_dump($tasks);
echo "</pre>"; // program works fine this far.
$bm = getBiggestMonth(); // program breaks somehow during this function call.
My variables are in a php-file like so:
<?php
$dbHost = "host";
$dbUname = "username";
$dbPwd = "password";
$dbName = "databasename";
?>
If I switch the funtion's call order, then getBiggestMonth() runs fine and the other one won't. Also, all of this worked fine when all the files were located in the same folder (the functions were then static functions inside a class, but that shouldn't be an issue, the same problem persists here), so I dont understand how possible variable scope can be different here, and require_once should take care of other things. Help?
This is because you are using require_once. It will only include the configuration once. You can change it to use require so that it will work as you expect.
The require_once() statement is identical to require() except PHP will
check if the file has already been included, and if so, not include
(require) it again.
You are using require_once to pull in a file into the scope of the getEntries() function. PHP keeps a record of the files that have been required in so when you then call require_once in getBiggestMonth() it knows it has already been included in getEntries(). Because it has already been included it does not require the file in again so you don't get your variables in your getBiggestMonth() scope.
require_once does not have anything to do with variables it just monitors the files that have been included into the current PHP process.
The echo statement after the return in getEntries() wont obviously work as the function exits after the return.

Yet another 'Call to a member function on a non-object' problem

I have a html page that calls a php object to get some data back from the database. It works fine, but the script was getting unwieldy so I decided to break some of it out into a bunch of functions.
So I have the following files:
// htdocs/map.php
<?php
include("config.php");
include("rmap.php");
$id = 1;
$gamenumber = getGameNumber($id);
echo $gamenumber;
?>
// htdocs/config.php
<?php
$_PATHS["base"] = dirname(dirname(__FILE__)) . "\\";
$_PATHS["includes"] = $_PATHS["base"] . "includes\\";
ini_set("include_path", "$_PATHS[includes]");
ini_set("display_errors", "1");
error_reporting(E_ALL);
include("prepend.php");
?>
// includes/prepend.php
<?php
include("session.php");
?>
// includes/session.php
<?php
includes("database.php");
class Session {
function Session() {
}
};
$session = new Session;
?>
// includes/database.php
<?php
include("constants.php");
class Database {
var $connection;
function Database() {
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
}
function query($query) {
return mysql_query($query, $this->connection);
}
};
/* Create database connection */
$database = new Database;
?>
// includes/rmap.php
<?php
function getGameNumber($id) {
$query = "SELECT gamenumber FROM account_data WHERE usernum=$id";
$result = $database->query($query); // line 5
return mysql_result($result, 0);
}
?>
And constants has a bunch of defines in it (DB_USER, etc).
So, map.php includes config.php. That in turn includes prepend.php which includes session.php and that includes database.php. map.php also includes rmap.php which tries to use the database object.
The problem is I get a
Fatal error: Call to a member function on a non-object in
C:\Develop\map\includes\rmap.php on line 5
The usual cause of this is that the $database object isn't created/initialised, but if I add code to show which gets called when (via echo "DB connection created"; and echo "using DB connection";) they are called (or at least displayed) in the correct order.
If I add include("database.php") to rmap.php I get errors about redefining the stuff in constants.php. If I use require_once I get the same errors as before.
What am I doing wrong here?
$database is not in the scope of function GetGameNumber.
The easiest, though not necessarily best, solution is
<?php
function getGameNumber($id) {
global $database; // added this
$query = "SELECT gamenumber FROM account_data WHERE usernum=$id";
$result = $database->query($query); // line 5
return mysql_result($result, 0);
}
?>
global is deemed not perfect because it violates the principles of OOP, and is said to have some impact on performance because a global variable and all its members are added to the function's scope. I don't know how much that really affects performance, though.
If you want to get into the issue, I asked a question on how to organize such things a while back and got some good answers and links.
You need to include
global $database;
at the top of getGameNumber(), since $database is defined outside of getGameNumber itself
Your $database varibleis not accessible from the function's scope automatically. You might need to declare it as global $database; in the function.
Scopes in PHP are explained in the documentation: http://de3.php.net/manual/en/language.variables.scope.php
Please also mind that PHP 4and MySQL3 are out of support for a looooong time and might contain security problems and other unfixed issues.

Categories