PHP Passing $_FILES and $_POST as parameters to function - php

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 :)

Related

How to upload an image to database in php

I need to upload an image to database and save it inside a folder so I can display the image by giving the path to that folder. I have already coded this but there is a problem it in saving inside a folder. It saves the path to the database and correctly storing details but it dosen't save inside the folder which I have created inside my project.Folder name is also same but I cannot fix this problem. Please help me find to correct this. I've been struggling with this for a long time.
public function save()
{
$url = $this->do_upload();
//$title = $_POST["title"];
//$this->main_m->save($title, $url);
}
private function do_upload()
{
$type = explode('.', $_FILES["pic"]["name"]);
$type = strtolower($type[count($type)-1]);
$url = "./images/".uniqid(rand()).'.'.$type;
if(in_array($type, array("jpg", "jpeg", "gif", "png")))
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
if(move_uploaded_file($_FILES["pic"]["tmp_name"],$url))
return $url;
return "";
}
Try change the relative path by a absolute path.
public function save()
{
$url = $this->do_upload();
//$title = $_POST["title"];
//$this->main_m->save($title, $url);
}
private function do_upload()
{
$type = explode('.', $_FILES["pic"]["name"]);
$type = strtolower($type[count($type)-1]);
$url = "/data/images/".uniqid(rand()).'.'.$type;
if(in_array($type, array("jpg", "jpeg", "gif", "png")))
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
if(move_uploaded_file($_FILES["pic"]["tmp_name"],$url))
return $url;
return "";
}

PHP Photo/File Upload Issues

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.

Image upload takes previous temp file to upload in PHP

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.)

Iam doing an ajax file upload , but after uploading the form shows twice

I doing an ajax file uploadusing jquery.form.js.
After uploading I send back the uploaded files' id from PHP to tpl(Smarty).
Problem is that now I'm getting the tpl twice. When I put an exit command in the php file I can solve this problem, but then I will not get the value of the returned file's id to tpl.
Now I would like to get the returned file key in tpl, and also want to display the tpl only once.
if(isset($input['act']) and trim($input['act']) == "uplaodFile") {
$valid_formats = array("jpg", "png", "gif", "bmp");
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
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;
$tmp = $_FILES['photoimg']['tmp_name'];
if($filekey = $files->uploadFile($contact_id, $wrkspace_id, $_FILES['photoimg'], "files", null))
{
$smarty->assign("filekey",$filekey);
}
}
else
Error::setError ("Image file size max 1 MB");
}
else
Error::setError("Invalid file format..");
}
else
Error::setError("Please select image..!");
//EXIT;
}
display("schedule_event");

PHP image upload - rename without losing extension?

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!!!!!!!!!

Categories