Pass global variable into function not working - php

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");
}

Related

Can't store the uploaded image path in database using codeigniter

I read similar query on google, there I read about checking whether file is writable and then setting permissions using chmod() function, but I tried that too, it didnt work. I want to store the image path in database, and move the image to the uploads folder. The path of the image would be as :
C:/xampp/htdocs/konnect1/uploads/Hydrangeas1.jpg
On using chmod(), I get Warning as "Message: chmod(): No such file or directory".
please help as what should I change now.
Controller page->admin_c.php
Posting the function, where image upload code is written.
public function create_event1()
{
if($this->input->post('counter') || !$this->input->post('counter'))
{
$count = $this->input->post('counter');
$c = $count;
//echo $c;
if($this->input->is_ajax_request())
{
$vardata = $this->input->post('vardata');
echo $vardata;
}
$g = $_POST['results'];
$configUpload['upload_path'] = '/konnect1/uploads/'; #the folder placed in the root of project
$configUpload['allowed_types'] = 'gif|jpg|png|bmp|jpeg'; #allowed types description
$configUpload['max_size'] = '0'; #max size
$configUpload['max_width'] = '0'; #max width
$configUpload['max_height'] = '0'; #max height
$configUpload['encrypt_name'] = false; #encrypt name of the uploaded file
$this->load->library('upload', $configUpload);
$this->upload->initialize($configUpload); #init the upload class
if( chmod($configUpload['upload_path'], 0755) )
{
// more code
chmod($configUpload['upload_path'], 0777);
}
else
echo "Couldn't do it.";
if ( ! is_writable($this->upload->do_upload('picture')))
{
$uploadedDetails = $this->upload->display_errors('upload_not_writable');
echo $uploadedDetails;
}
else if(!$this->upload->do_upload('picture'))
{
$uploadedDetails = $this->upload->display_errors();
}
else
{
$uploadedDetails = $this->upload->data();
//print_r($uploadedDetails);die;
$etype = $this->input->post('etype');
$ecategory = $this->input->post('ecategory');
$ename = $this->input->post('ename');
$edat_time = $this->input->post('edat_time');
$evenue = $this->input->post('evenue');
$sch_name0 = $this->input->post("sch_name0");
$speaker_name0 = $this->input->post("speaker_name0");
$sch_stime0 = $this->input->post("sch_stime0");
$sch_etime0 = $this->input->post("sch_etime0");
$sch_venue0 = $this->input->post("sch_venue0");
$sch_name = $this->input->post("sch_name");
$speaker_name = $this->input->post("speaker_name");
$sch_stime = $this->input->post("sch_stime");
$sch_etime = $this->input->post("sch_etime");
$sch_venue = $this->input->post("sch_venue");
$agenda_desc = $this->input->post("agenda_desc");
if ((!empty($etype)) || (!empty($uploadedDetails)) || (!empty($ecategory)) || (!empty($ename)) || (!empty($edat_time)) || (!empty($evenue)) || (!empty($sch_name0)) || (!empty($speaker_name0)) || (!empty($sch_stime0)) || (!empty($sch_etime0)) || (!empty($sch_venue0)) || (!empty($sch_name)) || (!empty($speaker_name)) || (!empty($sch_stime)) || (!empty($sch_etime)) || (!empty($sch_venue)) || (!empty($agenda_desc)))
{
$res1 = $this->admin_m->insert($uploadedDetails);
if($res1 == true)
{
$res2 = $this->admin_m->insert1($c);
$lastid = $this->db->insert_id();
$data['h'] = $this->admin_m->select($lastid);
//return the data in view
$this->load->view('admin/event', $data);
}
else
echo "error";
}
}
}
}
Model Page->admin_m.php
<?php
class Admin_m extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert($image_data = array())
{
//$data1 = explode('/',$imge_data);
//$data2 = in_array("konnect1", $data1);
$data = array(
'ename' => $this->input->post('ename'),
'eimg' => $this->input->post('eimg'),
'edat_time' => $this->input->post('edat_time'),
'evenue' => $this->input->post('evenue'),
'sch_name' => $this->input->post('sch_name0'),
'speaker_name' => $this->input->post('speaker_name0'),
'sch_stime' => $this->input->post('sch_stime0'),
'sch_etime' => $this->input->post('sch_etime0'),
'sch_venue' => $this->input->post('sch_venue0'),
'etype' => $this->input->post('etype'),
'ecategory' => $this->input->post('ecategory'),
'agenda_desc' => $this->input->post('agenda_desc'),
'eimg' => $image_data['full_path']
);
$result = $this->db->insert('event',$data);
if($result == true)
return true;
else
echo "Error in first row";
}
public function insert1($c)
{
for($i=0; $i<=$c; $i++)
{
$sql = array(
'sch_name' => $this->input->post('sch_name')[$i],
'speaker_name' => $this->input->post('speaker_name')[$i],
'sch_stime' => $this->input->post('sch_stime')[$i],
'sch_etime' => $this->input->post('sch_etime')[$i],
'sch_venue' => $this->input->post('sch_venue')[$i]
);
//$sql = "INSERT INTO event(sch_name,speaker_name,sch_stime,sch_etime,sch_venue) VALUES(($this->input->post('sch_name')[$i]),($this->input->post('speaker_name')[$i]),($this->input->post('sch_stime')[$i]),($this->input->post('sch_etime')[$i]),($this->input->post('sch_venue')[$i]))";
$res = $this->db->insert('event',$sql);
}
if ($res == true)
return true;
else
echo "Error from first row";
}
public function select($lastid)
{
//data is retrive from this query
$query = $this->db->get('event');
return $query;
}
}
?>
for reference, attached model code also.
According to the error message, it seems PHP is unable to find the directory.
Please use PHP function is_dir() to first validate if PHP can recognize the path as a folder.
Once it returns true, you can proceed to use it.
Also in your upload path, you have started with / which would mean that your project is placed in root of OS and I don't think that location would be correct.
From the terminal cd to your project directory and run command pwd and get the current working directory and then use the proper upload path after taking into consideration the location of the project.

Image not moving to proper folder zend framework2

I started working on Zend Framework image upload.The code is not showing any errors but image not moving to proper destination.
public function uploadAction()
{
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form = new UploadForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload'); //upload destination
$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if($favadapter->receive($favicon))
{
echo "suceess";
}
else
{
echo "Failed";
}
die;
}
}
return array('form' => $form);
}
The image is not received and gives failed message.Can you solve this problem.Thanks in advance
You write "gives failed message" so apparently something goes wrong. You should try to find out what and why... All we can do is guess with the information you are giving inside your question.
If you read the ZF2 documentation on this file adapter class here then you can see that the adaper has a getMessages method. This might give you some insight on what actually goes wrong:
$adapter = new Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
This code snippet comes straight out of the official docs!
Your final running code make sure you comment filters
public function uploadAction()
{
error_reporting(0);
$em = $this->getEntityManager();
$form = new UploadForm($em);
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload/'); //upload destination
//$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if (!$favadapter->receive())
{
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
else
{
echo "success";
}
// die;
}
}
// if ($request->isPost())
// {
// $fname = $_FILES['fileupload']['name'];
// $tmp_name = $_FILES["fileupload"]["tmp_name"];
// $uploads_dir = 'public/img/upload';
// if(move_uploaded_file($tmp_name,"$uploads_dir/$fname"))
// {
// echo "Uploaded";
// }
// else
// {
// echo "Error";
// }
// }
return array('form' => $form);
}

Erro 406 (Not Acceptable) jquery file upload Deleting Files

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

Php function calling, Undefined function error

Earlier I have a form that ask user to upload a picture and I have this function:
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
}
Basically it moves the uploaded picture to images file. Then I am calling this function in an if statement:
if (fileUploaded () == true) {
if ($fileResult) {
/*checking the size of file*/
}
}
else {
$fileName = "default.jpg";
}
After when I try to upload and submit it gives the error in the below:
Fatal error: Call to undefined function fileUploaded()
What should be the problem?
Thanks.
You don't return a default value in your function. Maybe it's the problem :
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
return false;
}
//functions.php
function fileUpload($path) {
if(!isset($_FILES['picture'])) return false;
$fileName = $_FILES['picture']['name'];
$fileTmpLoc = $_FILES['picture']['tmp_name'];
if(move_uploaded_file ($fileTmpLoc, $path)) return $fileName;
return false;
}
//main.php
include('functions.php');
$fileName = fileUpload('/images/');
if($fileName === false) {
$fileName = 'default.jpg';
}
//do the rest here
Something similar to the above code. Since your function is in a different file, you need to include it (or require it)

Codeigniter 2.1 controller not found

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.

Categories