Been looking around as i'm having a few issues with PHP file upload! I'm trying to upload a photo or three to a database (admin_images) if the user wants to or show the photo that's already stored in the db. I'm having some issues, below is my code I currently have, any advice is welcome.
require_once 'connect/config.php';
require_once 'connect/opendb.php';
require_once 'connect/magic.quotes.php';
$home_query = "SELECT * FROM admin";
$home_rt = mysql_query($home_query);
$home_row = mysql_fetch_assoc($home_rt);
if(isset($_POST['submit'])) { $HomeTitle = check_input($_POST['HomeTitle']); $HomeBio = check_input($_POST['HomeBio']);
$home_query = mysql_query("UPDATE admin SET HomeTitle = '".$HomeTitle."', HomeBio = '".$HomeBio."' WHERE ID = 1");
foreach ($_FILES['file']['name'] as $f => $name) {
$name = strtolower($name);
$allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $name); $extension = end($temp);
if(in_array($extension, $allowedExts)) { if($_FILES['file']['size'][$f] < 2000000) {
$uniqid = uniqid();
move_uploaded_file($_FILES["file"]["tmp_name"][$f], "upload/" . $uniqid . "." . $extension);
mysql_query("INSERT INTO admin_images (id, HomeImage1, HomeImage2, HomeImage3) VALUES (".$last_id.", '".$uniqid .".".$extension."')");
} else {
} } else {
} } header("Location: home1.php");
} require_once 'connect/closedb.php'; ?
In the PHP further down the page I have included:
input type="file" name="files[]" multiple
Apologies if I'm being unclear.
Thanks in advance.
By using $_FILES['file'] you are telling the PHP to get file from input type with name "file" -the input you show has a different name (actually its an array).
it is best to dump the $_FILES array to view the actual data in it.
var_dump($_FILES);
see this. it gives detail process. match the format and check for any bug.
Related
I have created this admin user page where data can be inserted. But everytime I try to execute it says:
mkdir(): File exists in rental/search/add_property_2.php on line 98
Here is the code:
$p_img9 = $_POST['p_img9'];
$p_img10 = $_POST['p_img10'];*/
if (!file_exists('tmp_imgs/'.$property_id)) { // Creating Temprory Directroy for images
mkdir('tmp_imgs/tmp_'.$property_id, 0777, true); ...Line 98
}
foreach ($_FILES['p_img']['name'] as $f => $name) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $name);
$extension = end($temp);
Seeking Help On This
Property Id is auto generated and on previous page to this its defined as
$property_id = get_new_property_id();...
and second page where getting error
$property_id = $_POST['property_id'];..
Your check condition doesn't match the directory you are creating. You can fix it like so
$directory = 'tmp_imgs/tmp_'.$property_id;
if (!file_exists($directory)) {
mkdir($directory, 0777, true);
}
I have this code for upload
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photo/" . $_FILES["image"]["name"]);
$location="photo/" . $_FILES["image"]["name"];
then the insert $location code for sql to add
The Question is how to have my picture file name number add ex: if i have "Picture.jpg "uploaded if i will upload again and same file name the output of the filename will be Picture(1).jpg and if I upload again with the same file name the output filename will be Picture(2).jpg and so on I want the "()" to increment if ever i will upload same file name. thanks in advance ^^
This can be achived with loop:
$info = pathinfo($_FILES['image']['name']);
$i = 0;
do {
$image_name = $info['filename'] . ($i ? "_($i)" : "") . "." . $info['extension'];
$i++;
$path = "photo/" . $image_name;
} while(file_exists($path));
move_uploaded_file($_FILES['image']['tmp_name'], $path);
You should also sanitize input file name:
string sanitizer for filename
Sanitizing strings to make them URL and filename safe?
If you want to have a unique image name after upload even if they have same name or they are uploading in loop means multiple upload.
$time = time() + sprintf("%06d",(microtime(true) - floor(microtime(true))) * 1000000);
$new_name=$image_name.'_'.$time.'.'.$extension
You can add the image name with a unique time stamp which differ each nano seconds and generate unique time stamp
This code is untested, but I would think something along the lines of:
if (file_exists('path/to/file/image.jpg')){
$i = 1;
while (file_exists('path/to/file/image ('.$i.').jpg')){
$i++;
}
$name = 'image ('.$i.');
}
And then save the image to $name. (which at some point will result in image (2).jpg)
try this
$path = "photo/" . $_FILES["image"]["name"];
$ext = pathinfo ($path, PATHINFO_EXTENSION );
$name = pathinfo ( $path, PATHINFO_FILENAME ] );
for($i = 0; file_exists($path); $i++){
if($i > 0){
$path = "photo/" .$name.'('.$id.').'.$ext;
}
}
echo $path;
Can you try this,
$name = $_FILES['image']['name'];
$pathinfo = pathinfo($name);
$FileName = $pathinfo['filename'];
$ext = $pathinfo['extension'];
$actual_image_name = $FileName.time().".".$ext;
$location="photo/".$converted_name;
if(move_uploaded_file($tmp, $location))
{
}
I searched online for a code that does PHP image upload using ajax. I found the code attached below. The issue is that I changed few things (minor tweaks) to make it work on my server. Originally it was just a php page (not a class or function) that handles the data posted from form. I made it into class then function. I am following OOP now. I thought the best way to do things in the conversion from procedural to OOP was to pass $_FILES and $_POST to a method and inside deal with them. I think this didn't work. Look at the example and please advise on how to go forward.
function uploadImageChosen($_FILES, $_POST){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
$connectionInstance = new ConnectionClass();
$connectionInstance->connectToDatabase();
$imgName;
$imgURL;
$imgSize;
$imgDir = $_POST['directory'];
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$imgSize = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$imgName = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$imgName))
{
$imgURL = $path.$imgName;
$connectionInstance->query("INSERT INTO imagesupload(id, title, url, size, directory) VALUES (null, '$imgName','$imgURL', '$imgSize', '$imgDir')");
//echo "<img src='uploads/".$imgName."' class='preview'>";
}
else{
echo "failed";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}//end of if
}//end of function
As to the page where the class function is being called, here it is:
<?php
require_once("../classes/UploadImages.php");
$uploadInstance = new UploadImages();
$uploadInstance->uploadImageChosen($_FILES, $_POST);
//header("LOCATION:portfolio.php");
?>
Thank you very much :)
$_POST and $_FILES are superglobal arrays, they are always available, and redefining them in a function or method is a bad idea.
You can do something like this:
$uploadInstance->uploadImageChosen();
..
function uploadImageChosen(){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
...
$name = $_FILES['photoimg']['name'];
...
Or if you need copies in the local scope do it like this:
$uploadInstance->uploadImageChosen($_FILES, $_POST);
..
function uploadImageChosen($files, $post){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
...
$name = $files['photoimg']['name'];
...
Try removing $_SERVER['REQUEST_METHOD'] == "POST" from the IF-statement, and see what it does.
The script above has a problem which was not detected in error log. The problem was first presented when I instantiated the connection class. I should have created another variable that would receive the open connection for querying to work That was solved and data now present in the DB. The second problem was the JPG format was not in array of acceptable types, so I added that along with jpg (variations). This made the file actually transfer to upload folder. Thank you all for support and sorry for the inconvenience :)
Here I have the problem with uploading image in PHP.
The problem is that when first time I upload the image file it works fine.
But when I am trying to upload the file second time without page refresh it takes first image name and upload it.
What is the problem and how can it be resolved?
$name = $_FILES['ImageFile']['name'];
$size = $_FILES['ImageFile']['size'];
$tmp = $_FILES['ImageFile']['tmp_name'];
$path = "public/www/uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
$response = '';
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) {
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
$response = "<img src='public/www/uploads/".$actual_image_name."?parm=".time()."' class='preview'>";
} else {
$response = "failed";
}
} else {
$response = "Image file size max 1 MB";
}
} else {
$response = "Invalid file format..";
}
} else {
$response = "Please select image..!";
}
Here, $response is a variable that used to get status.
Sounds like you are using some sort of AJAX to call this function.
You might need to find a way to reset the $_FILES array at the end of this function... maybe something like this would help:
$_FILES = array();
Otherwise, because there is no (apparent) page refresh happening after the file upload (as you mentioned,) I'm thinking that the $_FILES variable has no chance of being naturally reset (as would happen if you weren't using AJAX here.)
I currently have:
$file_name = $HTTP_POST_FILES['uid']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "uploads/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['uid']['tmp_name'], $path))
{
echo "Successful<BR/>";
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['uid']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['uid']['type']."<BR/>";
}
else
{
echo "Error";
}
}
this generates a random number before the current file name ie 4593example.jpg
but i would just like it to rewrite the whole filename to 4593.jpg removing the ucrrent name (example). When i have tried doing this i lose the extension (.jpg)
any help is appreciated.
If you're dealing with images only, I would consider detecting the image's type using getimagesize() and giving the new file an extension according to that.
That way, you don't have to rely on what extension you get from the user (which could be wrong).
Like so:
$extensions = array(
IMAGETYPE_JPG => "jpg",
IMAGETYPE_GIF => "gif",
IMAGETYPE_PNG => "png",
IMAGETYPE_JPEG2000 => "jpg",
/* ...... several more at http://php.net/manual/en/image.constants.php
I'm too lazy to type them up */
);
$info = getimagesize($_FILES['uid']['tmp_name']);
$type = $info[2];
$extension = $extensions[$type];
if (!$extension) die ("Unknown file type");
move_uploaded_file($_FILES['uid']['tmp_name'], $path.".".$extension);
`
Also:
As #alex says, your method has a considerable risk of collisions of random names. You should add a file_exists() check to prevent those (e.g. a loop that creates a new random number until one is found that doesn't exist yet)
HTTP_POST_FILES is deprecated, use $_FILES instead
I strongly advise you to use move_uploaded_file() instead of copy() which is vulnerable to attacks.
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$newFilename = $random_digit . '.' . $ext;
BTW, what will happen if the random number clashes (which may happen next or in 10 years)?
There are many better ways to name them - for example, hash of the filename and time() should theoretically never clash (though in practice hash collisions do occur).
You can get the original extension by using the following code:
$extension = strrchr($HTTP_POST_FILES['uid']['tmp_name'], '.');
Then you can add the extension to the variable $new_file_name like this:
$new_file_name = $random_digit . $file_name . '.' . $extension;
You can use this code:
$file_name = $HTTP_POST_FILES['uid']['name']; $random_digit=rand(0000,9999);
$extension= end(explode(".", $HTTP_POST_FILES['uid']['name']));
$new_file_name=$random_digit.'.'.$extension; $path= "uploads/images/users/".$new_file_name; if($ufile !=none) { if(copy($HTTP_POST_FILES['uid']['tmp_name'], $path)) { echo "Successful
"; echo "File Name :".$new_file_name."
"; echo "File Size :".$HTTP_POST_FILES['uid']['size']."
"; echo "File Type :".$HTTP_POST_FILES['uid']['type']."
"; } else { echo "Error"; } }
enjoy!!!!!!!!!