Image upload in non existing folder in PHP - php

I've run into a problem where I need to upload an image into a folder and store its path into database.
If the folder is not present then create the new folder and then store it there and save full path into database.
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);
image name to be used
$imagename=("Userimage")."-".time().$ext;
image path
$target_path = "images/".$imagename
Condition
if(move_uploaded_file($temp_name, $target_path))
{
$query_upload="INSERT into images_tbl (images_path , submission_date) VALUES ('".$target_path."','".date("Y-m-d")."')";
$imagedb= mysqli_query($con,$query_upload);
while($imagepath = mysqli_fetch_array($imagedb))
{
echo "success";
}
}

It's easy:
$target_path = 'images/'.$imagename;
if(!is_dir($target_path)) mkdir($target_path, 0755);
Don't use " " when you can use ' ', because each time you use " .." , php try to find variable inside and lost time for nothing. ;)

You could do something like this:
<?php
$target_dir = preg_replace('#^(.*)'.basename($target_path).'$#', '$1', $target_path);
if (!is_dir($target_dir))
mkdir($target_dir, 0755);
if(move_uploaded_file($temp_name, $target_path))
{
$query_upload="INSERT into images_tbl (images_path , submission_date) VALUES ('".$target_path."','".date("Y-m-d")."')";
$imagedb= mysqli_query($con,$query_upload);
while($imagepath = mysqli_fetch_array($imagedb))
{
echo "success";
}
}
?>
The preg_replace part strips the directory path out of the complete path.

if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
0777 is the directory permission ,that is a creating the directory and setting the permission to 0777 so that file can be uploaded to this directory

Related

move uploaded image into folder in php(move_uploaded_file() function)

I have a problem with moving uploaded files.
<?php
$image_name = $_FILES['image']['name'] ;
$target_file = "../uploads/$image_name";
$targetFileForItem = "uploads/$image_name";
move_uploaded_file($_FILES['image']['tmp_name'], $target_file);
$sql = "INSERT INTO items (name , description,`price`, `country`, `release`, `condition`, `image`)
VALUES ('$name','$description','$price', '$country', '$date', '$condition', '$targetFileForItem')" ;
?>
the variable $targetFileForItem works currect, and inserts into my db very well, but the file don't move into $target_filevar's folder, which is uploads. As you see I use move_uploaded_file() function, but i's not working. Any suggestions?
Write this to debug
ini_set('display_errors',1);
error_reporting(E_ALL);
If your code is ok then check file permissions you can use this
if (is_dir($target_file ) && is_writable($target_file )) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
is_writable Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable
for more info read this http://php.net/manual/en/function.is-writable.php
Check your permission for upload folder it must be 775. If you are using FTP than right click on folder and change File permission of that folder to 755.
If it's localhost then it must be a path or folder name issue.
And make your code like this so you can get find out errors also.
<?php
$image_name = $_FILES['image']['name'] ;
$target_file = "../uploads/$image_name";
$targetFileForItem = "uploads/$image_name";
// if folder not exists than it will make folder.
if(!file_exists($target_file))
{
mkdir($target_file, 0777, true);
}
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_file))
{
echo "file successfully uploaded";
}
else
{
echo "error in file upload";
}
?>

Upload the same file into multiple folders

I have an uploading form, and when i select the file,i need it to be uploaded in multiple folders.Any ideas how to do that? I've tried with a loop like the following one:
foreach($_POST['check'] as $check){
move_uploaded_file($_FILES['doc']['tmp_name'], $target_path);
chmod($target_path,0777);
}
But it only upload once.Any ideas please?
After uploading, copy the file from the target path to the other paths with copy().
foreach($_POST['check'] as $check){
move_uploaded_file($_FILES['doc']['tmp_name'], $target_path);
chmod($target_path,0777);
// and now...
copy($target_path, $target_path_2);
copy($target_path, $target_path_3);
// etc...
}
By the way, setting 0777 for permissions generally is unnecessary and a bad idea. You want anyone to upload files and let any user execute them? That's the way to start giving anyone full control over your machine.
Also, are you sure that you need the file on multiple places? Why not have one common storage folder and create symbolic links to it? But that depends on your setup, of course.
Upload once and then just copy() it.
$i = 0;
foreach($_POST['check'] as $check){
$basePath = "/var/www/html/more/phpexm/";
$target_path = $basePath . $check;
if (!file_exists($target_path)){
mkdir($target_path, 0777);
}
if ($i == 0){
$sFileNameTmp = $_FILES['doc']['tmp_name'];
$sFileName = $_FILES['doc']['name'];
move_uploaded_file($sFileNameTmp, $target_path . '/' . $sFileName);
$sFirstFileUploaded = $target_path;
}
else{
copy ($sFirstFileUploaded . '/' . $sFileName, $target_path . '/' . $sFileName);
}
$i++;
}

can't move_uploaded_file to folder

I can insert the folder path into the database but the picture file doesn't seem to move into that folder?
$pic = $_POST['pic'];
$picName= $_FILES['pic']['name'];
$type = $_FILES['pic']['type'];
$tmp = $_FILES['pic']['tmp'];
$picPath = "/pictures/";
if(is_uploaded_file($tmp)) {
if(move_uploaded_file($tmp, $picPath . $picName)) {
echo "congrats! Image is uploaded.";
}
else {
echo "Sorry, couldn't move your picture.";
}
}
else {
echo "Sorry, couldn't upload your picture.";
}
$picPath = $picPath . $picName;
mysql_query("INSERT INTO User(pic) VALUES ('$picPath')");
I get this echo message: Sorry, couldn't upload your picture.
The php files is saved on public_html folder, and I have a pictures folder where I want to move the users pictures into.
The insertion works as I can store the $picPath in my database, but the picture don't get stored in my folder.
Try replacing
$tmp = $_FILES['pic']['tmp'];
with
$tmp = $_FILES['pic']['tmp_name'];
1) check folder permissions if its writable or not.
2) make sure your path is same with the same folder name in code as well.
3) Try to change from this $picPath = "/pictures/"; to something like this $picPath = "pictures/"; removed forward slash.

Rename file on upload PHP

I am trying to build a script to upload and rename an image to a folder and store the path in my sql db.
Here is where I am at: The file get uploaded both to the folder and the pathname to the db but I cannot figure out how to rename the filename. Ideally I would like to make the filename unique so I don't duplicates.
<?php
//preparing the patch to copy the uploaded file
$target_path = "upload/";
//adding the name of the file, finishing the path
$target_path = $target_path . basename( $_FILES['picture']['name']);
//moving the file to the folder
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
//getting input from the form
$name = $_POST['name'];
$description = $_POST['description'];
//preparing the query to insert the values
$query = "INSERT INTO complete_table (name, description, picture) VALUES ('$name', '$description', '". $target_path ."')";
//opening connection to db
$link = mysql_connect('localhost', 'root', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//selecting a db
mysql_select_db("wcs_venues", $link) or die(mysql_error());
//running the query
$result = mysql_query($query) or die (mysql_error());
//closing the connection
mysql_close($link);
?>
I am new with all this and I am really trying but after looking at many tutorial and answered questions on Stack-overflow, I realized I needed help. Thank you in advance for helping this newbie.
Well, this is where you set the name of the file being saved:
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
In this case, you're building the file name in the variable $target_path. Just change that to something else. What you change it to is up to you. For example, if you don't care about the name of the file and just want it to always be unique, you could create a GUID or a Unique ID and use that as the file name. Something like:
$target_path = "upload/";
$target_path = $target_path . uniqid();
Note that this would essentially throw away the existing name of the file and replace it entirely. If you want to keep the original name, such as for display purposes on the web page, you can store that in the database as well.
First get the file extension:
$file_extension = strrchr($uploaded_file_name, ".");
Then rename the uploaded file with a unique id + file extension
$uploaded_file_name = uniqid() . $file_extension;
Example:
TIP: Save the original file name and other information in a database.
First get the extension with pathinfo()
Then create your unique name:
$name = 'myname'.uniqid();
Then rename your file.
$target_path = $target_path . $name.$ext);
move_upload_file takes the second parameters $destination, its where you are inserting the target_path ( where your file is going to be saved with that given name ).

PHP upload to specific folder

I am trying to do a php upload that will upload into a specific folder.
One would choose the file they wish to upload next to a dropdown box which is a folder list. This is because it organises files.
<?php
session_start();
if(!isset($_SESSION["USER"]["Admin"])){
header("Location: index.html?unath");
}
$folder = mysql_real_escape_string($_POST['loc']);
$target_path = "../../shared/docs/$folder";
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload2)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Currently the code uploads the file into the "docs" folder and not docs/folder. Instead it puts the folder name in front of the file. For example- if the folder is called "abc" and my file is called robs.docx it will upload it to the main Docs folder and call it abcrobs.docx
You have a missing slash
Replace this line:
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
with:
$upload2 = $target_path ."/". basename( $_FILES['uploadedfile']['name']);
OR:
Replace this line:
$target_path = "../../shared/docs/$folder";
with:
$target_path = "../../shared/docs/".$folder."/";
You do not need mysql_real_escape_string because there's no SQL involved here.
If no database connection is established, mysql_real_escape_string returns null. So you're probably throwing away the $_POST['loc'] value.
You should never ever use user supplied values for manipulating anything on the filesystem without really, really thorough inspection of what you're going to manipulate. See Security threats with uploads.
Use var_dump liberally to see what your values look like at various stages and do some debugging.
You are missing a slash after $target_path
Add a / on the end of your $target_path:
$target_path = "../../shared/docs/$folder/";
You should properly escape your variables:
$target_path = "../../shared/docs/". $folder ."/";

Categories