Getting the base path/URL - php

I am trying to get the base path of the documents through a function as I do not want to find the paths like ../folder1/folder2/mypage.php or ../../../folder1/folder2/somepage.php.
Therefore I tried...
function getBaseUrl() {
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
return $protocol.$hostName.$pathInfo['dirname']."/";
}
Then i give write the code...
$base = getBaseUrl();
require_once $base.'_include/db/qry.php';
require_once $base.'_include/db/functions.php';
Both the files qry.php & functions.php is in http://localhost/mysite/_include/db/
While i run the page, error shows ...
Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\mysite\_include\header.php on line 9
Warning: require_once(http://localhost/mysite/_include/db/qry.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\mysite\_include\header.php on line 9
Fatal error: require_once(): Failed opening required 'http://localhost/mysite/_include/db/qry.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\mysite\_include\header.php on line 9
I tried by echoing the getBaseUrl() like echo $base; and it is showing the right path i.e. http://localhost/mysite/.
What should I do ?

you can use $_SERVER['DOCUMENT_ROOT']

You should just use the absolute path on the server instead of url.
You could get the base path by using __DIR__.
For example:
// just example, change to fit your real path.
$base = __DIR__ . '/../';
require_once $base.'_include/db/qry.php';
require_once $base.'_include/db/functions.php';

Related

Got error while trying to run localhost website on cPanel

I have been trying to switch my web app from localhost to a school server but it's telling me it cannot find the path:
Warning: require_once(/util/tags.php): failed to open stream: No such
file or directory in
/home/xiaoant/public_html/database_pizza/pizza/util/main.php on line
17
Fatal error: require_once(): Failed opening required '/util/tags.php'
(include_path='///') in
/home/xiaoant/public_html/database_pizza/pizza/util/main.php on line
17
<?php
// Start session to store user and cart data
session_start();
// Get the document root
$doc_root = filter_input(INPUT_SERVER, 'DOCUMENT_ROOT', FILTER_SANITIZE_STRING);
// Get the application path
$uri = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING);
$dirs = explode('/', $uri);
$app_path = '/' . $dirs[1] . '/' . $dirs[2] . '/';
// Set the include path
set_include_path($doc_root . $app_path);
// Get common code
require_once('/util/tags.php');
require_once('/model/database.php');
// Define some common functions
function display_db_error($error_message) {
global $app_path;
include 'errors/db_error.php';
exit;
}
function display_error($error_message) {
global $app_path;
include 'errors/error.php';
exit;
}
?>
If you're using window and hosted it on a linux server Please check you path if it contain upper case letters directory names in linux is case sensitive unlike windows
Also you could list all the files in directory to check
'''$files1 = scandir($dir);
print_r($files1);
'''
And see if it there

Opencart Injection Attack

i found this error on my opencar's log ( error.log )
2017-04-11 13:42:45 - PHP Warning: is_dir() expects parameter 1 to be
a valid path, string given in
/home/xxxx/domains/xxxx.com/public_html/system/modification/system/engine/action.php
on line 172017-04-11 13:42:45 - PHP Warning: is_file() expects
parameter 1 to be a valid path, string given in
/home/xxxx/domains/xxx.com/public_html/system/modification/system/engine/action.php
on line 27
I dont know how to prevent it, but when i see the code like this :
$file = DIR_APPLICATION . 'controller/' . str_replace(array('../', '..\\', '..'), '', $path) . '.php';
if (is_file($file)) {
$this->file = $file;
$this->class = 'Controller' . preg_replace('/[^a-zA-Z0-9]/', '', $path);
array_shift($parts);
break;
}
i feel someone inject the ftp path, so opencart return the error.
can someone tell me how to prevent it ???
Why are you calling a Controller like this? You are able to easily load in Controllers with the framework of OpenCart, this makes you able to load in contents of your website through custom controllers, this about a header or footer.
Example in a controller:
$data['header'] = $this->load->controller('common/header');
Above the $data variable is the variable whitch is send with setting the output (view). You are able to echo it in the view as '$header'.
Example of echoing:
<?=$header?>

connecting to SFTP is not working form the command line

I am trying to read a file from SFTP. I am able to connect to the server read information when I run the URL via browser.
But when I run this command from the command line I get many errors
This is the error that I get
C:\Users\test>php -f C:\phpsites\dp_in\IN_sales.php
PHP Warning: require(../classes/connection.php): failed to open stream: No such
file or directory in C:\phpsites\dp_in\IN_sales.php on line 17
Warning: require(../classes/connection.php): failed to open stream: No such file
or directory in C:\phpsites\dp_in\IN_sales.php on line 17
PHP Fatal error: require(): Failed opening required '../classes/connection.php'
(include_path='.;C:\php\pear') in C:\phpsites\dp_in\IN_sales.php on li
ne 17
Fatal error: require(): Failed opening required '../classes/connection.php' (inc
lude_path='.;C:\php\pear') in C:\phpsites\dp_in\IN_sales.php on line 17
This is how I connect to the server using SFTP.
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
Another weird thing is that another file using similar code works with no issues!
I am not sure what could be causing this issue
EDITED
Here is my entire code after the edit
<?php
ini_set('max_execution_time', 900);
ini_set('user_ini.cache_ttl', 900);
date_default_timezone_set('America/Los_Angeles');
error_reporting(E_ALL);
ini_set('display_errors', 1);
$today = strtotime( "-25 day" );
$remote_file = '/per/Data_'. date('Ymd', $today ) . '.csv';
//set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include(__DIR__ . '/Net/SFTP.php');
//include "phpseclib.php";
$sftp = new Net_SFTP('IPADDRESS');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
if(empty($sftp->size($remote_file))){
exit('File Not Found - ' . $remote_file);
}
$csv = $sftp->get($remote_file);
$handle = fopen('php://temp', 'r+');
fputs($handle, $csv);
rewind($handle);
$data = array();
while ($csv_row = fgetcsv($handle) ) {
$data[] = $csv_row;
}
fclose($handle);
require realpath(__DIR__ . '/..') . '/classes/connection.php';
use __DIR__ in your require in order to require your files properly:
require(__DIR__ . "../classes/connection.php")
Multiple issues...
1) You need to define your includes path so that the require works
2) Your connection is probably failing because of #1 (missing credentials from included file)
I figured it out!!
I added this code to the top one my file
chdir(dirname(__FILE__));
This changes the working directory to the running file path.

realpath($_SERVER["DOCUMENT_ROOT"]) not working on Windows

I get this error:
Warning: require_once(C:\xampp\htdocs/models/config.php): failed to open stream: No such file or directory in C:\xampp\htdocs\venture\html\admin\index.php on line 3
Here is the code where the error appears:
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
require_once($root . "/models/config.php");
you need change slash
$root = realpath(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) );
require_once($root . "/models/config.php");

Why do I get "Warning: require_once(config): failed to open stream: No such file or directory" when trying to run this code?

I'm currently working on programming my very own online store with NetBeans IDE 8.0.2 using PHP. My system is Windows 7 32bit and my localhost is powered by WampServer 2.5. I'm following THC Courses: https://www.youtube.com/playlist?list=PLbXVpMmmrntAvOYgkqhHW0hVu8dWUNyfz
So far everything was going great but I got stock at this video: S2 {Building Framework} Class and method (p6). The guy is asking to echo a sample text on the screen to test the code, but I get these two error messages when running the project on localhost:
Warning: require_once(config): failed to open stream: No such file or directory in C:\wamp\www\ecommerce\inc\autoload.php on line 2
Fatal error: require_once(): Failed opening required 'config' (include_path='.;C:\php\pear') in C:\wamp\www\ecommerce\inc\autoload.php on line 2
autoload.php:
<?php
require_once('config');
function __autoload($class_name) {
$class = explode("_", $class_name);
$path = implode("/", $class).".php";
require_once($path);
}
Core.php:
<?php
class Core {
public function run() {
echo "Hello this is a print test";
}
}
index.php:
<?php
require_once'inc/autoload.php';
$core = new Core();
$core->run();
config.php:
<?php
if(!isset($_SESSION)) {
session_start();
}
//site domain name with http
defined("SITE_URL")
||define("SITE_URL", "http://".$_SERVER['SERVER_NAME']);
//directory seperator
defined("DS")
||define("DS", DIRECTORY_SEPERATOR);
//root path
defined("ROOT_PATH")
||define("ROOT_PATH", realpath(dirname(__FILE__) .DS.".." .DS));
//classes folder
defined("CLASSES_DIR")
||define("CLASSES_DIR", classes);
//pages folder
defined("PAGES_DIR")
||define("PAGES_DIR", pages);
//modules folder
defined("MOD_DIR")
||define("MOD_DIR", "mod");
//inc folder
defined("INC_DIR")
||define("INC_DIR", "inc");
//templates folder
defined("TEMPLATE_DIR")
||define("TEMPLATE_DIR", "template");
//emails path
defined("EMAILS_PATH")
||define("EMAILS_PATH", ROOTH_PATH.DS. "emails");
//catalogue images path
defined("CATALOGUE_PATH")
||define("CATALOGUE_PATH", ROOTH_PATH.DS. "media" .DS."catalogue");
//add all above directories to the include path
set_include_path(implode(PATH_SEPERATOR, array(
realpath(ROOTH_PATH.DS.CLASSES_DIR),
realpath(ROOTH_PATH.DS.PAGES_DIR),
realpath(ROOTH_PATH.DS.MOD_DIR),
realpath(ROOTH_PATH.DS.INC_DIR),
realpath(ROOTH_PATH.DS.TEMPLATE_DIR).
get_include_path()
)));
Change this:
require_once('config');
to:
require_once('config.php');
//^^^See here file extension
(Also make sure it's in the same directory with autoload.php, otherwise change the path)
EDIT:
Or try i with a absolute path like this:
require_once(dirname(__FILE__) . "/config.php");
EDIT 2:
Since you now get error messages from the config file, means that it got included, but still has some errors in it!
The first would be this:
//directory seperator
defined("DS")
||define("DS", DIRECTORY_SEPERATOR);
//^^^^^^^^^^^^^^^^^^^ Typo must be: DIRECTORY_SEPARATOR
Next one is here:
//classes folder
defined("CLASSES_DIR")
||define("CLASSES_DIR", classes);
//^^^^^^^ This isn't a constant so if it is a string put quotes around it
Same error here:
//pages folder
defined("PAGES_DIR")
||define("PAGES_DIR", pages);
//^^^^^
Next error here:
//emails path
defined("EMAILS_PATH")
||define("EMAILS_PATH", ROOTH_PATH . DS . "emails");
//^^^^^^^^^^ Typo must be: ROOT_PATH , you have one h too much
Same here:
//catalogue images path
defined("CATALOGUE_PATH")
||define("CATALOGUE_PATH", ROOTH_PATH.DS. "media" .DS."catalogue");
//^^^^^^^^^^
And all over the palce you have 6 typos here:
//add all above directories to the include path
set_include_path(implode(PATH_SEPERATOR, array(
//^^^^^^^^^^^^^^ Typo must be: PATH_SEPARATOR
realpath(ROOTH_PATH.DS.CLASSES_DIR),
//^^^^^^^^^^ Typo must be: ROOT_PATH , you have one h too much
realpath(ROOTH_PATH.DS.PAGES_DIR),
//^^^^^^^^^^
realpath(ROOTH_PATH.DS.MOD_DIR),
//^^^^^^^^^^
realpath(ROOTH_PATH.DS.INC_DIR),
//^^^^^^^^^^
realpath(ROOTH_PATH.DS.TEMPLATE_DIR).
//^^^^^^^^^^
get_include_path()
)));
EDIT 3:
Here you can simplify these 2 lines and i would change the require, so it works even if you include the file itself into another one! Like this:
autoload.php:
function __autoload($class_name) {
$class = explode("_", $class_name);
$path = implode("/", $class).".php";
require_once($path);
}
to this:
function __autoload($class_name) {
$path = str_replace("_", "/", $class_name) . ".php";
require_once(dirname(__FILE__) . "/" . $path);
}

Categories