I need to look for and echo an image file name that's located in either of these two directories named 'photoA' or 'photoB'.
This is the code I started with that tries to crawl through these directories, looking for the specified file:
$file = 'image.jpg';
$dir = array(
"http://www.mydomain.com/images/photosA/",
"http://www.mydomain.com/images/photosB/"
);
foreach( $dir as $d ){
if( file_exists( $d . $file )) {
echo $d . $file;
} else {
echo "File not in either directories.";
}
}
I feel like I'm way off with it.
You cannot use a url in file_exists, you need to use an absolute or relative path (relative to the runnings script) in the file-system of the server, so for example:
$dir = array(
"images/photosA/",
"../images/photosB/",
"/home/user/www/images/photosB/"
);
You can also use paths relative to the root of the web-server if you don't know the exact path and add the document root before that:
$dir = array(
$_SERVER['DOCUMENT_ROOT'] . "/images/photosA/",
$_SERVER['DOCUMENT_ROOT'] . "/images/photosB/"
);
(or you use it once, where you use file_exists())
Since you are running this script from within the root directory of your website, you won't need to define 'http://www.mydomain.com/' as this will cause Access Denied issues as it is not an absolute/relative file path. Instead, if the images/ folder is at the same directory level as your PHP script, all you will need to do is
$dir = array(
"images/photosA/",
"images/photosB/"
);
Otherwise, just add the absolute path as needed to make it work, but you can not put the. The rest seems as if it should work fine.
As the others said, file_exists() is for local files.
If you REALLY need to look for files over http, you can use :
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
NOTE: This relies on the server returning a 404 if the image does not exist. If the server instead redirects to an index page or a pporly-coded error page, you could get a false success.
Related
I'm trying to figure out, how to delete correctly image file with summernote from directory folder on remote server and localhost.
So, image successfully uploaded from summernote editor and located by directory path:
C:/xampp/htdocs/user/blog/uploads/img-uploads/154_20220702.png
and C:\xampp\htdocs\user\blog\admin\editor-delete.php code:
<?php
$src = $_POST['src'];
$path = "../uploads/img-uploads/";
$dir = basename($path);
$file_name = str_replace($dir, '', $src);
unlink($file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
?>
or
$src = $_POST['src'];
$dir = "../uploads/img-uploads/";
$file_name = str_replace($dir, '', $src);
unlink($file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
Warning: unlink(): http does not allow unlinking in
C:\xampp\htdocs\user\blog\admin\editor-delete.php
$src = $_POST['src'];
$dir = "../uploads/img-uploads/";
$file_name = str_replace($dir, '', $src);
unlink($_SERVER['DOCUMENT_ROOT'] . $file_name);
if ($file_name) {
echo 'File Delete Successfully';
}
Localhost correct path must be C:/xampp/htdocs/blog/uploads/img-uploads/154_20220702.png, but with unlink($_SERVER['DOCUMENT_ROOT'] .'/'. $file_name); the path contains extra http://localhost/user/ in C:/xampp/htdocs/http://localhost/user/blog/uploads/img-uploads/154_20220702.png
Warning:
unlink(C:/xampp/htdocshttp://localhost/user/blog/uploads/img-uploads/154_20220702.png):
No such file or directory in
C:\xampp\htdocs\user\blog\admin\editor-delete.php
File Delete Successfully
jquery-3.6.0.min.js:5177 XHR finished loading: POST
"http://localhost/user/blog/admin/editor-delete.php".
I cannot completely test this but I think you could change the editor-delete.php script like this. Judging by the paths cited in the question you need to construct the absolute path by leaving the admin directory traversing the file structure into uploads/img-uploads so chdir and getcwd are two useful functions for this. The notes in the code show what I mean.
The piece of code that displays the File Delete Successfully is based upon a variable which will always be true (effectively) rather than the more meaningful result from the actual unlink operation so you should use that returned value to fork your program logic.
<?php
/*
C:\xampp\htdocs\user\blog\admin\editor-delete.php
so:
chdir('../') leads to C:\xampp\htdocs\user\blog\
chdir('../uploads/img-uploads') should lead to C:\xampp\htdocs\user\blog\uploads\img-uploads
*/
if( isset( $_POST['src'] ) ){
# Change working directory for current script operations
# - go up one level out of "admin" and into the uploads folder.
chdir('../uploads/img-uploads');
# default value for use later in output message
$status=false;
# construct the full path to local file using getcwd() to find working directory.
$path=sprintf( '%s/%s', getcwd(), basename( $_POST['src'] ) );
# if the file exists - delete it or warn ( inspect the path! )
if( file_exists( $path ) )$status=#unlink( $path );
else exit( sprintf( 'Unable to find file: "%s"', $path ) );
# prevent cached results tainting file checks
clearstatcache();
echo $status ? 'File deleted successfully' : 'Sorry, that file could not be deleted';
}
?>
I'm trying to list files in a folder. I have done this before, so I am not sure why I am having a problem now.
I have a PDF files I am trying to display to my web page. The directory structure looks like this:
folder1/folder2/displayFiles.php
folder1/folder2/files.pdf
displayFiles.php is the process file where I am using the code below.
I am trying to display the file called files.pdf onto the page, which is in the same directory as the process file.
Here is my code so far:
<?php
$dir = "folder1/folder2/";
// $dir = "/"; <-- I also tried this
$ffs = scandir($dir);
foreach($ffs as $ff)
{
if($ff != '.' && $ff != '..')
{
$filesize = filesize($dir . '/' . $ff);
echo "<ul><li><a download href='$dir/$ff'>$ff</a></li></ul>";
}
}
?>
I know it's a simple fix. I just cannot find the code to fix it.
Your $dir is pointing at a non-existent folder
Change the dir to point to the folder correctly $dir = ".";.
Just use glob
http://php.net/manual/de/function.glob.php
$pdfs = glob("*.pdf"); // if needed loop through your directorys and glob files
print_r($pdfs);
Just an example. You should be able to use it with some edits.
$ad_title = $_POST['title'];
$ad_content = $_POST['content-ads'];
$ad_region = $_POST['region'];
if (!is_dir("uploads/".$ad_region)) {
// dir doesn't exist, make it
mkdir("uploads/".$ad_region);
echo "directory created!";
}
else {
echo "directory already exist!";
}
I am making a site and I am developing it in localhost for now. My save.php file and the uploads folders where the codes above is saved in the local directory
localhost/system/modules/new/
When I relocated the save.php file and the uploads folder in the directory
localhost/system/
all seems to be working now. But I want it to work in the
localhost/system/modules/new/
directory for better organization. Any help on how to make it work?
First thing I'd do is ensure that the paths are where you think they are.
Try this out
$ad_title = $_POST['title'];
$ad_content = $_POST['content-ads'];
$ad_region = $_POST['region'];
// Make sure the "uploads" directory is relative to this PHP file
$uploads = __DIR__ . '/uploads';
$path = $uploads . DIRECTORY_SEPARATOR . $ad_region;
// ensure that the path hasn't been tampered with by entering any relative paths
// into $_POST['region']
if (dirname($path) !== $uploads) {
throw new Exception('Upload path has been unacceptably altered');
}
if (!is_dir($path)) {
if (!mkdir($path, 0755, true)) {
// you should probably catch this exception somewhere higher up in your
// execution stack and log the details. You don't want end users
// getting information about your filesystem
throw new Exception(sprintf('Failed to create directory "%s"', $path));
}
// Similarly, you should only use this for debugging purposes
printf('Directory "%s" created', $path);
} else {
// and this too
printf('Directory "%s" already exists', $path);
}
you can use relative path ../ such as mkdir("../uploads/".$ad_region)
or use absolution path, such as mkdir("/localhost/system/modules/new/".$ad_region)
ref: http://php.net/manual/en/function.mkdir.php
You can use absolute file paths, like "/var/www/system/modules/new/$ad_region" (unix structure).
Or, for example, if your save.php file is in directory "system" and you want to create the directory in "system/modules/new/" you can do
mkdir("./modules/new/$ad_region");
There is a third parameter for mkdir, recursive, which allows the creation of nested directories. For the second parameter you can simple pass 0, for example
mkdir("./modules/new/$ad_region", 0, true);
I am able to get the web path to the file like so:
$filename = 'elephant.jpg';
$path_to_file = $this->getSkinUrl('manufacturertab');
$full_path = $path_to_file . '/' . $filename;
But if the file doesn't exist, then I end up with a broken image link.
I tried this:
if(!file_exists($full_path)) {
Mage::log('File doesn\'t exist.');
} else {
?><img src="<?php echo $full_path ?>" /><?php
}
Of course that didn't work because file_exists does not work on urls.
How do I solve this?
1.)
Can I translate between system paths and web urls in Magento?
e.g. something like (pseudocode):
$system_path = $this->getSystemPath('manufacturertab');
That looks symmetrical and portable.
or
2.)
Is there some PHP or Magento function for checking remote resource existence? But that seems a waste, since the resource is really local. It would be stupid for PHP to use an http method to check a local file, wouldn't it be?
Solution I am currently using:
$system_path = Mage::getBaseDir('skin') . '/frontend/default/mytheme/manufacturertab'; // portable, but not pretty
$file_path = $system_path . '/' . $filename;
I then check if file_exists and if it does, I display the img. But I don't like the asymmetry between having to hard-code part of the path for the system path, and using a method for the url path. It would be nice to have a method for both.
Function
$localPath = Mage::getSingleton( 'core/design_package' )->getFilename( 'manufacturertab/' . $filename, array( '_type' => 'skin', '_default' => false ) );
will return the same path as
$urlPath = $this->getSkinUrl( 'manufacturertab/' . $filename );
but on your local file system. You can omit the '_default' => false parameter and it will stil work (I left it there just because getSkinUrl also sets it internaly).
Note that the parameter for getSkinUrl and getFilename can be either a file or a directory but you should always use the entire path (with file name) so that the fallback mechanism will work correctly.
Consider the situation
skin/default/default/manufacturertab/a.jpg
skin/yourtheme/default/manufacturertab/b.jpg
In this case the call to getSkinUrl or getFilename would return the path to a.jpg and b.jpg in both cases if file name is provided as a parameter but for your case where you only set the folder name it would return skin/yourtheme/default/manufacturertab/ for both cases and when you would attach the file name and check for a.jpg the check would fail. That's why you shold always provide the entire path as the parameter.
You will still have to use your own function to check if the file exists as getFilename function returns default path if file doesn't exist (returns skin/default/default/manufacturertab/foo.jpg if manufacturertab/foo.jpg doesn't exist).
it help me:
$url = getimagesize($imagepath); //print_r($url); returns an array
if (!is_array($url))
{
//if file does not exists
$imagepath=Mage::getDesign()->getSkinUrl('default path to image');
}
$fileUrl = $this->getSkinUrl('images/elephant.jpg');
$filePath = str_replace( Mage::getBaseUrl(), Mage::getBaseDir() . '/', $fileUrl);
if (file_exists($filePath)) {
// display image ($fileUrl)
}
you can use
$thumb_image = file_get_contents($full_path) //if full path is url
//then check for empty
if (#$http_response_header == NULL) {
// run check
}
you can also use curl or try this link http://junal.wordpress.com/2008/07/22/checking-if-an-image-url-exist/
Mage::getBaseDir() is what you're asking for. For your scenario, getSkinBaseDir() will perform a better job.
$filename = 'elephant.jpg';
$full_path = Mage::getDesign()->getSkinBaseDir().'/manufacturertab/'.$filename;
$full_URL=$this->getSkinUrl('manufacturertab/').$filename;
if(!is_file($full_path)) {
Mage::log('File doesn\'t exist.');
} else {
?><img src="<?php echo $full_URL ?>" /><?php
}
Note that for the <img src> you'll need the URL, not the system path. ...
is_file(), rather than file_exists(), in this case, might be a good option if you're sure you're checking a file, not a dir.
You could use the following:
$file = 'http://mysite.co.za/files/image.jpg';
$file_exists = (#fopen($file, "r")) ? true : false;
Worked for me when trying to check if an image exists on the URL
Hi
I have a php file at, say, localhost/foo/foo/bar.php
which includes a file at localhost/foo/included.php
I need to be able to get "localhost/foo/" as a string inside included.php
If, instead of localhost/foo/foo/bar.php, it's localhost/big/burpy/lolz/here.php (still including included.php) I still need to get "localhost/foo/"
So, I need the path of the included file and not the one that the client requested.
I know when I see the solution I'm going to feel like a doofus, but it just escapes me at the moment. Help please? thanks :)
This how it got working for me :)
<?php
$path = (#$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
$path .=$_SERVER["SERVER_NAME"]. dirname($_SERVER["PHP_SELF"]);
echo $path;
?>
I figured it out myself:
$realpath = str_replace('\\', '/', dirname(__FILE__));
$whatIwanted = substr_replace(str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath), "", -6);
There we go :) Thanks for the help guys.
Inside your included file:
$yourdir = dirname(__FILE__);
or if you're using PHP 5.3.x:
$yourdir = __DIR__;
Get the document root from
// contains the document root, e.g. C:\xampp\htdocs
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
// strip drive letter if found
if(strpos($docRoot, ':') === 1) $docRoot = substr($docRoot, 2);
// directory of included file, e.g. C:\xampp\htdocs\include
$dirInclude = realpath(dirname(__FILE__));
// strip drive letter if found
if(strpos($dirInclude, ':') === 1) $dirInclude = substr($dirInclude, 2);
// find the document root
$rootPos = strpos($dirInclude, $docRoot);
// if the path really starts with the document root
if($rootPos === 0){
// example: \xampp\htdocs\include
$visibleDir = substr($rootPos, $);
// convert backslashes to slashes and strip drive letter
$webPath = str_replace('\\', '/', $visibleDir);
// yields: http://localhost/include
echo 'http://localhost' . $webPath;
}
else{
// included file was outside the webroot, nothing to do...
}
The steps for this are:
Use dirname(__FILE__) to get the folder of the include file.
Get the server root using $_SERVER['DOCUMENT_ROOT']
Remove the document root from the include folder to get the relative include folder
Obtain the server url
Append the relative include folder to the server url