I am still rather green when it comes to PHP. Not quite sure where the issue comes in here. I am using a rather simple SSH2 class (https://www.phpclasses.org/browse/file/34450.html) that works well for my needs, or has until this point.
This is the class I have set up. I put the ssh connection into the constructor, and attempt to use $this->ssh throughout the rest of the class functions.
include ("/var/www/html/class/ssh2_class.php"); ##https://www.phpclasses.org/browse/file/34450.html
class crontab {
function __construct($host,$params) {
$this->host = $host;
$this->pubkey = $params['pubkey'];
$this->privkey = $params['privkey'];
$this->usr = $params['user'];
$this->port = $params['port'];
$this->secret = $params['secret'];
$this->ssh = new SSH2($this->host)
or die ("Unable to connect to ". $this->host ."!");
$this->ssh->auth($this->usr, $this->pubkey, $this->privkey, $this->secret)
or die ("Unable to authenticate to ". $this->host ."!");
}
function show($sudo) {
if ($sudo) { $sudo = "sudo"; } else { $sudo = ""; }
$cmd = $sudo."$sudo crontab -l";
$this->ssh->exec($cmd);
return ($this->ssh->output);
}
The issue I run into is in the return line of the show function above. The $this->ssh->exec($cmd); works without issue; I've tested it by simply touching a file.
PHP Notice: Undefined property: SSH2::$output in /home/mackay_c/scripts/deploy/deploy.class.php on line 26
I've searched around the web, and am at a bit of a loss as to why this occurs. The 'output' function in the SSH2 class is:
function output() {
return stream_get_contents($this->stream);
Any help would be appreciated.
return ($this->ssh->output())
Related
I have been working on getting a PDO connection to establish within a class for the better half of a day. My problem is that as soon as I try to hit the new PDO(...) I get nothing, no errors nothing. Whatever I have after that will never run but my console will still be operational waiting for input. I have tried connecting in a few places including the "Driver" file where again, it doesn't do anything after I run the new PDO(...) instantiation. Here is part of my Database Class:
namespace App\Database;
class MySQL
{
private $Host;
private $DBName;
private $DBTable;
private $DBUser;
private $DBPassword;
private $DBPort;
private $PDO;
private $parameters;
private $bConnected = false;
public $querycount = 0;
function __construct($DBName, $DBTable)
{
$this->Host = getenv("DATABASE_HOST");
$this->DBPort = getenv("DATABASE_PORT");
$this->DBUser = getenv("DATABASE_USER");
$this->DBPassword = getenv("DATABASE_PASSWORD");
$this->DBName = $DBName;
$this->DBTable = $DBTable;
$this->Connect();
$this->$parameters = array();
}
private function Connect()
{
try{
echo "I am the good child and always print".PHP_EOL;
$this->PDO = new PDO("mysql:host=localhost;port=33061;dbname=store", "root", "password");
echo "Please Print Me <3".PHP_EOL;
$this->bConnected = true;
} catch (PDOException $e){
echo $e->getMessage();
die();
}
}
I have checked values for Host, DBPort etc and in this code below I have all their values hard coded so nothing should be wrong due to the formatting of insert the variables in their proper slots. I know PDO is turned on because I can use it in other projects but my catch isn't catching anything, I can get the first echo to run but the second one never appears. Any help would be awesome because at this point I am scratching my head at why I can't get this to connect.
Thanks!
If I am unclear I can try and provide clarity and I can also show the driver file if need be but basically, it is just calling the constructor just fine and the connect function is giving us problems.
I have been going over each line of my code for about the last hour or so if not more. I found some discrepancies in my variables. I used in a couple places $this->$parameters
or other variations which didn't seem to cause an error for some reason but rendered the code inoperable. I'm not sure why it wasn't throwing an error about the variables but it would seem that is what caused my issue.
Thank you for your time and help!
I have had the hardest time getting PHP to talk to Postgres SQL. Here is my setup:
Ubunu Desktop 13.10
PHP 5.5.3
Postgres 9.1.10
Apache 2.4.6
Netbeans 7.4 with xdebug
Everything is working fine. I am able to enter and retrieve data in the Postgres Database fine from the command line but not in PHP. Here are the lines of code that I am using to connect:
$dbConn = new softwareDB('localhost', 'postgres', 'root', 'softwareuitest');
...
$results = $dbConn.getClients();
while($client = pg_fetch_result($results)){
echo '<option value=\"'.$client.'\">'.$client.'</option>';
}
The softwareDB class constructor is as follows:
Class softwareDB {
private $conn;
function _construct($host, $user, $password, $dbname) {
$connectString =
'host=' . $host .
' port=5432' .
' user=' . $user .
' password=' . $password .
' dbname' . $dbname;
$this->conn = pg_connect($connectString);
}
...
public function getClients() {
global $conn;
return pg_query($conn,'getClients','SELECT * FROM clients');
}
...
}
When running the code nothing happens... I see nothing in the Apache log file, nothing in the postgres log, nothing from the debugger, and only HTML (without query data) in the output.
I cannot post images yet but here are the details about Postgres from phpInfo():
PDO
PDO Drivers | pgsql
pdo_pgsql
version 9.1.9
module 1.0.2
revision $id$
pgsql
PostgreSQL(libpq) | PostgreSQL 9.1.9 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.8.1-10ubuntu1) 4.8.1, 64-bit
allow_persistent is on
You have two main issues. The first is a typo; PHP class instance methods are called via the arrow operator. It should be...
$results = $dbConn->getClients();
The second is your use of global $conn. You don't have a variable named $conn, global or not. What you do have is a member property $conn which you may reference by prefixing it with $this, eg
public function getClients() {
return pg_query($this->conn, 'SELECT * FROM clients');
}
Looking further, I would suggest that if you're going to abstract DB details away in your softwareDB class, you might as well do it completely. I'd go with something like this
class softwareDB {
private $conn;
public function __construct($host, $user, $password, $dbname) {
$this->conn = pg_connect(sprintf('host=%s port=5432 user=%s password=%s dbname=%s',
$host, $user, $password, $dbname));
if ($this->conn === false) {
throw new Exception(pg_last_error());
}
}
public function getClients() {
$result = pg_query($this->conn, 'SELECT * FROM clients');
return pg_fetch_all($result);
}
}
I'm not too familiar with the PostgreSQL Functions so you may need to tweak this but the general idea is that code using your softwareDB class doesn't need to know anything about postgres or other DB operations.
I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array
I'm a .Net developer that have taken over a PHP project. This project has a database layer that looks like this:
<?php
class DatabaseManager {
private static $connection;
const host = "projectname.mysql.hostname.se";
const database = "databaseName";
const username = "userName";
const password = "password";
public function __construct()
{
}
public function instance($_host = null, $_username = null, $_password = null)
{
if(!self::$connection)
{
if(!$_host || !$_username || !$_password)
{
$host = self::host;
$username = self::username;
$password = self::password;
}else{
$host = $_host;
$username = $_username;
$password = $_password;
}
self::$connection = mysql_connect($host, $username, $password);
$this->setDatabase();
}
return self::$connection;
}
public function setDatabase($_database = null)
{
if(!$_database)
{
$database = self::database;
}else{
$database = $_database;
}
$connection = $this->instance();
mysql_select_db($database, $connection) or die(mysql_error());
}
} ?>
I have written a php file that uses this layer but after a while i got these mysql errors implying i didn't close my connections which i hadn't. I try to close them but know i get other weird errors like system error: 111. Very simplyfied my php file looks like this:
<?php
$return = new stdClass();
$uid = '9999999999999';
$return->{"myUid"} = $uid;
$dm = new DatabaseManager();
$dmInstance = $dm->instance();
/* MY CLICKS */
$sql = sprintf("SELECT count(*) as myClicks FROM clicks2011, users2011 WHERE clicks2011.uid = users2011.uid AND users2011.uid = %s AND DATEDIFF(DATE(at), '%s') = 0 AND exclude = 0", mysql_real_escape_string($uid), mysql_real_escape_string($selectedDay));
$result = mysql_query($sql, $dmInstance) or die (mysql_error());
$dbResult = mysql_fetch_row($result);
$return->{"myClicks"} = $dbResult[0];
mysql_close($dmInstance);
echo json_encode($return); ?>
Okay, I'm going to post this as an answer because I think one (possibly both) of these things will help you.
First: You don't need to manually close your MySQL connections. Unless you have set them up so that they persist, they will close automatically. I would avoid doing that unless you determine that every other problem is NOT the solution.
In addition, I would switch to using prepared statements. It's more secure, and pretty future-proof. I prefer PHP's PDO over mysqli, but that's up to you.
If you'd like to look over an example of a simple PDO object to take the many lines out of creating prepared statements and connections and getting results, you can look at my homebrew solution.
Second: "System Error 111" is a MySQL error. From what I've read, it appears that this error typically occurs when you are using PHP and MySQL on the same server, but telling PHP to connect to MySQL via an IP address. Switch your $host variable to 'localhost'. It is likely that this will solve that error.
The problem here is you're calling mysql_close and not specifying a valid mysql connection resource object. You're, instead, trying to close an instance of the DatabaseManager object.
You'll probably want to run mysql_close(DatabaseManager::connection); which is where the DatabaseManager is storing the resource object.
Additionally, I'd personally recommend you learn PDO or use the mysqli drivers. In future releases of PHP the built in mysql functions will be moved into E_DEPRECATED
Try implement __destrcut
public function __destruct()
{
mysql_close(self::$connection)
}
Then simply use unset($dm);
I have create a class called Database.php for interacting with MySql database using Pear Db class.
Database.php
<?php
require_once('DB.php');
require_once('cException.php');
class DataBase
{
private $dsn = 'mysql://root:xxxxxx#localhost/avatar';
private $conn;
//Constructor
function __construct()
{
global $conn;
$this->conn = DB::connect($dsn);
if(DB::isError($conn))
{
throw new DatabaseConnectionException();
}
}
//destructor
function __destruct()
{
$this->conn->disconnect();
}
public function select($query)
{
$conn->setFetchMode(DB_FETCHMODE_ASSOC);
$result = & $conn->query($query);
if(DB::isError($result))
{
return new SelectCommandException($result->getMessage());
}
return $result;
}
static public function instance()
{
static $objDB;
if(! isset($objDB))
{
$objDB = new DataBase();
}
return $objDB;
}
?>
And I am calling this class from a sample file test.php
test.php
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
require_once 'Database.php';
try
{
$db = DataBase::instance();
}
catch (DatabaseConnectionException $ex1)
{
echo $ex1->toString();
}
try
{
$sql = "Select * from register";
$result = $db->select($sql);
var_dump($result);
}
catch (SelectCommandException $ex2)
{
echo $ex2->toString();
}
?>
When I run test.php I get the following error
Warning:
require_once(/usr/share/pear/DB.php):
failed to open stream: No such file or
directory in
/var/www/Avatar/Database.php on line 2
Fatal error: require_once(): Failed
opening required
'/usr/share/pear/DB.php'
(include_path='.:/usr/share/php:/usr/share/pear')
in /var/www/Avatar/Database.php on
line 2
I don't know why I am getting this error. In phpinfo() it shows include_path .:/usr/share/php:/usr/share/pear .:/usr/share/php:/usr/share/pear
I am using php5 and I even tried installing php-pear package, still I get the same error.
I don't understand what's wrong here. Can someone please point me in a right direction.
Note : I have not installed php5 using sudo apt-get install php5. I have downloaded php5 packages using Keryx application.
Looks you did not install DB package, try in command prompt, do
pear list
If no package of DB is installed, you can installed it with
pear install DB
example from documentation