$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);
Related
This is my upload php:
if (trim($_FILES['path_filename']['name']))
{
if (File::upload($_FILES['path_filename'], dirname(realpath(__FILE__)) . '/../tests'))
{
$test->setPathFilename('../tests/' . $_FILES['path_filename']['name']);
}
}
}
else
{
if ($aux)
{
$aux = str_replace("\\", "/", $aux);
$aux = preg_replace("/[\/]+/", "/", $aux);
$test->setPathFilename($aux);
}
}
$_POST["upload_file"] = $test->getPathFilename();
This above code is working well, I mean, upload to server is working and also getting Path File Name and insert into sql table is working too.
Example: When I upload a file for example: ABC.jpg , it will upload to tests folder and also Path File Name is (( ../tests/ABC.jpg )) and it will insert to sql table.
The problem is here:
I changed global function to rename files automatically by using this following code:
Before It was:
$destinationName = $file['name'];
I changed it to:
$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
$destinationName = sha1_file($file["tmp_name"]).time().".".$ext;
Now, After upload file to tests folder, it will be renamed automatically, but still Path File name is same, It's ABC.jpg not renamed file in tests folder.
How to get Renamed Path File Name ???
I really appreciate your help on this issue.
Thanks in advance
Use basename() to get the filename from a path.
$filename = basename('/path/to/file.ext');
This will give you: file.ext
To rename the path file name you could use this:
if ( !file_exists( $path ) ) {
mkdir( $path, 0777, true );
}
This will make sure the path exist and if it doesn't it will created. Now we can rename()
rename( __FILE__ "/new/path/".$file_name );
This will move it between directories if necessary.
I'm trying to create a folder tree from an array, taken from a string.
$folders = str_split(564);
564 can actually be any number. The goal is to create a folder structure like /5/6/4
I've managed to create all folders in a single location, using code inspired from another thread -
for ($i=0;$i<count($folders);$i++) {
for ($j=0;$j<count($folders[$i]);$j++) {
$path .= $folders[$i][$j] . "/";
mkdir("$path");
}
unset($path);
}
but this way I get all folders in the same containing path.
Furthermore, how can I create these folders in a specific location on disk? Not that familiar with advanced php, sorry :(
Thank you.
This is pretty simple.
Do a for each loop through the folder array and create a string which appends on each loop the next sub-folder:
<?php
$folders = str_split(564);
$pathToCreateFolder = '';
foreach($folders as $folder) {
$pathToCreateFolder .= DIRECTORY_SEPARATOR . $folder;
mkdir($folder);
}
You may also add the base path, where the folders should be created to initial $pathToCreateFolder.
Here you'll find a demo: http://codepad.org/aUerytTd
Or you do it as Michael mentioned in comments, with just one line:
mkdir(implode(DIRECTORY_SEPARATOR, $folders), 0777, TRUE);
The TRUE flag allows mkdir to create folders recursivley. And the implode put the directory parts together like 5/6/4. The DIRECTORY_SEPARATOR is a PHP constant for the slash (/) on unix machines or backslash (\) on windows.
Why not just do:
<?php
$directories = str_split(564);
$path = implode(DIRECTORY_SEPARATOR, $directories);
mkdir($path, 0777, true);
Don't know what you're really trying to do, but here are some hints.
There are recursive mkdir:
if(!file_exists($dir)) // check if directory is not created
{
#mkdir($dir, 0755, true); // create it recursively
}
Path you want can be made in two function calls and prefixed by some start path:
$path = 'some/path/to/cache';
$cache_node_id = 4515;
$path = $path.'/'.join('/', str_split($cache_node_id));
Resulting path can be used to create folder with the code above
So here we come to a pair of functions/methods
function getPath($node_id, $path = 'default_path')
{
return $path.'/'.join('/', str_split($node_id))
}
function createPath($node_id, $path = 'default_path');
{
$path = getPath($node_id, $path);
if(!file_exists($path)) // check if directory is not created
{
#mkdir($path, 0755, true); // create it recursively
}
}
With these you can easily create such folders everywhere you desire and get them by your number.
As mentioned earlier, the solution I got from a friend was
$folders = str_split(564);
mkdir(implode('/',$folders),0777,true);
Also, to add a location defined in a variable, I used
$folders = str_split($idimg);
mkdir($path_defined_earlier. implode('/',$folders),0777,true);
So thanks for all the answers, seems like this was the correct way to handle this.
Now the issue is that I need to the created path, so how can I store it in a variable? Sorry if this breaches any rules, if I need to create a new thread I'll do it...
I need to know if a folder exists before creating it, this is because I store pictures inside and I fear that the pictures are deleted if overwrite the folder.
The code I have to create a folder is as follows
$path = public_path().'/images';
File::makeDirectory($path, $mode = 0777, true, true);
how can I do it?
See: file_exists()
Usage:
if (!file_exists($path)) {
// path does not exist
}
In Laravel:
if(!File::exists($path)) {
// path does not exist
}
Note: In Laravel $path start from public folder, so if you want to check 'public/assets' folder the $path = 'assets'
With Laravel you can use:
$path = public_path().'/images';
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
By the way, you can also put subfolders as argument in a Laravel path helper function, just like this:
$path = public_path('images/');
You can also call this method of File facade:
File::ensureDirectoryExists('/path/to/your/folder')
which creates a folder if it does not exist and if exists, then does nothing
In Laravel 5.x/6 you can do it with Storage Facade:
use Illuminate\Support\Facades\Storage;
$path = "path/to/folder/";
if(!Storage::exists($path)){
Storage::makeDirectory($path);
}
Way -1 :
if(!is_dir($backupLoc)) {
mkdir($backupLoc, 0755, true);
}
Way -2 :
if (!file_exists($backupLoc)) {
mkdir($backupLoc, 0755, true);
}
Way -3 :
if(!File::exists($backupLoc)) {
File::makeDirectory($backupLoc, 0755, true, true);
}
Do not forget to use use Illuminate\Support\Facades\File;
Way -4 :
if(!File::exists($backupLoc)) {
Storage::makeDirectory($backupLoc, 0755, true, true);
}
In this way you have to put the configuration first in config folder
filesystems.php . [Not recommended unless you are using external disks]
The recommended way is to use
if (!File::exists($path))
{
}
See the source code
If you look at the code, it's calling file_exists()
I normally create random folders inside the images for each file this helps a bit in encrypting urls and thus public will find it hardr to view your files by simply typing the url to your directory.
// Check if Logo is uploaded and file in random folder name -
if (Input::hasFile('whatever_logo'))
{
$destinationPath = 'uploads/images/' .str_random(8).'/';
$file = Input::file('whatever_logo');
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$savedPath = $destinationPath . $filename;
$this->whatever->logo = $savedPath;
$this->whatever->save();
}
// otherwise NULL the logo field in DB table.
else
{
$this->whatever->logo = NULL;
$this->whatever->save();
}
This is what works great for me
if(!File::exists($storageDir)){
File::makeDirectory($storageDir, 0755, true, true);
$img->save('Filename.'.png',90);
}
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.
I am trying to create a web app using codeigniter which will be used over a home or office network. Now Im looking for a backup option which can be done from the web protal. For example, in my htdocs folder i have: App1, App2 etc.
i want to backup and download the App1 folder directly from the webapp which can be done from any client machine which is connected to the server. is it possible. if yes then can you please let me know how?
~muttalebm
sorry for the late reply. I found a quite easy and simple backup option builtin with codeigniter. Hope this helps someone
$this->load->library('zip');
$path='C:\\xampp\\htdocs\\CodeIgniter\\';
$this->zip->read_dir($path);
$this->zip->download('my_backup.zip');
i used the code directly from the view and then just called it using the controller.
~muttalebm
Basically what you want to do is zip the application folder and download it, fairly simple to do. Please check out:
Download multiple files as a zip folder using php
On how to zip a folder for download.
I you do not have that extension a simple command can be used instead, I assume you are running on Linux if not replace command with zip/rar Windows equivalent:
$application_path = 'your full path to app folder without trailing slash';
exec('tar -pczf backup.tar.gz ' . $application_path . '/*');
header('Content-Type: application/tar');
readfile('backup.tar.gz');
Note: Make every effort to protect this file from being accessed by unauthorized users otherwise a malicious user will have a copy of your site code including config details.
// to intialize the path split the real path by dot .
public function init_path($string){
$array_path = explode('.', $string);
$realpath = '';
foreach ($array_path as $p)
{
$realpath .= $p;
$realpath .= '/';
}
return $realpath;
}
// backup files function
public function archive_folder($source = '' , $zip_name ='' , $save_dir = '' , $download = false){
// Get real path for our folder
$name = 'jpl';
if($zip_name == '')
{
$zip_name = $name."___(".date('H-i-s')."_".date('d-m-Y').")__".rand(1,11111111).".zip";
}
$realpath = $this->init_path($source);
if($save_dir != '')
{
$save_dir = $this->init_path($save_dir);
}else{
if (!is_dir('archives/'))
mkdir('archives/', 0777);
$save_dir = $this->init_path('archives');
}
$rootPath = realpath( $realpath);
// echo $rootPath;
// return;
// Initialize archive object
$zip = new ZipArchive();
$zip->open($save_dir . '\\' . $zip_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
if($download){
$this->download($zip);
}
}