Cannot redeclare class in PHP error - php

new to PHP. Using the SLIM framework and the routing has been tested and is working fine. Have two files index.php and API.php. index.php is:
<?php
require 'vendor/autoload.php';
require_once 'API.php';
//Turn on error checking
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
//Create a new SLIM app
$app = new \Slim\Slim();
$app->response->headers->set('Content-Type', 'application/json');
$app->get('/', function() use($app) {
$app->response->setStatus(200);
echo "InstaAPI\n";
});
$app->run();
?>
API is:
<?php
class DbHandler{
protected static $conn;
function __construct() {
//Static self notation is different
if(!isset(self::$conn)) {
//same as self.connect
$this->connect();
}
}
function __destruct(){
if(isset(self::$conn)){
self::$conn->close();
}
}
function connect(){
$config = parse_ini_file('../../config2.ini');
// Try and connect to the database
self::$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(self::$conn===FALSE) {
header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: application/json");
$response = array("Response"=>"Failed to connect to the database");
echo json_encode($response);
die();
}
else{
echo "Fine!!";
}
}//end connect
}//end class
?>
I am getting the error: PHP Fatal error: Cannot redeclare class DbHandler in ../API.php on line 62. Not sure why this is happening. I am using require_once and still getting the same error. Could someone give me some pointers to what I might be doing wrong please?

the code of Api.php is less than 62 lines. looks like there is extra code below it. consider deleting extra lines

Related

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct() on PDO class

I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:
[16-Sep-2022 11:05:02 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
Stack trace:
#0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
#1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
#2 {main}
thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11
I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:
error_reporting(E_ALL ^ E_NOTICE);
define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
define('I', 'interfaces/');
// Management
require_once C . 'config.php';
// Interfaces
require_once A . I . 'interface.engine.php';
require_once A . I . 'interface.core.php';
require_once A . I . 'interface.template.php';
// Classes
require_once A . 'class.engine.php';
require_once A . 'class.core.php';
require_once A . 'class.template.php';
// OBJ
$engine = new Kit\engine();
$core = new Kit\core();
$template = new Kit\template();
// Start
session_start();
$template->Initiate();
This references the class.engine.php first which is where I have created the database connection class, as shown below:
namespace Kit;
use PDO;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class engine
{
public $pdo;
public function __construct()
{
global $_CONFIG;
$dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
} catch (\PDOException $e) {
print "<b>An error has occurred whilst connecting to the database:</b><br />" . $e->getMessage() . "";
die();
}
}
}
$connection = new engine();
I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:
namespace Kit;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class core implements iCore
{
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function website_settings()
{
$qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
$qry->execute([]);
if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
}
}
Sorry if this is a simple fix but I really can't see where I'm going wrong.
Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed
Just guessing, but i think
$core = new Kit\core($engine->pdo);
will fix your issue.

Slim error about `Unexpected data in output buffer` not related to characters before a PHP tag or a closing PHP tag

I have this simple code structure:
api.php:
<?php
require_once 'api/Main.class.php';
new Main();
api/Main.class.php:
<?php
require_once __DIR__ . '../../vendor/autoload.php';
require_once 'Router/Router.class.php';
class Main
{
function __construct()
{
$router = new Router();
$router->getRoute();
}
}
Router/Router.class.php:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require_once __DIR__.'../../../vendor/autoload.php';
class Router
{
function getRoute()
{
$app = new \Slim\App;
$app->get(
'/',
function (Request $request, Response $response, array $args) {
$response->getBody()->write('Home');
return $response;
}
);
$app->run();
}
}
This produces the following error when I go to api.php: <b>Fatal error</b>: Uncaught RuntimeException: Unexpected data in output buffer. Maybe you have characters before an opening <?php tag? in /Path/to/project/root/vendor/slim/slim/Slim/App.php:625
This error doesn't give me much information. I've been trying to get Slim to work in an OOP codebase, but this error keeps popping up every time I try this.
I've also tried returning $app, so I can run t elsewhere, which also produces the same error. What is going wrong in this code?

Can't call the function in PHP

I am having a problem with my index.php. Whenever I go to http://localhost/blog/admin/index.php I get an error:
Fatal error: Call to undefined function Blog\DB\connect() in C:\xampp\htdocs\blog\blog.php on line 6.
In the admin folder all I am requiring is my blog.php which is working fine in other files when I required them. I am stuck with this and can not understand why this is happening.
index.php in admin folder
My admin/index.php:
<?php
require '../blog.php';
My blog.php. It is requiring the db.php in which we have called the connect function.
<?php
require 'db.php';
$conn = \App\DB\connect($config);
if(!$conn)
die('Could not connect to db');
My db.php. It is just trying to establish a connection:
<?php namespace App\DB;
require 'config.php';
function connect($config)
{
try
{
$conn = new \PDO("mysql:host=localhost;dbname=blogs",
$config['DB_USERNAME'],
$config['DB_PASSWORD']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(PDOException $e)
{
return false;
}
}

How to run simple Php API?

I used Php Slim Framework for my API. I install the Slim Framework to my web root directory on my server and copy the index.php file I coded.
Index.php:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->run();
function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
}
catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
?>
I am getting 500 (Internal Server Error).
Edit: I changed "$app = new Slim();" to the "$app = new \Slim\Slim();" then receive the below error.
I am using EasyEngine(Nginx).
Edit-2:Now 500 Internal gone but another error showing.
XMLHttpRequest cannot load http://api.mangayurdu.com/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://deneme.mangayurdu.com' is therefore not allowed access.
Here is my code that getting JSON data:
.factory('MY', function($http){
var factory = {};
var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
From the posted code it looks like Slim can't find a function called getUser. getUsers() is defined in your code, but no getUser() function.
try putting this in the start of your PHP page
<?php header('Access-Control-Allow-Origin: *');?>

can't figure what might causing this error when creating PDO object

i am following a tutorial to create an OOP based login system.I did everything accordingly but while creating pdo i am getting an error in DB.php file in line 15.Can't figure out the reason for this error.Been stuck there for some time.Can anyone help me out with this error .The code might look long but it is a piece of cake for you i promise.There are FOUR php files.
1.init.php file holds the ingredients to create a new PDO() object.
2.config.php file is used to get data from init.php file as string is passed to it as ('mysql/host') type and use explode() function to extract data from it.
2.DB.php file is used to connect to database.
The error i am getting is
DB.php file:
class DB{
private $_instance=null;
private $pdo,
$query,
$error=false,
$results,
$count=0;
private function __construct(){
try{
$this->$pdo=new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/user'),Config::get('mysql/password'));
}catch(PDOException as $e){
echo $e->getMessage();
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance=new DB();
}
return self::$_instance;
}
}
Config.php file:
class Config{
public static function get($path){
if($path){
$config=$GLOBALS['config'];
$arr=explode('/',$path);
foreach($arr as $bit){
if(isset($config[$bit])){
$config=$config[$bit];
}
}
return $config;
}
}
}
init.php file:
session_start();
$GLOBALS['config']=array(
'mysql'=>array(
'host' => 'localhost',
'db' => 'login',
'user' => 'root',
'password' => ''
)
);
spl_autoload_register(function($class){
require_once 'c:/xampp/htdocs/login/classes/'.$class.'.php';
});
require_once 'c:/xampp/htdocs/login/function/sanitize.php';
index.php file:
require_once 'c:/xampp/htdocs/login/core/init.php';
DB::getInstance()->query('SELECT name FROM table WHERE id=1');
Your error message is a Parse Error. This means the PHP interpreter/processor/program tried to read your file, but found a syntax error, and had to stop. If you look at Line 15 of DB.php (per the error message)
}catch(PDOException as $e){
You'll see the problem. This isn't valid PHP syntax -- you probably want
}catch(PDOException $e){
The PDOException bit of that is a a class type hint for the exception handling code -- there's no need to use the as.

Categories