Basically I created this script that check if a file exists and then creates it.
It worked great before when I had a non OOP version of it.
Now I modified it to become OOP and somehow it doesn't work and I get the error in Apache PHP Fatal error: Call to undefined function createFile() in C:\Program Files (x86)\Zend\Apache2\htdocs\Proj11\1.php on line 66
I highlighted where line 66 is with the line //// THE ERROR LINE BELOW
Whats wrong with it??? thx
<?php
//DB Config File
$phase = $_GET['phase'];
if(empty ($phase)){
$phase = new phase1();
$phase->start();
} elseif ($phase = 1) {
$phase = new phase2();
$phase->stepFunction();
};
class phase1 {
function __construct () {
$dbFile = 'dbconfig.php';
$step = 0;
$username = $_GET['username'];
$password = $_GET['password'];
$server = $_GET['server'];
$dbName = $_GET['dbName'];
$this->step = $step;
$this->dbFile = $dbFile;
$this->username = $username;
$this->password = $password;
$this->server = $server;
$this->dbName = $dbName;
$db = new PDO ('mysql:host=' .$server.';dbname='.$this->dbName,$this->username,$this->password);
$this->db = $db;
}
public function createFile () {
//Creates File and populates it.
$fOpen = fopen($this->dbFile, 'w');
$fString .= "<?php\n";
$fString .= "// Database Constants\n";
$fString .= "\$DB_SERVER =" . "\"" . $this->server . "\";\n";
$fString .= "\$DB_USER =" . "\"" . $this->username . "\";\n";
$fString .= "\$DB_PASS =" . "\"" . $this->password . "\";\n";
$fString .= "\$DB_NAME =". "\"" . $this->dbName . "\";\n";
$fString .= "?>";
fwrite($fOpen, $fString);
fclose($fOpen);
return true;
}
public function start (){
try {
if ($this->db) { //if succesful at connecting to the DB
if (file_exists($this->dbFile)){
if (is_readable($this->dbFile) && is_writable($this->dbFile)){
//Creates File, populates it and redirects the user
//////////////////////////
//// THE ERROR LINE BELOW
//////////////////////////
if (createFile()) {
$phase = new phase2();
$phase->stepFunction($this->step);
exit ();
}
} else {
echo "The file {$dbFile} cannot be accessed. Please configure the file manualy or grant Write and Read permission."; }
} else {
//Creates File, populates it and redirects the user
if (createFile()) {
$phase = new phase2();
$phase->stepFunction($this->step);
exit ();
}
}
}
} catch (PDOException $e) { //Catchs error if can't connect to the db.
echo 'Connection failed: ' . $e->getMessage();
}
}
} // en class Phase 1
createFile() is a method defined in the class, and must be called inside the class as $this->createFile():
if ($this->createFile()) {...}
I have not looked over your code thoroughly yet, but you may have omitted $this-> on other method calls as well.
I'll point out also that since there doesn't appear to be any circumstance in which createFile() returns anything other than TRUE, there's no real need for the if () {} block; the else case will never be reachable.
Related
I've searched high and low for this topic, and no one has the same issue I'm experiencing that I could find.
I'm creating a user in a MySQL table, with a hash from password_hash with a strength of 10.
I've been having hell getting it to validate, and have a test script made to actually validate my findings. Here is the script:
public function testAction(){
$data = new dataHandler;
$data->table = "access";
$hash1 = $data->insert(array('email'=>'test6#test.com', 'password'=>'ABC123.abc', 'password_confirm'=>'ABC123.abc', 'alias'=>'ABC123.abc'));
$res = $data->find(array('email'=>'test6#test.com'));
$hash2 = $res[0]['hash'];
$test = password_verify('ABC123.abc', $hash1);
$test2 = password_verify('ABC123.abc', $hash2);
var_dump($test);
echo "<br>";
var_dump($test2);
echo "<br><br>";
echo "Length: " . strlen($hash1) . "<br>{$hash1}<br>Length: " . strlen($hash2) . "<br>{$hash2}";
die();
}
To verify that my script wasn't somehow doing something weird when storing, I made my hash method (called from within the insert() method dynamically) echo out the hash directly:
public function createHash($password){
$hash = password_hash($password, HASH);
echo "Length: " . strlen($hash) . "<br>$hash<br>";
return $hash;
}
Here's the insert method. cleanData simply unsets anything not available in a describe - it is not changing any values whatsoever. Warning, it's terribly ugly presently due to a lot of debugging and such:
public function insert($data){
if(!is_array($data)){
return false;
} else {
$this->openDb();
$ins = "";
$fs = "";
$data = $this->cleanData($data);
foreach($data as $key => $field){
if($key == "password"){
$auth = new authorization;
$key = "hash";
$field = $auth->createHash($field);
$data['hash'] = $field;
unset($data["password"]);
}
$ins .= ":{$key}, ";
$fs .= "`{$key}`, ";
//$data[$key] = $this->DBH->quote($field);
}
$ins = rtrim($ins, ", ");
$fs = rtrim($fs, ", ");
try {
# the shortcut!
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $this->DBH->prepare("INSERT INTO `" . $this->table . "` ($fs) value ($ins)");
$STH->execute($data);
$id = $this->DBH->lastInsertId();
$this->closeDb();
return $data['hash']; //Debugging
return $id;
} catch(PDOException $e) {
$this->errHandler($e->getMessage());
}
}
}
Now, here's the output:
Length: 60
$2y$10$wGJxGjK4Lz4FgZ3OZJjBo.9lF7LE90p3Q5inOsBROQTU5FBVdj1LK
bool(true)
bool(false)
Length: 60
$2y$10$wGJxGjK4Lz4FgZ3OZJjBo.9lF7LE90p3Q5inOsBROQTU5FBVdj1LK
Length: 60
$2y$10$wGJxGjK4Lz4FgZ3OZJjBo.9lF7LE90p3Q5inOsBROQTU5FBVdj1LK
As you can see, both password_verify attempts fail. The first comes from the hash generation without any further manipulation, the second comes from the database.
What am I doing wrong?
The only thing I could find when searching was people testing and using double quotes, or random human error. This, however, doesn't appear to me to be either of those two.
That password hash is for the empty string, try it yourself:
<?php
echo password_verify('', '$2y$10$4Y7kQNP/6XyBtQQ4zPI6ZuaelCjHdWE.kBRTUVk56J7PV4BQYWoUS')?'Y':'N';
?>
Make sure you're passing createHash a valid $password.
I have read the previous questions with similar titles, none seem to provide me with an answer to this particular situation. I am receiving the error mentioned above on a specific functionality. I am not sure what is making it pop up. This is my first development so, unless it is specific to resolving the bug, please leave out the fact that I should be using PDO or mysqli.
this is the function i am trying to instantiate. when the sql command is executed in isolation, it returns the proper results.
public function search_for_candidates_by_technology($technology, $seniority){
$technology = $this->real_escape_string($technology);
$seniority = $this->real_escape_string($seniority);
$this->query("SELECT * FROM candidates WHERE technology LIKE ". $technology ." AND seniority LIKE ". $seniority ."");
}
The class to which the function belongs is tecnoDB
In the actual page where I am trying to instantiate, this is the code:
<form name="buscarBase" action="buscarCV.php" method="POST">Que technologia:<input type="text" name="usertech" value=""/><br/>
Que seniority:<input type="text" name="userSeniority" value="" />
<input type="submit" name="buscar" value="Buscar" />
<input type="submit" name="back" value="Panel de Control"/>
</form>
<table border="black">
<tr><th>Technology</th><th>Seniority</tr>
<?php
$search = tecnoDB::getInstance()->search_for_candidates_by_technology($_POST['usertech'], $_POST['userSeniority']);
while($searchResult = mysql_fetch_array($search)){
echo "<tr><td>" . htmlentities($searchResult['technology']) ."</td>";
echo "<td>". htmlentities($searchResult['seniority']) . "</td></tr>";
}
?>
</table>
The error is coming on the line: while($searchResult = mysql_fetch_array($search))....
That makes me think that the problem is that $search is not being created as an instance. Any ideas?
This is my first project and first question, please be gentle.
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
session_start();
if (!array_key_exists("user", $_SESSION)) {
header('Location: index.php');
exit;
}
require_once("Includes/tecnoDB.php");
$company_id = tecnoDB::getInstance()->get_company_id_by_name($_SESSION['user']);
if ($_SERVER['REQUEST_METHOD'] == "POST"){
if (array_key_exists("back", $_POST)) {
header('Location: companyControlPanel.php' );
exit;
}
else{
$service_user = tecnoDB::getInstance()->verify_service_status($company_id);
$access = $service_user->fetch_row();
if (array_key_exists ("buscar", $_POST)){
if($access[0] < 2 ){
header("Location: selectServicePackage.php" );
exit;
}
}
}
}
// put your code here ?>
<form name="buscarBase" action="buscarCV.php" method="POST">Que tecnologia:<input type="text" name="usertech" value=""/><br/>
Que seniority:<input type="text" name="userSeniority" value="" />
<input type="submit" name="buscar" value="Buscar" />
<input type="submit" name="back" value="Panel de Control"/>
</form>
<table border="black">
<tr><th>Technology</th><th>Seniority</tr>
<?php
$search = tecnoDB::getInstance()->search_for_candidates_by_technology($_POST['usertech'], $_POST['userSeniority']);
while($searchResult = mysql_fetch_array($search)){
echo "<tr><td>" . htmlentities($searchResult['technology']) ."</td>";
echo "<td>". htmlentities($searchResult['seniority']) . "</td></tr>";
}
?>
</table>
</body>
</html>
here goes the tecnoDB class:
class tecnoDB extends mysqli {
// single instance of self shared among all instances
private static $instance = null;
// db connection config vars
private $user = "phpuser";
private $pass = "phpuserpw";
private $dbName = "tecnosearch";
private $dbHost = "localhost";
//This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
// The clone and wakeup methods prevents external instantiation of copies of the Singleton class,
// thus eliminating the possibility of duplicate objects.
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
// private constructor
private function __construct() {
parent::__construct($this->dbHost, $this->user, $this->pass, $this->dbName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
parent::set_charset('utf-8');
}
public function get_company_id_by_name($name) {
$name = $this->real_escape_string($name);
$company = $this->query("SELECT id FROM company WHERE name = '"
. $name . "'");
if ($company->num_rows > 0){
$row = $company->fetch_row();
return $row[0];
} else
return null;
}
public function get_searches_by_company_id($company_id) {
return $this->query("SELECT id, description, technology FROM searches WHERE company_id=" . $company_id);
}
public function create_company ($name, $password){
$name = $this->real_escape_string($name);
$password = $this->real_escape_string($password);
$this->query("INSERT INTO company (name, password) VALUES ('" . $name . "', '" . $password . "')");
}
public function verify_company_credentials ($name, $password){
$name = $this->real_escape_string($name);
$password = $this->real_escape_string($password);
$result = $this->query("SELECT 1 FROM company
WHERE name = '" . $name . "' AND password = '" . $password . "'");
return $result->data_seek(0);
}
public function verify_service_status ($company_id){
$company_id = $this->real_escape_string($company_id);
$service = $this->query("SELECT service FROM company WHERE id = '". $company_id ."'");
return $service;
}
function insert_search($company_id, $description, $technology){
$description = $this->real_escape_string($description);
$technology = $this->real_escape_string($technology);
$this->query("INSERT INTO searches (company_id, description, technology)" .
" VALUES (" . $company_id . ", '" . $description . "','" .$technology. "')");
}
public function search_for_candidates_by_technology($technology, $seniority){
$technology = $this->real_escape_string($technology);
$seniority = $this->real_escape_string($seniority);
$this->query("SELECT * FROM candidates WHERE technology LIKE ". $technology ." AND seniority LIKE ". $seniority ."");
}
}
?>
I fixed the bug by setting the query in search_for_candidates_by_technology = $variable and returning the variable as well as in the actual page requiring the file where I have this function specified. I set the instance of the search_for_candidates_by_technology equal to $variable1 and created another object as the result of $variable1->get_array; . My error messages are now gone but the results are not appearing in the search. I am assuming because the action is on the same page and it causes the page to reload and when it reloads it essentially is resetting. I am looking at using an AJAX to show the results instead but I have never used asynchronous javascript and have only briefly seen XMLs. Any pointers or ideas that won't require AJAX?
For some reason the return doesn't work when the check_em() succeeds. I'm new to php, so I'm at a loss here.
<?php
//Class to handle mysql
class db_handler {
private $db_host = 'localhost';
private $db_name = 'project';
private $db_user = 'project';
private $db_pass = 'dbpassword';
private $db_con_mysql = '';
private $db_con_db = '';
public function check_em($username, $password) {
$db_query = "SELECT password FROM user WHERE name='".$username."' LIMIT 1;";
if($this->db_con_mysql!='') {
$db_query_response = mysql_query($db_query) or die('Query failed: '.mysql_error());
$db_query_return = mysql_fetch_row($db_query_response);
$db_sha1_hash = $db_query_return[0];
echo $db_sha1_hash."<br>";
echo sha1($password)."<br>";
if(sha1($password)==$db_sha1_hash) {
return 'user valid'; //THIS DOESN'T WORK!?!?!?
} else {
return 'no good';
}
} else {
$this->db_connect();
$this->check_em($username, $password);
}
}
//Connect to mysql, then database
private function db_connect() {
$this->db_con_mysql = mysql_connect($this->db_host, $this->db_user, $this->db_pass) || die('Connection failed: '.mysql_error());
$this->db_con_db = mysql_select_db($this->db_name) || die('Could not use'.$this->db_name.'. '.mysql_error());
return;
}
//Disconnect from database and reset vars used to track connection.
private function db_disconnect() {
if($this->db_con_mysql!='') {
mysql_close();
$this->db_con_mysql = '';
$this->db_con_db = '';
return;
}
}
public function fake($some_val) {
if($some_val<6) {
return TRUE;
} else {
return FALSE;
}
}
}
$db_obj = new db_handler();
$val1 = $db_obj->check_em('someuser','password'); //should return 'user valid'
echo "val1:".$val1."<br>";
echo "<br><br>";
$val2 = $db_obj->check_em('someuser','passw0rd'); //should return 'no good'
echo "val2:".$val2."<br>";
echo "<br><br>";
echo "test<br>";
echo $db_obj->fake(4)."<br>";
?>
Results:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
val1:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
7c6a61c68ef8b9b6b061b28c348bc1ed7921cb53
val2:no good
test
1
This line needs a return:
return $this->check_em($username, $password);
But a more sensible solution would be to connect to the database inside the if when the connection is null. Really, the whole thing could be better written, but I'll leave it at that.
...
else {
$this->db_connect();
return $this->check_em($username, $password);
}
...
You want to add the return, so that if it fails, then it goes one level deeper and finds another. If that level deeper succeeds, it passes the value up to the level above, which can pass it up and up until it reaches the original function call.
Already tearing my hairs out for a couple of days. There is not much left of them ;-)
I am experiencing a strange problem when I want to bind a service to a button or something else:
files:
- CDPC.php
<?php
require_once ('VOcdpc.php');
class CDPC {
var $username = "root";
var $password = "";
var $server = "localhost";
var $port = "3306";
var $databasename = "xoffercommon";
var $tablename = "tblcity";
var $connection;
public function __construct() {
$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port
);
mysqli_set_charset($this->connection,'utf8');
$this->throwExceptionOnError($this->connection);
}
public function getCDPC($cityID) {
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xoffercommon", $con);
$cdpc_Id = new Vocdpc();
$cdpc_Id->id_cdpc = 1;
$cdpc_Id->city_Id=$cityID;
$result_prov = mysql_query("SELECT tblProvence_Id FROM tblCity WHERE Id = " . $cityID);
$row = mysql_fetch_array($result_prov);
$cdpc_Id->provence_Id=intval($row['tblProvence_Id']);
$result_dist = mysql_query("SELECT tblDistrict_Id FROM tblProvence WHERE Id = " . $cdpc_Id->provence_Id);
$row = mysql_fetch_array($result_dist);
$cdpc_Id->district_Id=intval($row['tblDistrict_Id']);
$result_coun = mysql_query("SELECT tblCountry_Id FROM tblDistrict WHERE Id = " . $cdpc_Id->district_Id);
$row = mysql_fetch_array($result_coun);
$cdpc_Id->country_Id=intval($row['tblCountry_Id']);
return $cdpc_Id;
mysql_close($con);
}
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>
VOcpdc.php
<?php
class VOcdpc
{
public $id_cdpc;
public $country_Id;
public $district_Id;
public $provence_Id;
public $city_Id;
// explicit actionscript class
var $_explicitType = "Vocdpc";
}
?>
In flex builder
I can add the services to the Data Services panel but I have two strange things:
1) when I want to configure the return type he doesn't let me create a new ValueObject type, I only get the bottom datagrid which states: Properties returned by the operation: Property: country_Id, provence_Id, city_Id, id_cdpc, district_Id with the related values on the right side. Why can't I create a new data type on the top?
2) When I accept this and want to add the service call to a button (drag&drop) I get the following error: Error occurred while generating code. Make sure that there are no compiler eroors and try again after reopening the file. Componentn type services.cdpc.CDPC not found...
(ps: When I perform a Test Operation everything seems to be ok, I get the expected output values)
this is the class included in the main cdpc.php file, the post drops it apparently, so here is the VOcpdc file:
// explicit actionscript class
var $_explicitType = "Vocdpc";
}
?>
I have two php files, one manages database connection and the other retrieves data from the database. I am writing this from scratch as a learning experience, and granted it is 5am but for some reason I cannot access the variables I need to.
My database connection file is as follows:
<?
class mysqlManager {
var $dbhost = 'xxx.xxx.xxx.xxx';
var $dbuser = 'xxx';
var $dbpass = 'xxx';
var $dbname = 'xxx';
var $connection;
var $errorCode;
var $errorMsg;
public function __construct($host='',$user='',$pass='',$name='') {
if(!$host=='') $this->dbhost = $host;
if(!$user=='') $this->dbuser = $user;
if(!$pass=='') $this->dbpass = $pass;
if(!$name=='') $this->dbname = $name;
}
function openConnection($host,$user,$pass) {
if(!$this->connection = #mysql_connect($host,$user,$pass,true)) {
$this->errorCode = mysql_errno();
$this->errorMsg = mysql_error();
return false;
}
return true;
}
function closeConnection() {
if($this->connection){
#mysql_close($this->connection);
}
}
function selectDB($name) {
if(!$this->openConnection($this->dbhost,$this->dbuser,$this->dbpass)){
return false;
}else{
return #mysql_select_db($name);
}
}
}
?>
The next file for getting data is as follows:
<?
class ccp {
var $mgr;
public function __construct() {
$this->mgr = new mysqlManager();
}
public function test() {
print_r($this->mgr);
}
function getCCP() {
if($mgr->openConnection($mgr->dbhost,$mgr->dbuser,$mgr->dbpass)) {
if(!$mgr->selectDB($mgr->dbname)) {
$mgr->closeConnection();
return 'An error has occured while processing your request.';
}
$q = 'SELECT * FROM ccp WHERE cat="ccp" ORDER BY date DESC';
$r = #mysql_query($q);
$ret='';
while($row = #mysql_fetch_array($r)){
$ret = '<div class="post">';
$ret .= ' <h2 class="title">'.$row["title"].'</h2>';
$ret .= ' <p class="date">'.$row["date"].'</p>';
$ret .= ' <div class="entry">'.$row["body"].'</div>';
$ret .= '</div>';
}
$mgr->closeConnection();
return $ret;
}
}
}
?>
When I run the test function, I get this:
mysqlManager Object ( [dbhost] => xxx.xxx.xxx.xxx [dbuser] => xxx [dbpass] => xxx [dbname] => xxx [connection] => [errorCode] => [errorMsg] => )
How do I access the variables in the mysqlManager Object?
Thanks!
To access the members of an object, use ->, with nested objects, multiple times. So: In test():
echo $this->mgr->dbhost; // echoes xxx.xx.xxx.xxx
echo $this->mgr->dbpass; // echoes xxx
You can do this because the variables were declared using var, making them implicitly public. If you declare them with private or protected like so:
class mysqlManager
{
private $dbhost = 'xxx.xxx.xxx.xxx';
protected $dbuser = 'xxx';
...
you will not be able to access the variables from another object.
Does that answer your question?