Zend Framework PHP -> realpath() - php

im trying to create a Zend Framework custom Provider and here:
if($module == 'default'){
$modelsPath = dirname(__FILE__) . '/../application/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else
if(!$module == ''){
$modelsPath = dirname(__FILE__) . '/../application/' . $module . '/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else {
die('Please enter a module!');
}
when i im trying to create a path to the file and when its default module everything is ok, but when for ex. module is other word no matter what the realpath returns false?! where is the error?

try using the APPLICATION_PATH constant.
if($module == 'default'){
$modelsPath = APPLICATION_PATH . '/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else
if(!$module == ''){
$modelsPath = APPLICATION_PATH . '/' . $module . '/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else {
die('Please enter a module!');
}

Taken out of the php manual:
realpath() returns FALSE on failure, e.g. if the file does not exist.
Note:
The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.
So the problem most probably is with folder permission or the path simply is wrong!

Double check that the paths exist by simple echoing $filePath. If this checks out to be okay then ensure that the 'user' (apache, www-data, for example) have enough privileges. If you are not sure who your server is operating as you can simply debug by echoing whoami

Related

How can a create a folder and save a image on my server in php?

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__

php function to search paths for filename WITHOUT extension

Right so i'm making a configuration class that will use an array of different file types in 4 main locations. Now I want to make it so that the configuration class will search these locations in order at the moment i'm using the following
if (file_exists(ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file)) {
$this->filePath = ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file;
echo $this->filePath;
} else {
if (file_exists(ROOT . DS . "Application/Config/$file")) {
$this->filePath = ROOT . DS . "Application/Config/$file";
echo $this->filePath;
} else {
if (file_exists(CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file)) {
$this->filePath = CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file;
echo $this->filePath;
} else {
if (file_exists(CARBON_PATH . "Config/$file")) {
$this->filePath = CARBON_PATH . "Config/$file";
echo $this->filePath;
} else {
throw new \Exception("Unable to locate: $file, Please check it exists");
}
}
}
}
pretty messy and not very flexible.
What I want to be able to do is search the locations in the same order BY FILE NAME ONLY after finding the first match It would then return the file with the extension for the configuration class to use the correct method to parse into a php array and so on.
What is the best way to search these locations for a file name
Example
Say we want a database configuration file as you can see there are 2
ConfigLocation1/Dev/
/file.php
/database.json
ConfigLocation1/
/database.ini
/anotherfile.json
I would want to use the function like so
config::findFile('database');
and it return
$result = ConfigLocation1/Dev/database.json
but if it wasnt found here then then
$result = ConfigLocation1/database.ini
Not very good at explaining things so hope the example helps
As you mentioned you need to check for file in 4 locations, so instead of if conditions, create an array of directories and loop through.
and you can use glob, to find a file irrespective of extension. see my example below:-
//Make a array of directory where you want to look for files.
$dirs = array(
ROOT . DS . 'Application/Config/' . APP_ENV . DS,
CARBON_PATH . 'Config' . DS . APP_ENV . DS
);
function findFiles($directory, $filename){
$match = array();
foreach ($directory => $dir) {
$files = glob($dir.$filename);
foreach ($files as $file) {
$match[] = $file;
}
}
return $match;
}
// to find database
$results = findFiles($dirs, 'database.*');

Why isn't wordnik's php api loading the required classes?

I'm getting the following error with wordnik's php api
Fatal error: Class 'Example' not found in Swagger.php on line 212
I've edited Swagger.php to get it to work, below is the original function
function swagger_autoloader($className) {
$currentDir = substr(__FILE__, 0, strrpos(__FILE__, '/'));
if (file_exists($currentDir . '/' . $className . '.php')) {
include $currentDir . '/' . $className . '.php';
} elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
include $currentDir . '/models/' . $className . '.php';
}
}
The working code I changed to is
function swagger_autoloader($className)
{
include $currentDir . '/models/' . $className . '.php';
}
MORE INFO
My file structure is as follows.
WORDNIK (contains start.php)>>>WORDNIK (contains Swagger.php)>>MODELS (contains Example.php)
I'm using wampserver 2.2 with php 5.4.3
UPDATE/EDIT
Using the following code
function swagger_autoloader($className) {
echo "dirname(__FILE__)= ",dirname(__FILE__);
$currentDir = substr(__FILE__, 0, strrpos(__FILE__, '/'));
echo "currentDir=".$currentDir."</br>";
echo "className=".$className."</br>";
echo "__FILE__=",__FILE__."<br/>";
die();
I get the results
dirname(__FILE__)=D:\wamp\www\wordnik\wordnik
currentDir=
className=Example
__FILE__=D:\wamp\www\wordnik\wordnik\Swagger.php
As suggested by vcampitelli, using either __DIR__ or dirname(__FILE__) works.
MY QUESTION
Why doesn't the original function work?
UNIMPORTANT INFO
For people struggling through the examples, here is my start.php file
<?php
require('./wordnik/Swagger.php');
require('./wordnik/WordApi.php');
require('./wordnik/AccountApi.php');
require('./wordnik/WordsApi.php');
require('./wordnik/WordListApi.php');
require('./wordnik/WordListsApi.php');
$myAPIKey = 'replace_this_with_your_real_api';
$client = new APIClient($myAPIKey, 'http://api.wordnik.com/v4');
$wordApi = new WordApi($client);
$example = $wordApi->getTopExample('irony');
print $example->text;
?>
What does $currentDir return? Have you tried using __DIR__ or dirname(__FILE__) (they are the same) instead of that substr?
If you are using the second example just as you posted (without declaring $currentDir), so that is the problem at your original code: $currentDir is not returning the right folder!
With the original code, which file is being included? Because, actually, I think no one is! Use echo inside those if statements to check that!
The original function doesn't work because it is looking for the position of a UNIX-style forward slash '/', whereas you are on Windows and have backslashes '\'. That's a bug! I'll fix the lib to use dirname(FILE) as you do. Thanks for pointing out the error.

PHP Autoload ignorecase

Is there any way to call require_once with some "case insensitive flag" ?
In windows it's okay, but linux is case sensitive. Is there any way to override ?
Thanks
Sure, load
strtolower($className . ".php")
and name your files in lowercase.
Regardless of how you try to load your files, only the lowercase version will ever be loaded.
Just include some where else in you header.php or some other common file.,
<?php
$filename = basename($_SERVER['SCRIPT_FILENAME']);
$request = basename($_SERVER['SCRIPT_NAME']);
if($filename != $request)
die('Case of filename and request do not match!');
?>
I think this may help you resolve your problem. also refer the following location https://superuser.com/questions/431342/linux-both-case-sensitive-and-case-insensitive-and-always-inconvenient
You can use this every time you are loading you auto load the appropriate classes. yu have to change the directories depends on you project. you can you the echo or print_r to print what classes are loaded every time when you are calling something. also all you class names must ot have the same format for example, className.class.php e.g Dashboard.class.php, Category.class.php. you can use
ucwords to make the first letter capital.
function __autoload($className)
{
if (file_exists(__DIR__ . '/../library/' . strtolower($className) . '.class.php'))
{
require_once(__DIR__ . '/../library/' . strtolower($className) . '.class.php');
}
else if (file_exists(__DIR__ . '/../application/controllers/' . strtolower($className) . '.php'))
{
require_once(__DIR__ . '/../application/controllers/' . strtolower($className) . '.php');
}
else if (file_exists(__DIR__ . '/../application/models/' . strtolower($className) . '.php'))
{
require_once(__DIR__ . '/../application/models/' . strtolower($className) . '.php');
}
}

How to use Unlink() function

I'm trying to use PHP unlink() function to delete away the specific document in the folder. That particular folder has already been assigned to full rights to the IIS user.
Code:
$Path = './doc/stuffs/sample.docx';
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
It keep return fail. The sample.docx does reside on that particular path. Kindly advise.
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual
error to unlink file. To delete file you must to change the file's owner.
An example:
chown($tempDirectory . '/' . $fileName, 666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($tempDirectory . '/' . $fileName);
So try something like this:
$path = './doc/stuffs/sample.docx';
chown($path, 666);
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
EDIT 1
Try to use this in the path:
$path = '.'
. DIRECTORY_SEPARATOR . 'doc'
. DIRECTORY_SEPARATOR . 'stuffs'
. DIRECTORY_SEPARATOR . 'sample.docx';
Try this:
$Path = './doc/stuffs/sample.docx';
if (file_exists($Path)){
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
} else {
echo "file does not exist";
}
If you get file does not exist, you have the wrong path. If not, it may be a permissions issue.
This should work once you are done with the permission issue. Also try
ini_set('display_errors', 'On');
That will tell you whats wrong
define("BASE_URL", DIRECTORY_SEPARATOR . "book" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$path = "doc/stuffs/sample.docx";
if (unlink(ROOT_PATH . $Path)) {
echo "success";
} else {
echo "fail";
}
// http://localhost/book/doc/stuffs/sample.docx
// C:/xampp/htdocs\book\doc/stuffs/sample.docx
You need the full file path to the file of interest. For example: C:\doc\stuff\sample.docx. Try using __DIR__ or __FILE__ to get your relative file position so you can navigate to the file of interest.

Categories