Global PHP Database File - php

I'm currently making a PHP script and I need some help. Firstly it allows the user to enter database information on a file called install.html which presents a form to the user. The form uses GET to then send that information to a second install file which creates the relevant tables, enters the information into the tables and then allows the user to carry on with the script.
However I was wondering. In the second install file I used:
$databaseServer = $_GET["databaseServer"];
in order to get the information that was entered into the form. Is there anyway I can then send these variables ($databaseServer, $databaseName, $databaseUser, $databasePassword) to another file called db.php that I will include on top of every file I write that requires an SQL connection. I have looked at GLOBAL variables but they didn't work properly. I could have been doing something wrong however.

You could save a configuration array to a file:
<?php
class Config
{
public $path;
public function __construct($path)
{
$this->path = $path;
}
public function store($config)
{
$dump = var_export($config, true);
$dump = '<?php return ' . $dump . ';';
file_put_contents($this->path, $dump);
}
public function retrieve()
{
return include $this->path;
}
}
// Build your config array
$config['database'] = $_GET['database'];
$config['username'] = $_GET['username'];
// Make sure your server can write to this path
$configurator = new Config(__DIR__ . '/config/config.php');
// Save your config
$configurator->store($config);
// Get your config later
$read_config = $configurator->retrieve();
// Check our config against the saved version
assert($config == $read_config);
var_dump($read_config);

Related

Call script based on variable name

I have a parent function that is passed a variable called $scriptName. Depending on what is stored in $scriptName, I want to call the corresponding script.
I have a file called childOneScript.php
If $scriptName=="childOne", how do I call childOneScript.php?
You can just use the normal require
require_once $scriptName . 'Script.php';
Keep in mind however that if the script does not exist PHP will raise a fatal error, so you should be checking that the script does indeed exist.
/**
Assumes that $name does not contain the PHP extension and
this function works with relative paths.
If the file does not exist, returns false, true otherwise
*/
function loadScript($name) {
$name = $name . '.php';
if (!file_exists($name) || !is_readable($name)) {
// raise an error, throw an exception, return false, it's up to you
return false;
}
require_once $name;
return true;
}
$loaded = loadScript('childOneScript');
Alternatively you can use include, PHP will only raise a warning if it can't find the script.
There are a few security concerns with the above function. For example if the user is allowed to define the value of $scriptName an attacker could use it to read any file that is readable to the web server user.
Here is an alternative that limits the number of files that can be dynamically loaded to just the files that need be loaded in this manner.
class ScriptLoader {
private static $whiteList = array(
// these files must exist and be readable and should only include
// the files that need to be loaded dynamically by your application
'/path/to/script1.php' => 1,
'/path/to/script2.php' => 1,
);
private function __construct() {}
public static function load($name) {
$name = $name . '.php';
if (isset(self::$whiteList[$name])) {
require_once $name;
return true;
}
// the file is not allowed to be loaded dynamically
return false;
}
}
// You can call the static method like so.
ScriptLoader::load('/path/to/script1'); // returns true
ScriptLoader::load('/path/to/script2'); // returns true
ScriptLoader::load('/some/other/phpfile'); // returns false
You can simply do:
if ($scriptName=="childOne"){
require_once(childOneScript.php);
}
The require_once statement will check if the file has already been included, and if so, not include (require) it again.
Readup: require_once() | PHP
Just use the include statement inside the If condition.
if $scriptName == "childOne" {
include childOneScript.php;
}
You could use the include or require methods in PHP
<?php
function loadScript($scriptName) {
if ($scriptName=="childOne") {
include("childOneScript.php");
}
}
?>
Keep in mind though that the included script is included where you load it. So it's inside the loadScript function. That means you cannot access it's content outside its scope.

Variable Variables in PHP from required / included files

I am writing a MVC Framework (for the purpose of learning and discovery as opposed to actually intending to use it) and I have came across a slight problem.
I have a config.php file:
$route['default'] = 'home';
$db['host'] = 'localhost';
$db['name'] = 'db-name';
$db['user'] = 'user-name';
$db['pass'] = 'user-pass';
$enc_key = 'enc_key'
I load these via a static method in my boot class:
public static function getConfig($type) {
/**
* static getConfig method gets configuration data from the config file
*
* #param string $type - variable to return from the config file.
* #return string|bool|array - the specified element from the config file, or FALSE on failure
*/
if (require_once \BASE . 'config.php') {
if (isset(${$type})) {
return ${$type};
} else {
throw new \Exception("Variable '{$type}' is undefined in " . \BASE . "config.php");
return FALSE;
}
} else {
throw new \Exception("Can not load config file at: " . \BASE . 'config.php');
return FALSE;
}
}
and then load the route like so:
public function routeURI($uri) {
...
$route = $this::getConfig('route');
...
}
which catches the exception:
"Variable 'route' is undefined in skeleton/config.php"
now, it works fine if I make the config.php file like so
$config['route']['default'] = 'home'
...
and change the two lines in the method like so:
if (isset($config[$type])) {
return $config[$type];
I have also tried using $$type instead of ${$type} with the same problem.
Is there something I am overlooking?
As written, this function can be called only once, because it uses require_once and on subsequent calls you won't bring in the local variables defined in config.php anymore. I suspect you are getting this error on your second call to getConfig().

Getting WordPress database name/username/password with PHP

I'm writing a WordPress plug-in and need to read the database name, username, and password (In order to do a sql dump). Is this possible?
Thanks-
Yes, they are defined in wp-config.php
Database Name: DB_NAME
Database User: DB_USER
Database password: DB_PASSWORD
Database Host: DB_HOST
They are define. See you wp-config.php in the root directory of Wordpress
Wordpress has some fairly goofy stuff going on throughout its OO code, this isn't the first one I've encountered as we dig deeper into the internals with each successive project at Moxune. See WP_User::__set doesn't persist custom fields as it claims.
The goofiness I refer to here of course is that something like the table prefix, aka wpdb::prefix is a public member variable, however things like dbname, dbpassword, and dbhost are protected and there are no public accessor methods.
I'm sure one of the Wordpress core devs will try to argue some rationale for it, but in the meantime may as well use some good 'ol OO to cope. My suggestion, a decorator.
class SaneDb
{
private $_oDb;
public function __construct(wpdb $oDb)
{
$this->_oDb = $oDb;
}
public function __get($sField)
{
if($sField != '_oDb')
return $this->_oDb->$sField;
}
public function __set($sField, $mValue)
{
if($sField != '_oDb')
$this->_oDb->$sField = $mValue;
}
public function __call($sMethod, array $aArgs)
{
return call_user_func_array(array($this->_oDb, $sMethod), $aArgs);
}
public function getDbName() { return $this->_oDb->dbname; }
public function getDbPass() { return $this->_oDb->dbpassword; }
public function getDbHost() { return $this->_oDb->dbhost; }
}
Then atop your plugin code (functions.php) setup a global in similar vein to wpdb.
global $sanedb;
$sanedb = new SaneDb($wpdb);
From there, just use $sanedb within your plugin instead of $wpdb.
Lastly, getting ahold of the database name et al.
$sanedb->getDbName();
This is super simple now. You can create a PHP file and use the following code.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
// We need the WordPress Database Credentials
global $wpdb;
$user = $wpdb->dbuser;
$pass = $wpdb->dbpassword;
$name = $wpdb->dbname;
If you need other data just do a print_r on the wpdb variable and you'll see everything inside of there.

How to do file uploads with PHP and the Zend Framework?

I am using Zend Framework 1.9.6. I think I've got it pretty much figured out except for the end. This is what I have so far:
Form:
<?php
class Default_Form_UploadFile extends Zend_Form
{
public function init()
{
$this->setAttrib('enctype', 'multipart/form-data');
$this->setMethod('post');
$description = new Zend_Form_Element_Text('description');
$description->setLabel('Description')
->setRequired(true)
->addValidator('NotEmpty');
$this->addElement($description);
$file = new Zend_Form_Element_File('file');
$file->setLabel('File to upload:')
->setRequired(true)
->addValidator('NotEmpty')
->addValidator('Count', false, 1);
$this->addElement($file);
$this->addElement('submit', 'submit', array(
'label' => 'Upload',
'ignore' => true
));
}
}
Controller:
public function uploadfileAction()
{
$form = new Default_Form_UploadFile();
$form->setAction($this->view->url());
$request = $this->getRequest();
if (!$request->isPost()) {
$this->view->form = $form;
return;
}
if (!$form->isValid($request->getPost())) {
$this->view->form = $form;
return;
}
try {
$form->file->receive();
//upload complete!
//...what now?
$location = $form->file->getFileName();
var_dump($form->file->getFileInfo());
} catch (Exception $exception) {
//error uploading file
$this->view->form = $form;
}
}
Now what do I do with the file? It has been uploaded to my /tmp directory by default. Obviously that's not where I want to keep it. I want users of my application to be able to download it. So, I'm thinking that means I need to move the uploaded file to the public directory of my application and store the file name in the database so I can display it as a url.
Or set this as the upload directory in the first place (though I was running into errors while trying to do that earlier).
Have you worked with uploaded files before? What is the next step I should take?
Solution:
I decided to put the uploaded files into data/uploads (which is a sym link to a directory outside of my application, in order to make it accessible to all versions of my application).
# /public/index.php
# Define path to uploads directory
defined('APPLICATION_UPLOADS_DIR')
|| define('APPLICATION_UPLOADS_DIR', realpath(dirname(__FILE__) . '/../data/uploads'));
# /application/forms/UploadFile.php
# Set the file destination on the element in the form
$file = new Zend_Form_Element_File('file');
$file->setDestination(APPLICATION_UPLOADS_DIR);
# /application/controllers/MyController.php
# After the form has been validated...
# Rename the file to something unique so it cannot be overwritten with a file of the same name
$originalFilename = pathinfo($form->file->getFileName());
$newFilename = 'file-' . uniqid() . '.' . $originalFilename['extension'];
$form->file->addFilter('Rename', $newFilename);
try {
$form->file->receive();
//upload complete!
# Save a display filename (the original) and the actual filename, so it can be retrieved later
$file = new Default_Model_File();
$file->setDisplayFilename($originalFilename['basename'])
->setActualFilename($newFilename)
->setMimeType($form->file->getMimeType())
->setDescription($form->description->getValue());
$file->save();
} catch (Exception $e) {
//error
}
By default, files are uploaded to the system temporary directory, which means you'll to either :
use move_uploaded_file to move the files somewhere else,
or configure the directory to which Zend Framework should move the files ; your form element should have a setDestination method that can be used for that.
For the second point, there is an example in the manual :
$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
->setDestination('/var/www/upload')
->setValueDisabled(true);
(But read that page : there are other usefull informations)
If you were to move the file to a public directory, anyone would be able to send a link to that file to anyone else and you have no control over who has access to the file.
Instead, you could store the file in the DB as a longblob and then use the Zend Framework to provide users access the file through a controller/action. This would let you wrap your own authentication and user permission logic around access to the files.
You'll need to get the file from the /tmp directory in order to save it to the db:
// I think you get the file name and path like this:
$data = $form->getValues(); // this makes it so you don't have to call receive()
$fileName = $data->file->tmp_name; // includes path
$file = file_get_contents($fileName);
// now save it to the database. you can get the mime type and other
// data about the file from $data->file. Debug or dump $data to see
// what else is in there
Your action in the controller for viewing would have your authorization logic and then load the row from the db:
// is user allowed to continue?
if (!AuthenticationUtil::isAllowed()) {
$this->_redirect("/error");
}
// load from db
$fileRow = FileUtil::getFileFromDb($id); // don't know what your db implementation is
$this->view->fileName = $fileRow->name;
$this->view->fileNameSuffix = $fileRow->suffix;
$this->view->fileMimeType = $fileRow->mime_type;
$this->view->file = $fileRow->file;
Then in the view:
<?php
header("Content-Disposition: attachment; filename=".$this->fileName.".".$this->fileNameSuffix);
header('Content-type: ".$this->fileMimeType."');
echo $this->file;
?>
$this->setAction('/example/upload')->setEnctype('multipart/form-data');
$photo = new Zend_Form_Element_File('photo');
$photo->setLabel('Photo:')->setDestination(APPLICATION_PATH ."/../public/tmp/upload");
$this->addElement($photo);

How to call WordPress functions in a custom PHP script

I have a PHP script I want to use for creating a new blog in WPMU. I am having trouble calling WordPress functions like wpmu_create_user and wpmu_create_blog.
My hope is to get this script running as a cron job from the command line and pick up new blog creation requests from an external db, create a new blog using the WordPress functions and update the database with the new blog information.
include wp-load.php file (in the root of your wordpress installation) in your php script file like so,
require_once("/path/to/wordpress/wp-load.php");
you will have to provide the abspath of the wp-load file,
now you can use all the functions of wordpress in your php script
I've got a universal solution that will work in any PHP file inside the wp-content folder without any adjustments or needing to know what is mysterious 'path/to/wordpress'
require_once(explode("wp-content", __FILE__)[0] . "wp-load.php");
It just automatically goes up to root of WordPress and loads wp-load.php.
You can just paste it anywhere, no matter if it's a plugin or theme file, and it will work.
I think stuff like ../../../.. looks extremely bad and when you modify the structure of your folders of a theme or plugin you can get crazy.
Note: This solution assumes you didn't rename your wp-content folder.
For wordpress 3.1, I had to specify the host/domain because wp-includes/ms-settings.php:100 needs it or it dies. So my script looks something like (note I am using it for a network/multiblog site):
#!/usr/bin/php -q
<?php
#for multi-blog only
$blog_id = 1;
#specify host or domain (needed for wp-includes/ms-settings.php:100)
$_SERVER[ 'HTTP_HOST' ] = 'localhost';
#location of wp-load.php so we have access to database and $wpdb object
$wp_load_loc = "/path/to/wordpress/wp-load.php";
require_once($wp_load_loc);
#for multi-blog only
switch_to_blog($blog_id);
#test to make sure we can access database
echo $wpdb->prefix;
?>
This should work:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
i.e. When the php script is on the same server and WP is installed on the root. As most cases are.
Following is the code I am using:
<?PHP
require_once ('/path/to/wordpress/wp-load.php');
require_once ('/path/to/wordpress/wp-blog-header.php');
require_once ('/path/to/wordpress/wp-includes/registration.php');
do_action('wpmuadminedit', '');
//Code to Connect and Select the external database
//Code to Connect to the external DB and get the new order details:
NewBlogName=$name and AdminEmail=$email
if ( !email_exists($email) )
{
// email does exist, create a new user
$name = create_name_from_email($email);
$password = "use a default password";
$user_id=wpmu_create_user($name, $password, $email);
create_blog($email, $title, $user_id, $password);
}
else
{
// user exists, create new blog
$user_id=email_exists($email);
$password = "use existing wordpress password";
create_blog($email, $title, $user_id, $password);
}
function create_name_from_email ($email) {
preg_match('/[^#]+)#/',$email,$matches);
$name = $matches[1];
return $name;
}
//Creates a new blog, expects user to already exist.
function create_blog($email, $title, $user_id, $password)
{
//Code to Update external DB that the order is in process
$public = array("public" => 1);
if (constant('VHOST') == 'yes')
{
$newdomain = $domain . "." . $current_site->domain;
$path = $base;
}
else
{
$newdomain = $current_site->domain; $path = $base . $domain . '/';
}
$domain = strtolower($domain);
$newdomain = strtolower($newdomain);
$path = strtolower($path);
$meta = apply_filters('signup_create_blog_meta', array('lang_id' => 1, $public));
$meta = apply_filters("add_singup_meta", $meta);
wpmu_create_blog($newdomain, $path, $title, $user_id , $meta, $current_site->id);
do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $title, $meta);
// Update external DB with BlogUrl, NewBlogName, AdminPassword,
OrderStatus=Complete.
mysql_close($con);
?>
require_once('../../../wp-load.php');
I think you have to add this line before any usage of wordpress function in your custom file. and make sure i have add ../ 3 times as per my wordpress installation structure.It's depends on your structure checks manually.
ex. if your custom file is inside your themes/yourtheme/custom.php then above code will works perfectly and if not then add ../ or remove one or more ../ as per your path.
WordPress uses a phpass function.
This worked for me as I had a password, and the hash in a table (migrated WordPress users) and had to find a way to check login details.
Grab this download here - https://github.com/sunnysingh/phpass-starter
All you need is this basic function to check a text password to a WordPress hash:
<?php
require_once("PasswordHash.php");
$hasher = new PasswordHash(8, false);
// Check that the password is correct
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
// Password good
} else {
// Password wrong
}
?>
All credits to Sunny Singh!

Categories