I have to include a file stored in a database and retrieved as a variable.
how can I do it? I have tried this line but it doesn't work
include_once("News/$post->newspage");
the fild newspage contains the names of the files stored in News folder. for example his line works.
include_once("News/labourday2014.php");
you can try like
include_once("News/".$post->newspage);
include_once("News/{$post->newspage}"); should do the trick :)
Verify if the file exist then include it
if(is_file("News/".$post->newspage)) {
include_once("News/".$post->newspage);
} else {
// File dosent't exist
echo "File dosent't exist";
}
You can try this -
$fileName="News/".$post->newspage;
include_once($fileName);
Related
I have a function like this:
fitImageSizeAndSave($_FILES["imageToUpload"]["tmp_name"], $target_file) { ... }
That function works well. The first argument is $_FILES["imageToUpload"]["tmp_name"]. Ok, it's good when an user upload an image from his local computer. But sometimes he enters a external link and I get that image like this:
$image = file_get_contents($_POST['external_link']);
How can I make $image like $_FILES["imageToUpload"]["tmp_name"] for passing it to the function?
use file_put_contents() and then reference the temporary file that you've just put the data into
#Martin Sounds a great idea, may you please add an answer? –
$_FILES["imageToUpload"]["tmp_name"] is simply a string to a file location on the server, it is not a resuorce in itself.
$filePathLocation = $_SERVER['DOCUMENT_ROOT']."/some-temporary/file/storage";
$imageData = file_get_contents($_POST['external_link']);
if($imageData){
file_put_contents($imageData, $filepathLocation);
}
else {
$filepathLocation = $_FILES["imageToUpload"]["tmp_name"];
}
fitImageSizeAndSave($filepathLocation, $target_file) { ... }
The above, step by step:
Set a temporary storage location; possibly based on microtime() or something unique (database Id, if relevant) to limit different processes overwriting the same file path.
get the contents of the $_POST file URL. save to a string variable.
Check if variable is loaded ok; else use uploaded temporary file location THIS IS FOR ILLUSTRATION ONLY - You should have a more complete process for checking which data to use and the validity of said data already set up in your script.
Send this variable to your custom function, knowning it is populated with one or the other of the possibilities above.
The below is the PHP script to get image from url and save into your location machine or into own server
$imageurl ='http://i.ndtvimg.com/i/2015-08/mahesh-babu_630x450_81440064359.jpg';
$content = file_get_contents($imageurl);
if(file_put_contents('imagefolder/randomImageName.jpg', $content)){
echo "File uploaded through URL";
}else{
echo "File not uploaded...";
}
I need to upload file using php and I done it...Now my problem is I want to create a new folder for every user let me explain to you how??
My task is for user can login and access their account and file uploads. If the user will upload any file it goes to my destination folder named as 'uploads'. Now I want to create new folder inside the uploads folder with the particular username who uploads the file... so I want to create new folder for each and every users with their username... Can anyone tell me how to do this???
This is my php code for destination :
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../uploads/'.$_FILES['upl']['name']))
{
echo '{"status":"success"}';
exit;
}
Thanks in advance
What you're looking for is the mkdir function. You can create a directory by using:
mkdir('/path/to/dir', 0700);
as noted in the PHP documentation.
Try with -
//check if the folder not exists then create it
if (!file_exists('<rootpath>/<username>')) { //<rootpath> will be the path from document root and <username> will be the username you want
mkdir('<rootpath>/<username>');
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '<path>/<username>/'.$_FILES['upl']['name'])) // <path> be the relative path
{
echo '{"status":"success"}';
exit;
}
Suppose You want to upload the file inside uploads/username folder.
$path = $_SERVER['DOCUMENT_ROOT'].'/uploads';
Now create the folder -
mkdir($path."/".$username); //$username be the username you want
Now upload the file
move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$username.'/'.$_FILES['upl']['name'])
Use mkdir() function to create a folder upon user registration.
Upon login create a $_SESSION variable storing the username.
When using move_uploaded_file() function add session variable to path.
move_uploaded_file($_FILES['upl']['tmp_name'], '../uploads/'.$_SESSION['username'].'/'.$_FILES['upl']['name'])
http://php.net/manual/en/function.mkdir.php
http://php.net/manual/en/reserved.variables.session.php
Thanks SGT... I got the answer with this code
$userfolder = $_SESSION['email'];
//echo $userfolder;
$path = $_SERVER['DOCUMENT_ROOT'].'register/uploads';
if (!file_exists('$path')) {
mkdir($path."/".$userfolder);
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../uploads/'.$userfolder.'/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
Thanks Again
i need to change variable data if the 'data name' already exists..
i have this
if (file_exists('../../images/produtos/'.$name)){
$name = '1_'.$name;
}
it is working, if i have a file with the name that is saved in the variable $name, it create a new one with a 1_ before, but i need to check if there is a 1_.$name, 2_$name ...... until there is no file with the name saved in variable $name.
If i upload a file with name things.png i need to check if there is already a file called things.png, if there is then change a name to 1_things.png, but if there is a file called 1_things.png change the name to 2_things.png etc etc until there is no file with the same name.
PS: I dont want overwrite obv..
Im sorry for my bad english, but i really dont know how to explain this better, hope you guys understand.
Thanks in advance
Use a loop:
if(file_exists('../../images/produtos/'.$name)){
$i = 1;
while(file_exists('../../images/produtos/'.$i."_".$name)){
$i++;
}
$name = $i."_".$name;
}
I try to unlink an image in CodeIgniter, but the unlink function shows:
notice Undefined index: userfile
Here is my code
<?php
function get_from_post(){
$data['logo_name'] = $this->input->post('logo_name',TRUE);
$data['logo_thumb'] = $_FILES['userfile']['name'];
return $data;
}
function deleteconf($data){
$data= $this->get_from_post();
$update_id=$this->uri->segment(3);
#unlink(base_url.'image/logo_thumb'.$logo_thumb);
$query= $this->_delete($update_id);
}
?>
the unlink function shows notice Undefined index: userfile
The upload form, using multipart/form-data
Make sure you've use enctype="multipart/form-data" attribute/value for your upload form.
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">
From the MDN:
enctype
multipart/form-data: Use this value if you are using an <input>
element with the type attribute set to "file".
If you're going to use CodeIgniter form helper, you could use form_open_multipart() function:
This function is absolutely identical to the form_open() tag above
except that it adds a multipart attribute, which is necessary if you
would like to use the form to upload files with.
Deleting files, File path vs URL address
PHP unlink() function accepts the Path of the file as the first argument. Not the URL Address.
The base_url() helper function returns the URL address of the site, which you've set in the config.php file.
You'll have to use the path of the file on your server, as follows:
unlink('/path/to/image/image_name.jpg'); // This is an absolute path to the file
You could use an Absolute or Relative path, but note that the relative path is relative to the index.php file. i.e. If the image/ folder is placed beside index.php file, you should use image/image_name.jpg as the file path:
unlink('image/image_name.jpg'); // This is a relative path to the file
If you want to upload a photo for user profile and also
at the time the old user photo should be deleted by
using unlink method in codeignitor
$query = $this->db->where('profile_id',$profile_id)->get('users')->row();
$result = $query->photo;
$result = http://localhost/abc/user_photo/FE12563.jpg
if ($result) {
$dd = substr($result, strlen(base_url()));
unlink($dd);
return $this->db->set('photo',$photo)->where('profile_id',$profile_id)->update('users');
}
First check your file input name. Is it "userfile" or not?
if not then add it and then run it once again.
function get_from_post(){
$filename = $_POST['logo_name'];
$path = $_SERVER['DOCUMENT_ROOT'].'/projectname/uploads/'.$filename ;
if(is_file($path)){
unlink($path);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
base_url() function returns url of you project but here you have to use directory path of file which you want to delete.
$path = BASEPATH.'/assets/upload/employees/contracts/';
$get_file = $path.$con_id.'.jpg';
if(file_exists($get_file)){
unlink($get_file);
}
instead of unlink(base_url("/assets/upload/employees/contracts/'.$con_id."));
First unlink function work only with path (without url), so please remove base_url() function.
Then in your first function $_FILES array doesn't contain userfile index, that's why getting error.
NOTE:- Before using unlink i would like to use also file_exists() function, first it will check if file is exist on same path then use unlink function (for error handling).
Like that -
<?php
if(file_exists(filePath))
{
unlink(filePath);
}
?>
Please fix both issue.
Thanks
Suppose you have the file name in the database and your file is abc.jpg. Then to unlink that in Code Igniter just do -
$file = "abc.jpg";
$prev_file_path = "./assets/uploads/files/".$file;
if(file_exists($prev_file_path ))
unlink($prev_file_path );
My file upload path is "public_html/assets/uploads/files/". I am writing the above code in my controller which is "public_html/application/controllers/MyController.php". So the path will be same which I used in my CI file upload section. i.e.
...
$config['upload_path'] = './assets/uploads/files';
...
So we used relative path in both the upload and unlink section. So if the upload works perfectly then this will also work perfectly.
You can do like this, you need to get first the path of directory from where you have uploaded your image.
Exemple:
//this is your url
$mainPath='https://google.com/uploads/image/16.jpeg';
$uploadedDirectory=str_replace("https://google.com/","./", $mainPath);
//now you get path like this ./uploads/image/16.jpeg
if(unlink($uploadedDirectory)) {
$this->db->where('prodId',$id);
$this->db->delete('products');
}
$this->load->helper("file");
just add above line before unlink
unlink($path);
Can you please use this code to remove image on folder.
unlink(realpath('uploads/' . $_image));
"uploads" : Image exist in uploads folder.
"$_image" : Image file name
PHP functions:
1 : unlink()
2 : realpath()
The above code successfully working on my site to delete image on folder.
try this code
unlink(base_url().'/image/logo_thumb'.$logo_thumb);
Note: You didn't assign / declare $logo_thumb in your deleteconf().
Please check your code.
I have a simple statement below:
if(file_exists('/images/alum/'.$profile['pic']))
echo '/images/alum/'.$profile['pic'];
else echo '/images/user_default.jpg';
The file is there but it's always going to the default image. What have I got wrong?
You are saying on the server that the file at the root of the file system exists. You will have to probably add some . or ..
Try:
if(file_exists('./images/alum/'.$profile['pic']))
echo '/images/alum/'.$profile['pic'];
else echo '/images/user_default.jpg';
i.e. changing the "/images" to "./images" but only in the file_exists call.
Change it to this.
if(file_exists('./images/alum/'.$profile['pic']))
echo './images/alum/'.$profile['pic'];
else
echo './images/user_default.jpg';
make sure that $profile['pic'] has valid file name, contraction with path is valid, and current directory with parth point to file...
temporary negate condition to see file from profile...