i have a question that how to get name of a directory that is dynamically created?
explanation-:
i create a file upload type and one submit button whenever i clicked submit button then directory is created if not exist with logged in username. but file is not stored there because i can't get a name of directory to store that file.
i want how to get that name which function is used in php to get name of directory that is created dynamically.
//$image = $_GET['upload'];
$upload = $_POST["submit"];
session_start();
$_SESSION['x'] = "username";
$path = "upload/";
$image_name = $_FILES["upload"]["name"];
$temp = $_FILES["upload"]["tmp_name"];
if(isset($upload)){
mkdir($path.$_SESSION['x']);
$new = ""//what function I used here to fetch the name of directory in last step
move_uploaded_file($temp,$new.$image_name);
}
The directory name is $path.$_SESSION['x'].
Related
I have a piece of code to upload a picture and save it in a folder and the path in a databaseand show it on the webpage. Funny enough, upon uploading the picture for the first time, the image will show on the webpage and with change when I upload a new picture. But when I close the page, reopen it another day and decide to change the picture, the one of the webpage won't change even if i refresh the page but the one in the folder will change.
Here's my code
<?php
$sql2 = "SELECT Picture_HD FROM detailss WHERE Idn_nom = '$Indnum'";
require('connect.php');
$addr = "";
$addr = mysqli_query($conn, $sql2);
if ($addr) {
$locat = $addr->fetch_row();
$locat = (string)$locat[0];
} else {
$locat = "Pictures/default1.png";
}
mysqli_close($conn);
echo "<div id = 'Img'>";
echo "<img src = '" . $locat . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
echo "</div>";
?>
Your browser is caching the image.
If you want to prevent the browser to cache the image just add a random parameter at the end of the url.
echo "<img src = '" . $locat . "?t=" . time() . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
If your image is changing in your folder but you are seeing the old one on the webpage it's likely a caching issue, clear your browser cache (ctrl+f5 plus this is kinda broken so doesn't always work - so best to go into browser settings to do it, or open a private window after ctrl+f5) and if not the clear server level cache.
The best way to do this is to delete the existing image right before uploading the new one with the same file name
// define variables used for file name from session variable username the directory and extension by exploding the file name from the post method from a form with a metadata type
//set new file name to username from session variable
$filename = $_SESSION['username']
// set directory of files
$dir = "img/";
// set extension variable to file extension after posted from form
$ext=strtolower(end(explode('.',$_FILES['importimg']['name'])));
// new file upload name with existing extension
$upload_file = $dir . $filename . "." . $ext;
// delete file
// find all files with the same name any extension using variable defined above etc .txt, .php, .gif, .jpg, etc. then delete it
foreach (glob("img/$filename.*") as $deletefile) {
// unlink is used to delete the file and delete the cache of the file
unlink($deletefile);
}
// upload image
// upload file with type posted from metadata in form and upload it as your new file name using upload_file variable
if (move_uploaded_file($_FILES['importimg']['tmp_name'], $upload_file)) {
// successful upload of file add code for msg or sql query etc name to users table and redirect to profile page
echo "Successfully uploaded your file.";
} else {
// upload error show message
echo "There was an error uploading your file.";
}
Enjoy
I have a code in codeigniter which i will store the path of my image in my database. It works fine in inserting but the path is not correct.
My folder name of my upload images are stored in upimages.
The upimages is located in outside of application folder in codeigniter where i created assets/upimages. Here is my path code in inserting to database:
$data = $this->upload->data();
$image_path = $data['full_path'];
//var_dump($image_path);
$userid = ($this->session->userdata['logged_in']['user_id']);
$imagedb = $this->prof_model->user_img($image_path,$userid);
if(file_exists($image_path)) {
$status = "success";
$msg = "File successfully uploaded";
}
my image_path is the full path of my image but it outputs none if i call it again and here is the output of the full_path in my database:
C:/xampp/htdocs/Uploadtest/assets/upimages/test.jpg
when i change the path in my db and change it to :
http://localhost/Uploadtest/assets/upimages/test.jpg
it works fine.
my question is. how can i adjust my full_path to come up with the 2nd path. Remember that the location of my upimages is outside of the application folder which i created an asset/upimages
Try to make your file path as like as following:
$image_url = base_url().'assets/upimages/'.$data['upload_data']['file_name'];
$imagedb = $this->prof_model->user_img($image_url,$userid);
I have a function that saves the image in the respective folder.
I want to check if the image already exist in the folder , first with name if the name are same then with the SHA1 of the image
My current function looks something like this
function descargarImagen($id,$url,$pais1)
{
$ruta = rutaBaseImagen($id,$_POST['pais']);
$contenido = file_get_contents($url);
$ext = explode('.', $url);
$extension = $ext[count($ext) -1];
$imagen['md5'] = md5($contenido);
$imagen['sha1'] = sha1($contenido);
$imagen['nombre'] = $imagen['md5'].'.'.$extension;
$ficherof = $pais[$pais1]['ruta_imagenes'].'/'.$ruta.'/'.$imagen['nombre'];
$ficherof = str_replace('//', '/', $ficherof);
//Here before putting the file I want to check if the image already exist in the folder
file_put_contents($ficherof, $contenido);
$s = getimagesize($ficherof);
$imagen['mime'] = $s["mime"];
$imagen['size'] = $s[0].'x'.$s[1];
$imagen['url'] = $urlbase_imagenes.'/'.$ruta.'/'.$imagen['nombre'];
$imagen['url'] = str_replace('//', '/', $imagen['url']);
$imagen['date'] = time();
$imagen['fichero'] = $ficherof;
return $imagen;
}
I am trying to validate in two ways
1.If the name of the image is present in the folder or not .
2.If present then check if the image is same or different , because there could be new image but same name
Any suggestion will be appreciated
Thanks in Advance
You can use this,
// Check if file already exists
if (file_exists($target_file)) {
//echo "Sorry, file already exists.";
/**
* validate images that are different but have same name
* we can use base64_encode function to compare the old and new image
* basics: http://php.net/manual/en/function.base64-encode.php
* online conversion help: http://freeonlinetools24.com/base64-image
*/
$base64_encoded_new_image=base64_encode(file_get_contents($name_of_your_new_image_that_you_want_to_upload));
$base64_encoded_old_image=base64_encode(file_get_contents($name_of_the_image_that_already_exists));
if ($base64_encoded_new_image!=$base64_encoded_old_image) {
/** so the images are actually not same although they have same name
* now do some other stuffs
*/
}
}
for more information please visit http://www.w3schools.com/php/php_file_upload.asp
The hint given by this comment:
//Here before putting the file I want to check if the image already exist in the folder
makes me think you're asking for file_exists, which is the first thing that's shown if you search for "php file exist" in any search engine...
I have found this script http://d.danylevskyi.com/node/7 which I have used as a starter for the below code.
The goal is to be able to save a user picture:
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$uid = 99;
$account = user_load($uid);
// get image information
$image_path = 'public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif';
$image_info = image_get_info($image_path);
// create file object
$file = new StdClass();
$file->uid = $uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = 0; // Yes! Set status to 0 in order to save temporary file.
$file->filesize = $image_info['file_size'];
// standard Drupal validators for user pictures
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);
// here all the magic :)
$errors = file_validate($file, $validators);
if (empty($errors)) {
file_save($file);
$edit['picture'] = $file;
user_save($account, $edit);
}
?>
A picture is created in sites/default/files/pictures/ with the name picture-99-1362753611.gif
Everything seems correct in the file_managed table except that:
the filename field is empty
the uri field shows public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif
the status field is set to 0 (temporary)
The picture field in the users table gets updated with the fid of the above mentioned entry.
I would guess that the file_managed table should store the final file (in sites/default/pictures) instead of the original file info and that the users table should link to the one too.
Any idea how I can achieve that? I am quite new to the Drupal API. Thank you.
Edit:
I understand that I am giving the original file to the file_save and user_save functions. But which one actually creates the file in sites/default/pictures/ ?
Try adding the following to your code:
$file->filename = drupal_basename($image_path);
$file->status = FILE_STATUS_PERMANENT;
$file = file_save($file); // Use this instead of your current file_save
Does that help?
------------------ EDIT ------------------
If you want to save a copy of the file in a new location, you can replace the third line above with something like
// Save the file to the root of the files directory.
$file = file_copy($file, 'public://');
The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>