PHP Passing $_FILES and $_POST as parameters to function
$_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'];
...
sys_debug
Updated on August 21, 2022Comments
-
sys_debug over 1 year
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 :)