WordPress: functions.php is not in array error message - php

I do have the following code:
add_filter('upload_mimes','restrict_mimes_for_subscriber');
function restrict_mimes_for_subscriber($mimes) {
if (! current_user_can('delete_posts')) {
return;
}
$mimes = array(
'pdf' => 'application/pdf',
'jpg|jpeg' => 'image/jpeg'
);
return $mimes;
}
and I want to add an error message if the uploaded file is not in the array of allowed mimes for a subscriber. The below snippet is what I found already
if (! in_array("uploaded-file", $mimes)) {
echo "Error: Only PDF and JPG files allowed.";
}
But I do not know how I get the "uploaded-file" to compare it against the array? Any help to complete my code please?
And I think the snippet has to go into my code just before the return statement or?
Many thanks and cheers
Yogie

Related

Handling File Upload Exception - Laravel

This is how i upload a file into my database but i am not able to handle my exception when the file uploaded is an invalid format or type.
I am able to handle exception when no file is uploaded but not when the file type is invalid or does not meet the standard.
How do i get this done please?
Controller
public function import($id, Request $request)
{
$country= Country::all()->where('id',$id)->first();
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader)
{
})->get();
if(!empty($data) && $data->count())
{
foreach ($data->toArray() as $row)
{
if(!empty($row))
{
$dataArray[] =
[
'name' => $row['name'],
];
}
else {
return redirect('admin')->with('error','File format Error');
}
}
if(!empty($dataArray))
{
$country->teams()->createMany($dataArray);
return redirect('admin')->with('status','Countries successfully added');
}
}
}
else {
return redirect('admin')->with('error','No file was uploaded');
}
}
From Laravel's documentation, You can accept only a certain type of file using mime validation rule,
'file' => 'required | mimes:application/vnd.ms-excel',
The mime-type application/vnd.ms-excel will match these file extensions xls xlm xla xlc xlt xlw
I have uploading excel files in one of my project. Hope this will helps you:-
$file = Input::file('imported-file');
Excel::load($file ,function($reader){
$reader->each(function($sheet){
YourMOdelName::firstOrCreate($sheet->toArray());
});
});
YourModelName is your table name suppose if table is users so you have to define User in that case.....
From this way you can get the extenstion of your uploading file:-
$ext= Input::file('imported-file')->getClientOriginalExtension();
echo $ext; //print the extension here
Hope it willl help!
Okay i solved this in a very simple way by checking out the laravel documentation. So here is what i just added
if(($request->file('imported-file')->getClientOriginalExtension() != 'xls, xlm, xla ,xlc, xlt, xlw'))
{
}
else {
//process the file
}

windows 10 file upload and permissions php

I'm having trouble moving uploaded files, the problem seems to be a permissions problem, any help would be much appreciated. I'm using windows 10 and I've change my temp folder in php.ini to a custom folder in xampp directory and when I check this temp folder the file isn't there either, so it seems that it isn't even being uploaded to them temp. Please help.
class PortfolioItem extends DataBaseCommonObj{
protected static $table_name = 'portfolio_item';
protected static $db_fields = array('id','filename','mimetype','size','caption','job_id');
public $id;
public $filename;
public $mimetype;
public $size;
public $caption;
public $job_id;
private $temp_path;
protected $upload_dir="_portfolio-items";
public $errors=array();
protected $upload_errors = array(
// http://www.php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
public function attach_file($file){
global $session;
if(!$file || empty($file) || !is_array($file)){
$this->errors[] = 'no file was uploaded';
return false;
}elseif ($file['error'] != 0) {
$this->errors[]=$this->upload_errors[$file['error']];
return false;
}else {
$this->filename = basename($file['name']);
$this->temp_path = $file['tmp_name'];
$this->mimetype = $file['type'];
$this->size = $file['size'];
if(isset($session->message) && $session->message !== ''){
$current_job = Job::find_by_id(intval($session->message));
$this->job_id = $current_job->id;
}
return true;
}
}
defined('DS')?null:define('DS',DIRECTORY_SEPARATOR);
defined('SITE_ROOT')?null:define('SITE_ROOT', DS.'mp_creations');
defined('INC_PATH')?null:define('INC_PATH', SITE_ROOT.DS.'includes');
defined('PUB_PATH')?null:define('PUB_PATH', SITE_ROOT.DS.'public');
public function save(){
if(isset($this->id)){
$this->update();
}else{
if(!empty($this->errors)){
return false;
}
if(empty($this->filename) || empty($this->temp_path)){
$this->errors[] = 'file path not available';
return false;
}
$target_path = PUB_PATH.DS.$this->upload_dir.DS.$this->filename;
if(file_exists($target_path)){
$this->errors[] = "the file {$this->filename} already exists";
return false;
}
if(move_uploaded_file($this->temp_path,$target_path)){
if($this->create()){
unset($this->temp_path);
return true;
}
}else {
$this->errors[]='The file upload failed, possibly due to permission issues';
return false;
}
}
}
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.
http://php.net/manual/en/features.file-upload.post-method.php
The problem seemed to have been my methods and not anything to do with permissions. I was was using values stored in the session to pass to the move_uploaded_file() function, once I did it directly from the POST request it worked fine. Is it that the move_uploaded_file() needs to be called from a POST request? Anybody care to shed some light on this, please do as I'd love to learn what happening behind the scenes.

naming a file after submitting a form in Symfony

I am working on a form which accepts some user input and an image file, the submission part and the data getting entered into the database is working fine but I am stuck at how to name a file once it is uploaded, right now this is what i see as an image name in database C:\wamp2.5\tmp\phpF360.tmp which obviously is not correct.
This is what my controller looks like DefaultController.php
public function createBlogAction(Request $request)
{
$post = new Post();
$form = $this->createForm(new PostCreate(), $post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$post->upload();
$post->setDate(date_create(date('Y-m-d H:i:s')));
$post->setAuthor('ClickTeck');
$em->persist($post);
$em->flush();
$this->get('session')->getFlashBag()->add(
'notice',
'Success'
);
}
return $this->render('BlogBundle:Default:blog-create.html.twig', array(
'form' => $form->createView()
)
);
}
This is what my upload() looks like inside Entity/Post.php which is uploading the file and moving it into the folder, the file name that I see in a folder is correct however now the one that goes into the database
public function upload()
{
if (null === $this->getImage()) {
return;
}
// I might be wrong, but I feel it is here that i need to name the file
$this->getImage()->move(
$this->getUploadRootDir(),
$this->getImage()->getClientOriginalName()
);
$this->path = $this->getUploadDir();
$this->file = null;
}
I will really appreciate if someone can push me in right direction, I just need to name the file, a name which gets assigned to the image in database and the file should get uploaded with the same name as well.
UPDATE
I managed to get it to work using the following function, not sure if this is the best practice but it did work, i would love to hear from others on this. please do not provide any links, if you can refine what has already been done that would be great.
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getImage()) {
return;
}
$dirpath = $this->getUploadRootDir();
$image = $this->getImage()->getClientOriginalName();
$ext = $this->getImage()->guessExtension();
$name = substr($image, 0, - strlen($ext));
$i = 1;
while(file_exists($dirpath . '/' . $image)) {
$image = $name . '-' . $i .'.'. $ext;
$i++;
}
$this->getImage()->move($dirpath,$image);
$this->image = $image;
$this->path = $this->getUploadDir();
$this->file = null;
}
This topic from documentation may help you : http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
In addition, you should not put your upload function in the controller but rather use Doctrine events (Lifecycle callbacks) to call your function automatically.
as per suggestion of #theofabry you can check symfony2 documentation How to handle File Uploads with Doctrine, Controller must be thin as much as possible and try to do upload with Doctrine Events.
If you want to continue with your logic you may try following code, I have not tested yet...so please be careful.
// set the path property to the filename where you'ved saved the file
$this->path = $this->file->getClientOriginalName();
instead of
$this->path = $this->getUploadDir();

Wordpress/Jetpack: What part of my code is causing Jetpack to break?

I have created a custom post type (images) for handling event images, to which I have also added a custom image uploader meta field, and everything works exactly the way I want it to, EXCEPT, it breaks jetpack. I know from experience with Jetpack that a plugin may create unexpected output, causing the "-32700" error with jetpack, but i don't know which part of the code is causing it. The code for the image uploader is:
<?php
function add_custom_meta_boxes() {
// Define the custom attachment for posts
add_meta_box(
'wp_image_attachment',
'Custom Attachment',
'wp_image_attachment',
'images',
'side'
);
} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_image_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_image_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your image here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_image_attachment" name="wp_image_attachment" value="" size="25">';
echo $html;
} // end wp_image_attachment
function save_custom_meta_data($id) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['wp_image_attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $id;
} // end if
if('page' == $_POST['post_type']) {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} else {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} // end if
/* - end security verification - */
// Make sure the file array isn't empty
if(!empty($_FILES['wp_image_attachment']['name'])) {
// Setup the array of supported file types. In this case, it's just PDF.
$supported_types = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
// Get the file type of the upload
$arr_file_type = wp_check_filetype(basename($_FILES['wp_image_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
// Check if the type is supported. If not, throw an error.
if(in_array($uploaded_type, $supported_types)) {
// Use the WordPress API to upload the file
$upload = wp_upload_bits($_FILES['wp_image_attachment']['name'], null, file_get_contents($_FILES['wp_image_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_image_attachment', $upload);
update_post_meta($id, 'wp_image_attachment', $upload);
} // end if/else
} else {
wp_die("The file type that you've uploaded is not an image.");
} // end if/else
} // end if
} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');
function update_edit_form() {
echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
?>
I know that's a lot of code to be putting here, but I got shouted at last time I linked to pastebin [ ;) ], but any help would be greatly appreciated, as the site is nearly finished, but i'd really like to utilize the Publicize feature of Jetpack, so i'd prefer not to sacrifice it, but I NEED this bit to work.
Many thanks in advance! :)
Booooo! Rookie error! The unexpected output seems to have been caused by that section of my plugin being added onto the original custom post type section, which, of course ended with
?>
and the above section started with
<?php
which wordpress didn't seem to like.
Problem solved. For now...
*NB: This can probably be deleted now, or left for future reference :) *

Validate another field if file field is not empty

I'm trying to validate a field if a file fields is not empty. So if someone is trying to upload a file, I need to validate another field to make sure they selected what they are uploading, however I don't know how to check to see, or run a rule only if the field is not empty.
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('full_name, gender_id','required'),
array('video', 'file', 'types'=>'mp4', 'allowEmpty' => true),
array('audio', 'file', 'types'=>'mp3', 'allowEmpty' => true),
array('video','validateVideoType'),
);
}
public function validateVideoType() {
print_r($this->video);
Yii::app()->end();
}
So this->video is always empty whether I just uploaded something or not. How do I check to see if that variable is set?
Custom validation function must be defined properly. It has two parameters always $attribute & $params.
public function validateVideoType($attribute, $params) {
print_r($this->video);
Yii::app()->end();
}
Now in this you should write your custom way to validate.
I am sure that would work fine.
You can check it with jQuery/javascript, where 'new_document' is the name of the input file field.
if ($("#new_document").val() != "" || $("#new_document").val().length != 0) {
//File was chosen, validate requirements
//Get the extension
var ext = $("#new_document").val().split('.').pop().toLowerCase();
var errortxt = '';
if ($.inArray(ext, ['doc','docx','txt','rtf','pdf']) == -1) {
errortxt = 'Invalid File Type';
//Show error
$("#document_errors").css('display','block');
$("#document_errors").html(errortxt);
return false;
}
//Check to see if the size is too big
var iSize = ($("#new_document")[0].files[0].size / 1024);
if (iSize / 1024 > 5) {
errortxt = 'Document size too big. Max 5MB.';
//Show error
$("#document_errors").css('display','block');
$("#document_errors").html(errortxt);
return false
}
} else {
//No photo chosen
//Show error
$("#document_errors").css('display','block');
$("#document_errors").html("Please choose a document.");
return false;
}
This code is obviously not perfect for your needs but may have the requirements to piece together what you need.

Categories