I used php real path to get actual path of files and directory to delete and after deleted i will print all deleted
items. But my problem is that it also show the real path where the file source is and i don't want to show it to users
is there any way i can hide the pay and only show the file example.
I don't like it to look like this
[File]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg
[File]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/room_home_1.jpg
[Directory]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder
Is there anyway i can make it look this way using rejex or any method please i need help i have to remove /mnt/wef66/d2/81/557642661/htdocs/
[File]: www.example.com/useruploads/myfiles/imagefolder/mosaic_1.jpg
[File]: www.example.com/useruploads/myfiles/imagefolder/room_home_1.jpg
[Directory]: www.example.com/useruploads/myfiles/imagefolder
Maybe using something like this
echo preg_replace("/mnt/wef66/d2/81/557642661/htdocs", "www.example.com", "[File]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg");
$path = realpath($parentBas);
I would use configuration variables $privatePath and $publicPath.
So you can concat whichever you want to the relative paths to your directories or files.
For your example:
$privatePath = '/mnt/wef66/d2/81/557642661/htdocs/';
$publicPath = 'www.example.com/';
$pic1RelativePath = 'useruploads/myfiles/imagefolder/mosaic_1.jpg';
$pic1privatePath = $privatePath . $pic1RelativePath;
// /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg
$pic1publicPath = $publicPath . $pic1RelativePath;
// www.example.com/useruploads/myfiles/imagefolder/mosaic_1.jpg
I think this is easier and more efficient than replacing the paths with regex.
EDIT:
If you have all the real paths in an array, you can loop through it and replace easily all the private paths with the public paths this way:
$paths = [
'/mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg',
'/mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/room_home_1.jpg',
'/mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder'
];
foreach ($paths as &$path) {
$path = str_replace($privatePath, $publicPath, $path);
}
print_r($paths);
Related
I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.
Is there a way to copy and rename multiple files in php but get their names from an array or a list of variables.
The nearest thing to what I need that I was able to find is this page
Copy & rename a file to the same directory without deleting the original file
but the only thing the script on this page does is creating a second file and it's name is already preset in the script.
I need to be able to copy and create multiple files, like 100-200 and get their names set from an array.
If I have an initial file called "service.jpg"
I would need the file to be copied multiple times with the different names from the array as such :
$imgnames = array('London', 'New-York','Seattle',);
etc.
Getting a final result of 3 separate files called "service-London.jpg", "service-New-York.jpg" and so on.
I'm sure that it should be a pretty simple script, but my knowledge of PHP is really insignificant at the time.
One approach (untested) that you can take is creating a class to duplicate a directory. You mentioned you would need to get the name of the files in a directory and this approach will handle it for you.
It will iterate over an array of names (whatever you pass to it), and copy/rename all of the files inside a directory of your choice. You might want to add some checks in the copy() method (file_exists, etc) but this will definitely get you going and is flexible.
// Instantiate, passing the array of names and the directory you want copied
$c = new CopyDirectory(['London', 'New-York', 'Seattle'], 'location/of/your/directory/');
// Call copy() to copy the directory
$c->copy();
/**
* CopyDirectory will iterate over all the files in a given directory
* copy them, and rename the file by appending a given name
*/
class CopyDirectory
{
private $imageNames; // array
private $directory; // string
/**
* Constructor sets the imageNames and the directory to duplicate
* #param array
* #param string
*/
public function __construct($imageNames, $directory)
{
$this->imageNames = $imageNames;
$this->directory = $directory;
}
/**
* Method to copy all files within a directory
*/
public function copy()
{
// Iterate over your imageNames
foreach ($this->imageNames as $name) {
// Locate all the files in a directory (array_slice is removing the trailing ..)
foreach (array_slice(scandir($this->directory),2) as $file) {
// Generates array of path information
$pathInfo = pathinfo($this->directory . $file);
// Copy the file, renaming with $name appended
copy($this->directory . $file, $this->directory . $pathInfo['filename'] . '-' . $name .'.'. $pathInfo['extension']);
}
}
}
}
You could use a regular expression to build the new filenames, like this:
$fromFolder = 'Images/folder/';
$fromFile = 'service.jpg';
$toFolder = 'Images/folder/';
$imgnames = array('London', 'New-York','Seattle');
foreach ($imgnames as $imgname) {
$newFile = preg_replace("/(\.[^\.]+)$/", "-" . $imgname . "$1", $fromFile);
echo "Copying $fromFile to $newFile";
copy($fromFolder . $fromFile, $toFolder . $newFile);
}
The above will output the following while copying the files:
Copying service.jpg to service-London.jpg
Copying service.jpg to service-New-York.jpg
Copying service.jpg to service-Seattle.jpg
In the above code, set the $fromFolder and $toFolder to your folders, they can be the same folder, if so needed.
I have a standard config file: $variable = 'value';, but at the last moment came up to use the web interface to configure it. So what is the best way to read the file, find the value of variables and then resave the file again?
At the moment I have 2 ideas:
1) RegExp
2) Keep somewhere array example
Store all config values in an associative array like so:
$config = array(
'variable' => 'value'
);
For the web interface, you can easily loop over the entire array:
foreach($config as $key=>$value) { ... }
After making changes, loop over the array and write it back to the file. (You really should be using a DB for this, though).
When you include the file, you can either use it like this:
include('config.php');
echo $config['variable']
// or
extract($config);
echo $variable;
Note: If you extract, it will overwrite any variables by the same name you might have defined before extracting.
PS - To make it easier to read and write to and from a file, I would just use json encoding to serialize the array.
Use a db
If your config is user defined - it would be better to store the config in a database. Otherwise you have this "novel" problem to solve but also potentially introduce security problems. I.e. for any one user to be able to edit your config files - they must be writeable to the webserver user. That opens the door to injecting malicious code into this file from a web exploit - or simply someone with direct access to your server (shared host?) finding this writeable file and updating it to their liking (e.g. putting "<?php header('Location: my site'); die;" in it).
One config variable
If you must manage it with a config file, include the file to read it, and var_export the variables to write it. That's easiest to do if there is only one config variable, that is an array. e.g.:
function writeConfig($config = array()) {
$arrayAsString = var_export($config, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Allow partial updates
If you are changing only some variables - just include the config file before rewriting it:
function writeConfig($edits = array()) {
require 'config.php';
$edits += $config;
$arrayAsString = var_export($edits, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Multiple config variables
If you have more than one variable in your config file, make use of get defined vars and loop on them to write the file back:
function writeConfig($_name = '', $_value) {
require 'config.php';
$$_name = $_value; // This is a variable variable
unset($_name, $_value);
$string = "<?php\n";
foreach(get_defined_vars() as $name => $value) {
$valueAsString = var_export($value, true);
$string .= "\$$name = $valueAsString;\n";
file_put_contents('config.php', $string);
}
}
The above code makes use of variable variables, to overwrite once of the variables in the config file. Each of these last two examples can easily be adapted to update multiple variables at the same time.
In the script below, I'm attempting to iterate over the folders and files inside of the $base folder. I expect it to contain a single level of child folders, each containing a number of .txt files (and no subfolders).
I'm just needing to understand how to reference the elements in comments below...
Any help much appreciated. I'm really close to wrapping this up :-)
$base = dirname(__FILE__).'/widgets/';
$rdi = new RecursiveDirectoryIterator($base);
foreach(new RecursiveIteratorIterator($rdi) as $files_widgets)
{
if ($files_widgets->isFile())
{
$file_name_widget = $files_widgets->getFilename(); //what is the filename of the current el?
$widget_text = file_get_contents(???); //How do I reference the file here to obtain its contents?
$sidebar_id = $files_widgets->getBasename(); //what is the file's parent directory name?
}
}
//How do I reference the file here to obtain its contents?
$widget_text = file_get_contents(???);
$files_widgets is a SplFileInfo, so you have a few options to get the contents of the file.
The easiest way is to use file_get_contents, just like you are now. You can concatenate together the path and the filename:
$filename = $files_widgets->getPathname() . '/' . $files_widgets->getFilename();
$widget_text = file_get_contents($filename);
If you want to do something funny, you can also use openFile to get a SplFileObject. Annoyingly, SplFileObject doesn't have a quick way to get all of the file contents, so we have to build a loop:
$fo = $files_widgets->openFile('r');
$widget_text = '';
foreach($fo as $line)
$widget_text .= $line;
unset($fo);
This is a bit more verbose, as we have to loop over the SplFileObject to get the contents line-by-line. While this is an option, it'll be easier for you just to use file_get_contents.
I need to change the folder that "relative include paths" are based on.
I might currently be "in" this folder:
C:\ABC\XYZ\123\ZZZ
And in this case, the path "../../Source/SomeCode.php" would actually be in this folder:
C:\ABC\XYZ\Source
And realpath('.') would = 'C:\ABC\XYZ\123\ZZZ';
If however, realpath('.') were "C:\Some\Other\Folder"
Then in this case, the path "../../Source/SomeCode.php" would actually be in this folder:
C:\Some\Source
How do I change what folder is represented by '.' in realpath()?
Like this:
echo ('BEFORE = '.realpath('.')); // BEFORE = C:\ABC\XYZ\123\ZZZ
// Some PHP code here...
echo ('AFTER = '.realpath('.')); // AFTER = C:\Some\Other\Folder
How can I change the folder represented by '.', as seen by realpath()?
The function chdir() does this.
For example:
echo ('BEFORE = '.realpath('.')); // BEFORE = C:\ABC\XYZ\123\ZZZ
chdir('C:/Some/Other/Folder');
echo ('AFTER = '.realpath('.')); // AFTER = C:\Some\Other\Folder
Use the chdir() function.
Change your current working directory with chdir()
http://us.php.net/chdir