Multiple conditional in Laravel Middleware - laravel

I have a middleware like this:
class HasBilling {
public function handle($request, Closure $next) {
$user_profile = UsersProfile::where('user_id', Auth::id())->first();
if (!is_object($user_profile) && !\Auth::user()->hasPermissionTo('soy-agente') && !\Auth::user()->hasPermissionTo('soy-agente_inversor')) {
return redirect()->route('myaccount.facturacion.ver')->with('error', 'No posees datos de facturación. Antes de usar algunas funciones como facturación, publicidad, merkado, tarifas... debes rellenar los datos.');
}
if(is_object($user_profile) && is_null($user_profile->validate)){
return redirect()->route('myaccount.facturacion.ver')->with('error', 'Tus datos de facturación están pendiente de validar');
}
if(is_object($user_profile) && $user_profile->validate == 2){
return redirect()->route('myaccount.facturacion.ver')->with('error', 'Tus datos de facturación han sido rechazados.');
}
if(!is_null(\Auth::user()->activity) && \Auth::user()->activity == "empresa"){
$autorizado = UsersProfileAutorizado::find($user_profile->id);
if(!is_object($autorizado)){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'No posees ningún autorizado. Al ser una empresa, antes de usar algunas funciones como la facturación o la publicidad debes rellenar los datos de autorizado.');
}
if(is_object($autorizado) && is_null($autorizado->validate)){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'Tu autorizado está pendiente de validar.');
}
if(is_object($autorizado) && $autorizado->validate == 2){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'Tu autorizado ha sido rechazado.');
}
}
return $next($request);
}
}
The problem with this is that it checks the first IF, but the others are omitted.
The middleware works because the first if always checks for it, but the rest "ignore" them.
How can i fix that?

You could store the errors in an array, and redirect at the end of the method.
class HasBilling {
public function handle($request, Closure $next) {
$errors = [];
$user_profile = UsersProfile::where('user_id', Auth::id())->first();
if (
!is_object($user_profile)
&& !\Auth::user()->hasPermissionTo('soy-agente')
&& !\Auth::user()->hasPermissionTo('soy-agente_inversor')
) {
$errors[] = 'No posees datos de facturación. Antes de usar algunas funciones como facturación, publicidad, merkado, tarifas... debes rellenar los datos.';
}
if (
is_object($user_profile)
&& is_null($user_profile->validate)
){
$errors[] = 'Tus datos de facturación están pendiente de validar');
}
// Add other checks where you can append $errors array
if (count($errors) > 0) {
return redirect()
->route('myaccount.facturacion.ver')
->with('errors', $errors);
}
return $next($request);
}
}
When reading the errors in the 'myaccount.autorizado.ver route, you have to make sure to read, parse and show the $errors array instead of the single error. For example in a foreach that shows a list of errors.

Related

PayPal - Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAYID-L6ZZRNY2CA2198940171953X/execute

I am using the SAME code that I use on another platform, but the difference is that here I use euros.
I have created a different PayPal account, which is also in euros.
private $_api_context;
public function __construct()
{
//setup PayPal api context
$paypal_conf = \Config::get('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
$this->_api_context->setConfig($paypal_conf['settings']);
}
public function postPayment()
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$items = array();
$subtotal = 0;
$cart = \Session::get('cart');
$currency = 'EUR';
//PEDIDO ACTUAL
$pedidoActual = DB::table('pedido as pe')
->select('pe.subtotal')
->where('pe.idpedido','=',$cart['idpedido'])
->first();
$monto = number_format($pedidoActual->subtotal,2);
$item = new Item();
$item->setName("Pedido de Momento Mágico")
->setCurrency($currency)
->setDescription("Entrega a domicilio incluido")
->setQuantity(1)
->setPrice($monto);
$items[] = $item;
$subtotal = $monto;
///////////////
$item_list = new ItemList();
$item_list->setItems($items);
//Nos sirve si queremos agregar un costo por el envío
$details = new Details();
$subtotal = $subtotal;
$details->setSubtotal($subtotal)
->setShipping(0);
//Es el objeto que tiene la moneda, el detalle a pagar y envio
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($subtotal)
->setDetails($details);
//Los datos de la transacción
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Pedido de Prueba en App Store');
//Recibe la ruta si se realiza o se cancela el pago
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(\URL::route('payment.status'))
->setCancelUrl(\URL::route('payment.status'));
//A traves del objeto Payment creamos el pago
$payment = new Payment();
$payment->setIntent('Sale') //De tipo Venta directa, puede ser de otros tipos
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
//Enviamos el pago y si hay errores lo mostramos en el Debug
try
{
$payment->create($this->_api_context);
}
catch (\PayPal\Exception\PPConnectionException $ex) {
if (\Config::get('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
exit;
} else {
die('Ups! Algo salió mal');
}
}
// Si todo salió bien, Paypal nos devuelve información
foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
// add payment ID to session // para darle seguimiento al usuario que lo hizo
\Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// redirect to paypal
return \Redirect::away($redirect_url);
}
return \Redirect::route('home')
->with('error', 'Ups! Error desconocido.');
}
public function getPaymentStatus(Request $request)
{
// Get the payment ID before session clear
$payment_id = \Session::get('paypal_payment_id');
$cart = \Session::get('cart');
// clear the session payment ID
\Session::forget('paypal_payment_id');
$input = $request->all();
$payerId = Arr::except($input,array('PayerID'));
$token = Arr::except($input,array('token'));
//$payerId = \Input::get('PayerID');
//$token = \Input::get('token');
//if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
if (empty($payerId) || empty($token) || empty($payment_id)) {
$notificarError = (new MailController)->errorPagoPaypal();
return \Redirect::route('home')
->with('message', 'Hubo un problema al intentar pagar con Paypal');
}
//Si se pudo realizar el pago
$payment = Payment::get($payment_id, $this->_api_context);
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($payerId);
//Execute the payment
$result = $payment->execute($execution, $this->_api_context);
//echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later
if ($result->getState() == 'approved') { // payment made
// Eliminar carrito
// Enviar correo a user
$fecha_prog_envio = (new CartController)->obtenerFechaEnvio($cart['tipo_producto']);
// Enviar correo a user
$notificarPagoPayPal = (new MailController)->notificarPagoIngresado($fecha_prog_envio,'PayPal');
$this->saveOrder(\Session::get('cart'),$fecha_prog_envio);
\Session::forget('cart');
return \Redirect::route('home')
->with('message', 'Pago realizado correctamente.');
}
return \Redirect::route('home')
->with('message', 'La compra fue cancelada');
}
I have already read all the forums, checked the amounts are correct and it doesn't work.
It is not an authentication issue as I have tried to connect to the other platform and the error is the same.
I imagine that the error may come from the currency exchange, the total amount. But I have not found the error.
$execution->setPayerId($payerId);
What is the value of $payerId at this stage of using it? Log it.
It's supposed to be a plain string value, but your code before this where you set and check payerId looks funny, I don't trust the value.

Display an admin notice after a term creation in WordPress

I do not understand how to display a notice after a term creation in WordPress.
I have a custom field in a custom taxonomy. On the save event, I check if the value is incorrect and in this case, I want to display a notice.
I have a similar situation in the post editor but here I have solved with add_settings_error and admin_notices.
This method does not work in the term creation screen because in this scenario, there is an AJAX request and the page does not reload.
Here is the code about term screen:
add_action('create_account', 'save_start_amount_data__fr');
add_action('admin_notices', 'display_start_amount_data_validation_error__fr');
function save_start_amount_data__fr($term_id) {
if (
!isset($_POST['start_amount_nonce']) ||
!wp_verify_nonce($_POST['start_amount_nonce'], 'start_amount_nonce')
) {return $term_id;}
if (
(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
) {return $term_id;}
if (
!isset($_POST['taxonomy']) ||
$_POST['taxonomy'] != 'account' ||
!current_user_can('edit_posts')
) {return $term_id;}
if (
!isset($_POST['start_amount'])
) {return $term_id;}
if (
!preg_match('/^[-]?[0-9]+([,]?[0-9]{1,2})?$/', $_POST['start_amount'])
) {validate_start_amount_data__fr();}
$start_amount = $_POST['start_amount'];
$start_amount = sanitize_text_field($start_amount);
update_term_meta($term_id, 'start_amount', $start_amount);
return $term_id;
}
function validate_start_amount_data__fr() {
add_settings_error(
'incorrect_start_amount_value',
'incorrect_start_amount_value',
__('Please review the start amount value because it is in an incorrect format.', 'fr'),
'error'
);
set_transient('settings_errors', get_settings_errors(), 30);
return null;
}
function display_start_amount_data_validation_error__fr() {
$errors = get_transient('settings_errors');
if (!$errors) {return null;}
$message = '<div class="notice notice-error"><ul>';
foreach($errors as $error) {
$message .= '<li>' . $error['message'] . '</li>';
}
$message .= '</ul></div>';
echo $message;
delete_transient('settings_errors');
remove_action('admin_notices', 'display_start_amount_data_validation_error__fr');
return null;
}
I hope that someone can help me to achieve my goal.
See below the method that I'm using on a Custom Posts to display notifications.
Take a look to the filter "redirect_post_location".
//Actions
$this->loader->add_action( 'admin_notices', $plugin_admin, 'general_admin_notice' );
$this->loader->add_action( 'save_post', $plugin_admin, 'admin_save_post' );
/**
* Admin Save the Meta box values
*
* #since 1.0.0
*/
function admin_save_post( $id ) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['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['secure_doc_attachment']['name'])) {
$upload = $this->admin_upload_file( $_FILES , $id );
if (!$upload){
add_filter('redirect_post_location', function($loc) {
return add_query_arg( 'error', 1, $loc );
});
return $post_id;
}
}
}
/**
* Admin Notice
*
* #since 1.0.0
*/
function general_admin_notice(){
global $pagenow;
if ( 'post.php' === $pagenow && isset($_GET['post']) && 'custom-post' === get_post_type( $_GET['post'] ) ){
if ( isset($_GET['error'])) {
echo '<div class="notice notice-error is-dismissible">
<p>Error uploading the attachment.</p>
</div>';
}
}
}
See other useful link here:
https://wordpress.stackexchange.com/questions/124132/admin-post-update-redirection-to-posts-screen
Regards.
Ed.

AJAX POST request not working with XMLHttpRequest in Laravel

I'm using XMLHttpRequest to avoid using JQuery and I wanna make an Ajax request to delete an object but I keep getting redirected back and getting FOUND (302) HTTP errors.
This is my code:
function deleteGuia(urlToSend) {
var borra = confirm('¿Está seguro de borrar la guía?');
if (!borra) {
return;
}
var req = new XMLHttpRequest();
var csrfToken = document.querySelector('meta[name="csrf-token"]').content;
req.open("POST", urlToSend, true);
req.setRequestHeader('X-CSRF-TOKEN', csrfToken);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (this.readyState === this.DONE) {
console.log(this.responseURL);
}
if (req.status != 200) {
var msg = JSON.parse(req.response);
alert(msg.error);
} else {
alert('Exitoso');
}
}
}
var data = new FormData();
var guia = "{{$guia ?? ''}}";
var estado = "{{$tipo ?? ''}}";
data.append("guia", guia);
data.append("tipo", estado);
req.send(data);
}
</script>
This one's the controller function:
public function eliminarGuia(Request $request) {
$request->validate([
'guia' => 'required|numeric',
'tipo' => 'required'
]);
$guia = (int)$request->input('guia');
$tipo = $request->input('tipo');
\Log::info('Guia' . $guia . ' Tipo: '. $tipo);
if (strtoupper($tipo) === 'ENTREGA'){
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$borra_ciclos = Device::where('guia_recepcion', $guia)->delete();
if(!$borra_guia) {
return response(400)->json(['error', 'La guía no se encontró.']);
}
} else if (strtoupper($tipo) === 'REVERSA') {
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$devices = Device::where('guia_reversa', $guia)->get();
if (!$borra_guia){
return response(400)->json(['error', 'La guía no se encontró.']);
}
foreach($devices as $device)
{
if (!$device->fecha_recepcion) {
$device->delete();
} else {
$device->guia_reversa = 0;
$device->fecha_reversa = null;
$device->save();
}
}
} else {
return response(400)->json(['error', 'La guía no se encontró.']);
}
return response(200);
}
web.php
Route::post('borrar_guia', 'VistasController#eliminarGuia')->name('borrar_guia');
There's no redirection at all. Why might that be happening? I don't know what else to add. The controller should return a 200 code when it delets an existing object in the database but it's getting a 200 from the redirection.

Error uploading an image in symfony 3.4

I'm trying to upload an image in symfony 3, but when i execute my controller display me this error message "Call to a member function guessExtension() on string ". Before the image was stored in my directory web/uploads/images only and not in my database. And when i try to fix this problem, i have this error.
This is my entity:
namespace Doctix\MedecinBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
/**
* Media
*
* #ORM\Table(name="media")
* #ORM\Entity(repositoryClass="Doctix\MedecinBundle\Repository\MediaRepository")
* #ORM\HasLifecycleCallbacks
*/
class Media
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank(message="Ajouter une image valide")
* #Assert\File(mimeTypes={ "image/jpeg", "image/png", "image/gif" })
*/
private $image;
// On ajoute cet attribut pour y stocker le nom du fichier temporairement
private $tempFilename;
// On modifie le setter de File, pour prendre en compte l'upload d'un
fichier
lorsqu'il en existe déjà un autre
public function getImage()
{
return $this->image;
}
public function setImage($image)
{
$this->image = $image;
return $this;
// On vérifie si on avait déjà un fichier pour cette entité
if (null !== $this->url) {
// On sauvegarde l'extension du fichier pour le supprimer plus tard
$this->tempFilename = $this->url;
// On réinitialise les valeurs des attributs url et alt
$this->url = null;
$this->alt = null;
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->image) {
return;
}
// Le nom du fichier est son id, on doit juste stocker également son
extension
// Pour faire propre, on devrait renommer cet attribut en « extension »,
plutôt que « url »
$this->url = $this->image->guessExtension(); **Error location**
// Et on génère l'attribut alt de la balise <img>, à la valeur du nom du
fichier sur le PC de l'internaute
$this->alt = $this->image->getClientOriginalName();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->image) {
return;
}
// Si on avait un ancien fichier, on le supprime
if (null !== $this->tempFilename) {
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this-
>tempFilename;
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
// On déplace le fichier envoyé dans le répertoire de notre choix
$this->image->move(
$this->getUploadRootDir(), // Le répertoire de destination
$this->id.'.'.$this->url // Le nom du fichier à créer, ici « id.extension
»
);
}
/**
* #ORM\PreRemove()
*/
public function preRemoveUpload(){
// On sauvegarde temporairement le nom du fichier, car il dépend de l'id
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload(){
// En PostRemove, on n'a pas accès à l'id, on utilise notre nom sauvegardé
if (file_exists($this->tempFilename)) {
// On supprime le fichier
unlink($this->tempFilename);
}
}
public function getUploadDir(){
// On retourne le chemin relatif vers l'image pour un navigateur
return 'uploads/images';
}
protected function getUploadRootDir(){
// On retourne le chemin relatif vers l'image pour notre code PHP
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath(){
return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* #param string $url
*
* #return Media
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set alt
*
* #param string $alt
*
* #return Media
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
}
Then my controller:
public function mediaEditAction(Request $request){
$media = new Media();
$form = $this->createForm(MediaType::class, $media);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $media->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move(
$this->getParameter('images_directory'),
$fileName
);
$media->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
$request->getSession()->getFlashBag()->add('Notice', 'Photo ajoutée
avec succès');
// redirection
$url = $this->generateUrl('medecin_parametre');
// redirection permanente avec le status http 301 ::)))))
return $this->redirect($url,301);
}else{
return $this-
>render('DoctixMedecinBundle:Medecin:mediaedit.html.twig', array(
'form' => $form->createView()
));
}
}
Thanks.
Тhe image property of your entity is a string, so it is normal to get the error.
If you want to use guess extension you can use like following:
use Symfony\Component\HttpFoundation\File\File;
$file = new File($this->getUploadRootDir() . '/' . $this->image);
$this->url = $file->guessExtension();

Upload a pdf in Codeigniter

I want to upload a file from a form. It's working fine with .doc files but .pdf's don't work all the time. I'm not able to load my pdf named compositionFinale.pdf (3.67 MB)
I tried with another big pdf that was more than my $_FILES["size"] and I have an error that tells me:"Ce fichier est trop volumineux" (the file is too big).
But with compositionFinale.pdf that is also too big it doesn't pass in my
if ($_FILES["offre"]["size"] > 500000) (I put a echo to test). I don't have an error at the end and it tells me that the file is uploaded, but when I check in the file it is not.
EDIT: I tried to save this pdf as a reduced size pdf and when I upload my file it tells me that my file is too big. Which is fine. But why does not tell me it is too big when it was not reduced in size?
Is anyone see something I don't?
My controller
function publierOffreEmploi()
{
// validation
$this->form_validation->set_rules('poste', 'Poste', 'required|max_length[255]');
$this->form_validation->set_rules('ville', 'Ville', 'required|max_length[50]');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('secteurs[]', "Secteur(s) d'activité", 'required');
$this->form_validation->set_rules('date_fin_publication', 'Date de la fin de publication', 'required');
$this->form_validation->set_error_delimiters('<br /><span class="error erreur">', '</span>');
// si erreur dans la validation
if ($this->form_validation->run() == FALSE)
{
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view');
$this->_layoutBas();
}
// si aucune erreur dans la validation
else
{
// +++++++++++++++++++++++++++++++++++++++++++
$target_dir = "assets/uploads/";
$name = basename($_FILES["offre"]["name"]);
$target_file = $target_dir . basename($_FILES["offre"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$message = '';
// Si le formulaire a bien été envoyé
if(isset($_POST["submit"]))
{
// Vérifie si un fichier est bien sélectionné
if(($_FILES['offre']['name'])!= '')
{
$uploadOk = 1;
$pasDeFichier = "";
}
else
{
// définir le message d'erreur de l'image si le fichier choisi n'est pas une image
$uploadOk = 0;
$pasDeFichier = "Vous devez importer un fichier";
}
// si le fichier existe déja
if (file_exists($target_file))
{
// définir le message d'erreur de l'image si l'image existe déja dans le fichier de téléchargement
$uploadOk = 0;
$message.= "Ce fichier exite déja. Veillez le renommer<br>";
}
// si le fichier est plus gros que 500Ko
if ($_FILES["offre"]["size"] > 500000)
{
echo "too big";
die();
$uploadOk = 0;
// définir le message d'erreur si l'image est trop volumineuse
$message.= "Ce fichier est trop volumineux<br>";
}
// définir les formats autorisés
if($imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx" && $imageFileType != "DOC" && $imageFileType != "DOCX" && $imageFileType != "PDF")
{
// définir le message d'erreur si l'image n'est pas d'un format accepté
$uploadOk = 0;
$message.= "Seuls les fichiers .pdf, .doc et .docx sont acceptés";
}
// si erreur donc pas d'upload et retour au formulaire avec message d'erreur en fonction de l'erreur
if ($uploadOk == 0)
{
if ($pasDeFichier != "") {
$data=array();
$data["message"]= $pasDeFichier;
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view', $data);
$this->_layoutBas();
}
else{
$data=array();
$data["message"]= $message;
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view', $data);
$this->_layoutBas();
}
}
/*si l'image a été uploadé*/
else
{
if (move_uploaded_file($_FILES["offre"]["tmp_name"], $target_file)){
}
// Création d'une variable contenant le id de l'entreprise connectée
$idEntreprise = $this->entreprise_model->lire('id', $conditions = array('courriel' => $_SESSION["courriel_entreprise"]));
/*Transformer l'objet en tableau. Nous permet de stocker le id*/
$data=array();
$data["idEntreprise"]= $idEntreprise;
foreach ($idEntreprise as $id) {
}
// ------------------------------ CHECKBOX SECTEURS -----------------------------------------
// Récupération et concaténation des valeurs du checkbox multiple (secteurs)
//déclaration de la variable qui contiendra tous les secteurs
$secteurs ='';
//boucle afin d'optenir tous les secteurs
for ($i=0;$i<count($_POST['secteurs']);$i++)
{
//concaténation des champs
$secteurs .= $_POST['secteurs'][$i];
}
// données envoyées au modèle
$form_data = array(
'poste' => set_value('poste'),
'ville' => set_value('ville'),
'description' => set_value('description'),
'date_fin_publication' => set_value('date_fin_publication'),
'entreprise_id' => $id['id'],
'secteur' => $secteurs,
'type_offre_id' => 2,
'statut_offre_id' => 2,
'offre' => $name
);
// insertion dans la bd
// si l'insertion est un succes
if ($this->offre_model->inserer($form_data) == TRUE)
{
redirect('offre_controller/succes_publication_offre_emploi');
}
// si l'insertion est un echec
else
{
redirect('offre_controller/echec_publication_offre');
}
}
}
}
}
My pdf file
My form
<!-- UPLOAD DE L'OFFRE (PDF, DOC, DOCX) -->
<p>
<!-- affichage du message (gestion des messages d'erreurs) -->
<label for="offre" class="labelVisible labelFile">Veuillez importer votre offre d'emploi<span class="required"></span></label>
<?php echo form_error('offre'); ?>
<input id="offre" type="file" name="offre"/>
<br />
<?php
// si un mesasge d'erreur existe
if(isset($message))
{
?>
<span class="erreur"> <?php echo $message; ?></span>
<?php
}
?>
</p>
Thanks
I bet that PHP upload_max_filesize is set as default (2MB) you need to go to php.ini file and search for upload_max_filesize and change that to whatever you need (8MB, 32MB...). Also you need to set post_max_size to same size or higher.
I assume you are on Windows machine, running XAMPP, right click on icon and look for php.ini file open it and do your magic.

Resources