I can't read the path by use variable
$absPath = realpath('./');
//$absPath = /home/abc/domains/server2.abc.com/public_html/mockup
//$oldPath = /project_image/easy/Desert.jpg
$npath = $absPath."".$oldPath; //$oldPath is get by image element scr="xxx"
$npath will return this:
/home/abc/domains/server2.abc.com/public_html/mockup/project_image/easy/Desert.jpg
When i unlink it
unlink($npath);
Then php return
No such file or directory in /home/../mockup/update_file.php -> point unlink($npath);
And i try to Hard Code it
$npath = /home/abc/domains/server2.abc.com/public_html/mockup/project_image/easy/Desert.jpg
unlink($npath);
Then it will success.
I want to know how to use variable combine a new path to unlink it.
Sorry for my poor English
Are you sure your script is producing the exact same path? If you are building the path correctly and unlink is failing, you can try the shell instead. Sometimes this works like with samba mounts and what-not.
$absPath = realpath('./');
$npath = $absPath."".$oldPath;
// Bail if the path doesn't exist
if(!file_exists($npath)) die('Failed to build correct path');
// Try unlink via PHP
if(!unlink($npath) || file_exists($npath)) {
// PHP couldn't cut it, try unlink via shell
exec('rm ' . $npath, $output, $return);
if($return > 0)
die('Failed to delete file: ' . $npath);
}
Related
Understanding that the following question is not best practices by any means. The tool i am building is for personal use and will not be accessible to the internet in general. With that being said here is the idea or outline of what i am trying to accomplish.
PHP:
define("UPLOAD_DIR", "/var/www/html/uploads/");
if (!empty($_FILES["SANUpload"])) {
$myFile = $_FILES["SANUpload"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
$val = shell_exec("tar -xvf $parts -C /var/www/html/uploads 2>&1");
echo '$val';
}
The goal is once it gets uploaded I need to sort the files and put them in the correct spots. The upload will ALWAYS be a TAR file because the scripts that i built for it the ONLY output is a tar file.
My goal is to extract the tar file in uploads directory and then run move commands to move the files where they need to be. Then do a clean up and delete any files in the UPLOADS dir.
I found this example on here :
$val = shell_exec("tar -xvf $parts -C /var/www/html/uploads 2>&1");
echo '$val';
This is another component i am looking at as well:
try {
$phar = new PharData('myphar.tar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
The problem I am having with PharData is that it doesn't like the $path or $name variables. The same can be said for the example above PharData. Since the upload script could have different names I need to have the ability to unzip the file as a variable or to use a variable in the php script.
Technically - the script I have would keep the tar name the same however I could see a use case where someone might change that. So want to make sure that I have the option to address that.
So question is how do i extract a tar file - utilizing a variable name rather than have it spelled out and the actual name of the file all in PHP?
Figured out the issue - i needed to utilize the UPLOAD_DIR . $name in the pharData.
try {
$phar = new PharData(UPLOAD_DIR . $name);
$phar->extractTo(UPLOAD_DIR); // extract all files
} catch (Exception $e) {
// handle errors
}
I would like to know how to get the absolute file path of the file i have found using glob() function. I am able to find a desired file using
foreach (glob("access.php") as $filename) {
echo "$filename absolutepath is: ";
}
not sure what function gets the full path of the file searched. Tried to google but can't find anything sensible.
Thanks
Slight update :
I have noticed that glob() function only searches the directory that the script is run from - and that is not good to me. I need a function that is equivalent to unix find / -name "somename"
Any alternative ? or am i missing something with the glob() ??
If you have to look also for files in subdirectories, you could use something like the following:
foreach (glob("{access.php,{*/,*/*/,*/*/*/}access.php}", GLOB_BRACE) as $filename) {
echo "$filename absolutepath is: ".realpath($filename);
}
You can use realpath to get file absolute path. More info: http://www.php.net/manual/en/function.realpath.php
I thinkt you need realpath(), as described here: http://www.php.net/manual/en/function.realpath.php
foreach (glob("access.php") as $filename) {
echo "$filename absolutepath is: " . realpath($filename);
}
The directory in which the glob function searches is available through the getcwd function.
To search any directory, given its path, one may use the following code snippet:
$dirToList = '/home/username/documents';
$patternToSearch = '*.odt'; // e.g. search for LibreOffice OpenDocument files
$foundFiles = FALSE;
$olddir = getcwd();
if (chdir($dirToList)) {
$foundFiles = glob($patternToSearch);
chdir($olddir); // switch back to the dir the code was running in before
if ($foundFiles) {
foreach ($foundFiles as $filename) {
echo nl2br(htmlentities(
'found file: '.$dirToList.DIRECTORY_SEPARATOR.$filename."\n"
, ENT_COMPAT, 'UTF-8'));
}
}
// else echo 'no found files';
}
// else echo 'chdir error';
To finally satiesfy your wish to do a search like
find / -name "somename"
you may put that code snippet in a function and call it while iterating through the directory tree of interest using PHP's RecursiveDirectoryIterator class.
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
I have a filename stored with the directory as a value.
Ex. /var/www/remove_this.php
In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.
There are so many string editing functions, I don't know a good approach. Thanks!
dirname() will return you the directory part of the path
Use pathinfo() to get info about the file itself.
$file = '/var/www/remove_this.php';
$pathinfo = pathinfo($file);
$dir = $pathinfo['dirname']; // '/var/www/'
You could use string functions, but for this case PHP has some smarter directory functions:
$dir = dirname('/var/www/remove_this.php'); // /var/www
pathinfo is an excellent one as well.
<?php
$file="/var/www/remove_this.php";
$folder=dirname($var);
if (!file_exsts($folder))
{
if (mkdir($folder,777,true))
{
echo "Folder created\n";
} else
{
echo "Folder creation failed\n";
}
} else
{
echo "Folder exists already\n";
}
?>
The purpose of this code is to grab an update.zip file from a remote server, unzip it and save it to a local directory, updating, overwriting or creating the updated files.
I've almost got a non cURL version of this working, but I'd rather use this version. The first problem I have is that the path to the tmp folder is incorrect. I need a better method of sniffing that out (temporarily hardcoded)...
The 2nd problem is that the code's not working, but its not throwing an error. Its executing the $x branch but no zip extraction is taking place.
require('../../../wp-blog-header.php'); //enables wp security check and ABSPATH
$payload = file_get_contents('http://myserver.com/upgrade.zip'); //grab the file from the remote server
$target = ABSPATH .'wp-content/themes/mytheme/'; // this is the destination for the unzipped files
openZip($payload);
function openZip($file_to_open, $debug = false) {
global $target;
$file = ABSPATH . '/tmp/'.md5($file_to_open).'.zip'; //this should be home/myfolder/tmp but ABSPATH is giving the wrong path to the tmp directory.
$client = curl_init($file_to_open);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$fileData = curl_exec($client);
file_put_contents($file, $fileData);
$zip = new ZipArchive();
$x = $zip->open($file);
if($x === true) { //this is true, but no zip extraction?
$zip->extractTo($target);
$zip->close();
unlink($file);
} else {
if($debug !== true) {
unlink($file);
}
die("There was a problem. Please try again!");
}
}
The most likely cause here is that you're not actually writing the zip file data in your file_put_contents() call inside openZip. If you pass a zero-length file to $zip->open(), it will happily go about its way returning (bool)true, even though you obviously will not be able to extract anything from it. See this example.