I made a function to get the main folder path in which website is stored. In localhost it works fine.
function get_path()
{
$current=dirname(__FILE__) . '/';
$name=basename(__DIR__);
$from=array($name);
$to=array('');
$result=str_replace($from,$to,$current);
return trim($result, "/\\");
}
But in server it shows error while including files.
include(): Failed opening 'home3/home/public_html/dev/ship\model\main.php' for inclusion (include_path='.:/opt/php54/lib/php')
The file is there in that directory for sure. But its not working.
Try the following
// Define directory separator
define('DS', DIRECTORY_SEPARATOR);
function get_path()
{
$current = dirname(__FILE__) . DS;
$name = basename(__DIR__);
$from = array($name);
$to = array('');
$result = str_replace($from, $to, $current);
return $result;
}
Or you could use:
// define directory separator
define('DS', DIRECTORY_SEPARATOR);
function get_path($withSlash = true)
{
$path = realpath(dirname(__FILE__));
if ($trailingSlash) {
$path .= DS;
}
return $path;
}
You're stripping out the first slash (first character) - plus you're using \ instead of / in the path.
For the creation of paths you should use the PHP-function realpath to manage the slashes: http://php.net/realpath
Related
I have this short script to detect the user usage environment and try to normalize the root path:
Located in C:\xampp\htdocs\dev\t2\Last-Hammer\configs\const\loader.php
$env= '';
if (php_sapi_name() == 'cli') {
$env= 'cli';
if (!isset($_SERVER['PWD'])) {
$path = dirname(__DIR__).'\\';
} else {
$path = dirname($_SERVER['PWD']);
}
} else {
$env= 'web';
$path = $_SERVER['DOCUMENT_ROOT'];
}
echo $path;
echo PHP_EOL;
echo $env;
file_get_contents($path.'configs/const/client.xml')
i use it from 2 diferent files: index.php that wor well in root folder but trying to use it from a sub-directory like this /dev/cron.php
cron.php content:
$path = (!isset($_SERVER["PWD"]) ? dirname(__DIR__).'\\' : dirname($_SERVER["PWD"]));
require_once $path.'/configs/const/loader.php';
i get this output
//from Web environment
C:/xampp/htdocs/dev/t2/Last-Hammer/
web
and
//from CLI environment
C:\xampp\htdocs\dev\t2\Last-Hammer
cli
the problem is that this work correctly from Web environment but not work correctly in CLI, when i try to execute like: php cron.php code try to make a file_get_contents... like this using cli get this error:
PHP Warning: file_get_contents(C:\xampp\htdocs\dev\t2\Last-Hammer\configs\configs/const/client.xml): failed to open stream: No such file or directory in C:\xampp\htdocs\dev\t2\Last-Hammer\configs\const\loader.php on line 24
Warning: file_get_contents(C:\xampp\htdocs\dev\t2\Last-Hammer\configs\configs/const/client.xml): failed to open stream: No such file or directory in C:\xampp\htdocs\dev\t2\Last-Hammer\configs\const\loader.php on line 24
what is expected is that both for CLI or WEB, the root of the project is similar to: C:/xampp/htdocs/dev/t2/Last-Hammer/ and does not change constantly in the case of CLI depending on where it is executed the php file, as root could set in CLI. regardless of where it runs.
You are lacking trailing "\" on cli case. to uniform both, you could use str_replace():
$env= '';
if (php_sapi_name() == 'cli') {
$env= 'cli';
if (!isset($_SERVER['PWD'])) {
$path = dirname(__DIR__).'\\';
} else {
$path = dirname($_SERVER['PWD']).'\\';
}
} else {
$env= 'web';
$path = $_SERVER['DOCUMENT_ROOT'];
}
$path = str_replace( '\\', '/', $path );
echo $path;
echo PHP_EOL;
echo $env;
file_get_contents($path.'configs/const/client.xml')
define in your main scripts:
define('DOCROOT', '../'); // this in your cron.php
define('DOCROOT', './'); // this in your index.php
Just use relative paths:
$path = DOCROOT;
file_get_contents($path.'configs/const/client.xml')
Below I have left my code. It currently works in my development environment (localhost), but when I push the changes to my live server it seems like my php doesn't create the folder/file.
public static function saveImage($image, $name, $path = '')
{
$img_data = explode(',', $image);
$mime = explode(';', $img_data[0]);
$data = $img_data[1];
$extension = explode('/', $mime[0])[1];
if(!file_exists('../public/media/img/' . $path)){
mkdir('../public/media/img/' . $path, 0755);
echo('Test1');
}
echo('test2');
file_put_contents('../public/media/img/' . $path . $name . '.' . $extension, base64_decode($data));
return 'media/img/' . $path . $name . '.' . $extension;
}
Locally it will hit echo('test1') the first time, then it will only hit echo('test2'). When its on the server it always hits the echo('test1')
By default mkdir is not create a path recursively. An example if on your server you dont have a ../public/media folder, mkdir returns false and dont create a path.
To solve this pass a third parameter to mkdir as true:
mkdir('../public/media/img/' . $path, 0755, true);
Do yourself a favour and use absolute pathes...
You can use the constant __DIR__ to evaluate the folder in which the script actually resides.
Relative pathes are calculated from the current working directory, which can be different than __DIR__
I have a PHP application running in the Linux subsystem for Windows.
The application talks to an external .exe file that requires a filename as an input.
In my PHP application, I need to determine if the file exists before trying to send it to the external .exe file.
To summarise, when in my PHP application I need the Linux file path, but when passing it as an argument to the .exe I need the windows file path.
So it would look something like this:
<?php
$fn = '/mnt/c/myapp/myfile.png';
$exists = file_exists($fn);
if ($exists) {
shell_exec('external.exe -f ' . transformToWindowsPath($fn));
}
function transformToWindowsPath($fn)
{
// What should go here?
// Is something like this reliable?
return str_replace(
'/',
DIRECTORY_SEPARATOR,
preg_replace_callback(
'/\/mnt\/([a-zA-Z])\//',
function($matches) {
return strtoupper($matches[1]) . ":" . DIRECTORY_SEPARATOR;
},
$fn
)
);
}
Try with this function that converts the directory separator:
$fn = '/mnt/c/myapp/myfile.png';
function fnSystem($fn, $system='linux')
{
if($system == 'windows')
{
$fn = str_replace('/mnt/c/', '', $fn); // remove /mnt/c/ from front
$fn = str_replace('/', '\\', $fn); // convert the directory separator
$fn = "C://$fn"; // place C:// in front
}
elseif($system == 'linux')
{
$fn = str_replace('C://', '', $fn); // remove C:// from front
$fn = str_replace('\\', '/', $fn); // convert the directory separator
$fn = "/mnt/c/$fn"; // place /mnt/c/ in front
}
return $fn;
}
$fnWindows = fnSystem('/mnt/c/myapp/myfile.png', 'windows');
echo $fnWindows;
Result:
C://myapp\myfile.png
I'm using the below function:
class Image {
static function url($id, $type = 'maps') {
$path = UPLOAD_DIRECTORY . '/' . $type . '/';
$files = glob($path . $id . '.*');
if (count($files)) {
$ext = substr($files[0], strpos($files[0], '.') - strlen($files[5]));
return SERVER_URL . 'img/' . $type . '/' . $id . $ext;
} else {
return '';
}
}
}
It works fine when hosted on WAMP but when using on Unix running on nginx it doesn't display the image correctly because of the file path. It seems to add the physical path of the files in the URL so it thinks the patch of the file is http://localhost/demo/img/maps/20/public_html/demo/img/maps/20.png
On WAMP it displays correctly ie the URL is http://localhost/demo/img/maps/20.png
These are the defined variables:
define('SERVER_URL', 'http://localhost/demo/');
define('UPLOAD_DIRECTORY', dirname(__FILE__) . '/img');
id=20;
Physical location of the images are in /public_html/demo/img/maps/
How can I fix this on a unix OS.
Managed to work out a solution (btw I'm not a programmer).
Basically on the UNIX server the directory where the images were located had a dot in the path whereas on wamp it didn't.
So what I had to do is use the strrpost instead of strpost - this finds the position of the last occurrence of a substring in a string instead of the first occurance.
So I am trying to use rename function in php.
On the first try, if the destination folder is empty or does not contain any directories with the same name as the source folder the rename function works perfectly. However, if there is same directory name it fails. What I want is just to overwrite it and I thought rename() would suffice.
Here is my code:
/**
* Move temp folders to their permanent places
*
* $module_folder = example (violator, pnp, etc)
* $folders = name of folders within module_folder
**/
public function move_temp_to_permanent($module_folder, $folders){
$bool = false;
$module_folder_path = realpath(APPPATH . '../public/resources/temps/' . $module_folder);
$module_folder_destination_path = $_SERVER['DOCUMENT_ROOT'] . '/ssmis/public/resources/photos/' . $module_folder . '/';
foreach($folders as $folder){
$bool = rename($module_folder_path . '/' . $folder, $module_folder_destination_path . $folder);
}
return $bool;
}
The code above gives me an error saying:
Message:
rename(C:\xampp\htdocs\ssmis\public\resources\temps\violator/SJ-VIOL-2015-0002,C:/xampp/htdocs/ssmis/public/resources/photos/violator/SJ-VIOL-2015-0002):
Access is denied. (code: 5)
I am using CodeIgniter as framework.
Thank you very much!
If it is on Windows, this can be read in contributions:
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5. If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state. You can do something like this instead:
function rename_win($oldfile,$newfile) {
if (!rename($oldfile,$newfile)) {
if (copy ($oldfile,$newfile)) {
unlink($oldfile);
return TRUE;
}
return FALSE;
}
return TRUE;
}
Link.
You are adding extra / in path make this like
/**
* Move temp folders to their permanent places
*
* $module_folder = example (violator, pnp, etc)
* $folders = name of folders within module_folder
**/
public function move_temp_to_permanent($module_folder, $folders){
$bool = false;
$module_folder_path = realpath(APPPATH . '../public/resources/temps/' . $module_folder);
$module_folder_destination_path = $_SERVER['DOCUMENT_ROOT'] . '/ssmis/public/resources/photos/' . $module_folder . '/';
foreach($folders as $folder){
$bool = rename($module_folder_path . $folder, $module_folder_destination_path . $folder);
}
return $bool;
}
you can also echo the path you prepared so you can check its right or not