I am trying to use allow my custom API endpoint to upload files to a custom directory based on information sent in the request body. It is coming through fine but I am not getting it to pass into the directory properly. I have tried getting the studentid from the request body and then calling that as a global in my function but it is not working.
add_filter("wcra_upload_callback", "wcra_upload_callback_handler");
function wcra_upload_callback_handler($request) {
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH.'wp-admin/includes/file.php');
}
$studentid = $request['studentid'];
function studentresultsdir($dir) {
global $studentid;
$mydir = 'https://example.com/wp-content/uploads/studentresults/';
$dir['path'] = $mydir;
$dir['url'] = $mydir;
$dir['subdir'] = $studentid;
var_dump($dir);
return $dir;
}
add_filter("upload_dir", "studentresultsdir");
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
echo __('File is valid, and was successfully uploaded.', 'textdomain')."\n";
var_dump($movefile);
} else {
echo $movefile['error'];
}
remove_filter("upload_dir", "studentresultsdir");
}
My var_dump of $dir is giving me an empty subdirectory. I think this is the cause of my "unable to create directory" error too but need to work this step out first.
Just wanted to add that I will be adding authentication checks once I get this working.
I managed to solve this particular error by moving the global variable outside of all functions.
add_filter("wcra_upload_callback", "wcra_upload_callback_handler");
$studentid = '';
function wcra_upload_callback_handler($request) {
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH.'wp-admin/includes/file.php');
}
global $studentid;
$studentid = $request['studentid'];
function studentresultsdir($dir) {
global $studentid;
$mydir = 'https://example.com/wp-content/uploads/studentresults/';
$dir['path'] = $mydir;
$dir['url'] = $mydir;
$dir['subdir'] = '/'.$studentid;
var_dump($dir);
return $dir;
}
add_filter("upload_dir", "studentresultsdir");
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
echo __('File is valid, and was successfully uploaded.', 'textdomain')."\n";
var_dump($movefile);
} else {
echo $movefile['error'];
}
remove_filter("upload_dir", "studentresultsdir");
}
I am having trouble deleting the files with jquery fileupload . by clicking delete the error happens , do not delete the file . Error message:
upload/server/php/index.php?file=xxxx.png 406 (Not Acceptable)
Hpierce This is the code to which it refers
public function delete($print_response = true){
$file_names = $this->get_file_names_params();
if (empty($file_names)) {
$file_names = array($this->get_file_name_param());
}
$response = array();
foreach($file_names as $file_name) {
$file_path = $this->get_upload_path($file_name);
$success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
if ($success) {
foreach($this->options['image_versions'] as $version => $options) {
if (!empty($version)) {
$file = $this->get_upload_path($file_name, $version);
if (is_file($file)) {
unlink($file);
}
}
}
}
$response[$file_name] = $success;
}
return $this->generate_response($response, $print_response);
}
I have the same problem
hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
I have conroller baner, and when I try to run it (run upload function http://localhost/010/baner/upload_img), I got 404 error:
The page you requested was not found
What is wrong here?
The controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload_Baner extends CI_Controller {
protected $path_img_upload_folder;
protected $path_img_thumb_upload_folder;
protected $path_url_img_upload_folder;
protected $path_url_img_thumb_upload_folder;
protected $delete_img_url;
function __construct() {
parent::__construct();
$this->setPath_img_upload_folder("public/img/promotions/");
$this->setPath_img_thumb_upload_folder("public/img/promotions/thumbnails/");
$this->setDelete_img_url(base_url() . 'upload_baner/deleteImage/');
$this->setPath_url_img_upload_folder(base_url() . "public/img/promotions/");
$this->setPath_url_img_thumb_upload_folder(base_url() . "public/img/promotions/thumbnails/");
}
public function upload_img() {
//Format the name
$name = $_FILES['userfile']['name'];
$name = strtr($name, 'ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃà áâãäåçèéêëìÃîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
// replace characters other than letters, numbers and . by _
$name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);
//Your upload directory, see CI user guide
$config['upload_path'] = $this->getPath_img_upload_folder();
$config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
$config['max_size'] = '1000';
$config['file_name'] = $name;
//Load the upload library
$this->load->library('upload', $config);
if ($this->do_upload()) {
//If you want to resize
$config['new_image'] = $this->getPath_img_thumb_upload_folder();
$config['image_library'] = 'gd2';
$config['source_image'] = $this->getPath_img_upload_folder() . $name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 193;
$config['height'] = 94;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = $this->upload->data();
//Get info
$info = new stdClass();
$info->name = $name;
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $this->getPath_img_upload_folder() . $name;
$info->thumbnail_url = $this->getPath_img_thumb_upload_folder() . $name; //I set this to original file since I did not create thumbs. change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$name
$info->delete_url = $this->getDelete_img_url() . $name;
$info->delete_type = 'DELETE';
//Return JSON data
if (IS_AJAX) { //this is why we put this in the constants to pass only json data
echo json_encode(array($info));
//this has to be the only the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
} else { // so that this will still work if javascript is not enabled
$file_data['upload_data'] = $this->upload->data();
echo json_encode(array($info));
}
} else {
// the display_errors() function wraps error messages in <p> by default and these html chars don't parse in
// default view on the forum so either set them to blank, or decide how you want them to display. null is passed.
$error = array('error' => $this->upload->display_errors('',''));
echo json_encode(array($error));
}
}
public function do_upload() {
if (!$this->upload->do_upload()) {
return false;
} else {
//$data = array('upload_data' => $this->upload->data());
return true;
}
}
//Function Delete image
public function deleteImage() {
//Get the name in the url
$file = $this->uri->segment(3);
$success = unlink($this->getPath_img_upload_folder() . $file);
$success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);
//info to see if it is doing what it is supposed to
$info = new stdClass();
$info->sucess = $success;
$info->path = $this->getPath_url_img_upload_folder() . $file;
$info->file = is_file($this->getPath_img_upload_folder() . $file);
if (IS_AJAX) {//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
} else { //here you will need to decide what you want to show for a successful delete
var_dump($file);
}
}
public function get_files() {
$this->get_scan_files();
}
public function get_scan_files() {
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
protected function get_file_object($file_name) {
$file_path = $this->getPath_img_upload_folder() . $file_name;
if (is_file($file_path) && $file_name[0] !== '.') {
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
$file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
//File name in the url to delete
$file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
protected function get_file_objects() {
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
)));
}
public function getPath_img_upload_folder() {
return $this->path_img_upload_folder;
}
public function setPath_img_upload_folder($path_img_upload_folder) {
$this->path_img_upload_folder = $path_img_upload_folder;
}
public function getPath_img_thumb_upload_folder() {
return $this->path_img_thumb_upload_folder;
}
public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder) {
$this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
}
public function getPath_url_img_upload_folder() {
return $this->path_url_img_upload_folder;
}
public function setPath_url_img_upload_folder($path_url_img_upload_folder) {
$this->path_url_img_upload_folder = $path_url_img_upload_folder;
}
public function getPath_url_img_thumb_upload_folder() {
return $this->path_url_img_thumb_upload_folder;
}
public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder) {
$this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
}
public function getDelete_img_url() {
return $this->delete_img_url;
}
public function setDelete_img_url($delete_img_url) {
$this->delete_img_url = $delete_img_url;
}
}
Your controller is named Upload_Baner so unless you have a route defined that maps baner to upload_Baner this won't work. Does this url work?:
http://localhost/010/upload_Baner/upload_img
That is what your current controller will map to without the route.
I currently have this script where users (using a form where they can upload up to seven images) can upload multiple images to a folder and the image name to my database, without any success. Please help.
if (isset($_POST['submit'])) { $ref_49 = $_POST['ref_49'];
$name = $_POST['name'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$rent_sell = $_POST['rent_sell'];
$heading = $_POST['heading'];
$price = $_POST['price'];
$limitedtextarea = $_POST['limitedtextarea'];
$type = $_POST['type'];
$where = $_POST['where'];
$address = $_POST['address'];
$bedroom = $_POST['bedroom'];
$bathroom = $_POST['bathroom'];
$garages = $_POST['garages'];
$carports = $_POST['carports'];
$granny_flat = $_POST['granny_flat'];
$ref_99 = $_POST['ref_99'];
$fulldesc = $_POST['full_desc'];
if ($ref_99=="") {
$full_ad = "yes";
} else {
$full_ad = "no";
}
$todays_date = date("Y-m-d");
mkdir("gallery/" . $_POST["name"], 0777);
for ($i = 0; $i < 7; $i++)
{
$file_name = $_FILES['uploadFile' . $i]['name'];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'", "", $file_name);
// $copy = copy($_FILES['uploadFile'. $i]['tmp_name'], "gallery/" . $_POST["name"] . "/" . $file_name);
if ((($_FILES['uploadFile' . $i]["type"] == "image/gif")
|| ($_FILES['uploadFile' . $i]["type"] == "image/jpeg")
|| ($_FILES['uploadFile' . $i]["type"] == "image/pjpeg"))
&& ($_FILES['uploadFile' . $i]["size"] < 200000000))
{
if ($_FILES['uploadFile' . $i]["error"] > 0)
{
$message = "Return Code: " . $_FILES['uploadFile' . $i]["error"] . "<br />";
}
else
{
$query = "INSERT INTO property (
name, contact, email, type_of_listing, rent_sell, address, prop_desc, area, price, main_image, image_1, image_2, image_3, image_4, image_5, image_6, heading, bathroom, bedroom, garages, carports, granny_flat, full_description, full_ad, 49_ref, 99_ref, listed
) VALUES (
'{$name}', '{$contact}', '{$email}', '{$type}', '{$rent_sell}', '{$address}', '{$limitedtextarea}', '{$where}', '{$price}', '{$photo_1}', '{$photo_2}', '{$photo_3}', '{$photo_4}', '{$photo_5}', '{$photo_6}', '{$photo_7}', '{$heading}', '{$bathroom}', '{$bedroom}', '{$garages}', '{$carports}', '{$granny_flat}', '{$fulldesc}', '{$full_ad}', 'ref_49_{$ref_49}', 'ref_99_{$ref_99}', ''
)";
$result = mysql_query($query, $connection);
if (file_exists("gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]))
{
$message = "<h3>" . $_FILES['uploadFile' . $i]["name"] . " already exists.</h3>";
}
else
{
move_uploaded_file($_FILES['uploadFile' . $i]["tmp_name"], "gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]);
$message = "File: " . $_FILES['uploadFile' . $i]["name"] . " uploaded.";
}
}
}
else
{
$message = "<h3>Invalid file or no file selected.</h3><br />• Only JPEG OR GIF allowed.<br />• Size limited may not exceed 200KB.<br />Return";
}
}
}
}
There could be a lot of things going wrong here. Have you tried to break this up into pieces? Are you sure the DB is connecting? Are you sure php has access to write to the directories it's attempting to write to? Are you sure those directories exist...etc. etc.
Comment out the vast majority of the code, and start testing all the components piece by piece, or wrap stuff in try/catch and see what errors are produced.
[edit]
If the problem only occurs when you upload < 7 files then the problem is in that you've hard coded a 7 into your loop!
Loop through how many files are actually being uploaded, not a fixed number.
Assuming they're all being named sequentially (and starting at 0) you can test for the existence of your hashed FILE value in the loop and just keep ingesting until it comes up null (probably good to add a limiter to make sure it can't go on for ever)
something like this...
[edit 2] modified the condition to include a test for file size
for($i=0; $_FILES['uploadFile' . $i] && $_FILES['uploadFile' . $i]['size'] > 0 && $i<100 ; $i++){
try{
//do your upload stuff here
}catch(e){}
}
[EDIT]
To modify your page to include a dynamic number of fields do this:
check out this fiddle: http://jsfiddle.net/RjcHY/2/
Click the plus and minus buttons on the right side to see how it works. I made it so that it's naming the file buttons as per your php's expectations.
While dealing with common tasks like file uploading, write some library for handling those tasks and call necessary function wherever needed . If you create an uploader class file , you can simply invoke one of the methods you created to handle file uploads .
Here i will give you a Uploader class
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>
For handling multiple uploads , ex 3 images uploading
repeat the block as follows
<?php
for($i=1;$i<=3;$i++){
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->setSequence($i);
if($uploader->uploadFile('txtFile'.$i)){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
}
?>
in above example , file browse components are named as txtFile1,txtFile2,txtFile3
Hope you will understand my explanation .