Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all 14136 articles
Browse latest View live

CLI::prompt with rules validation

$
0
0
Hello,

I'm trying to build a spark Command but i'm having trouble with CLI::prompt

PHP Code:
<?php namespace App\Commands ;

use 
CodeIgniter\CLI\BaseCommand ;
use 
CodeIgniter\CLI\CLI ;

class 
CreateModel extends BaseCommand {

 protected 
$group 'Create' ;
 protected 
$name 'create:model' ;
 protected 
$description 'Création d’un fichier app/Models/XxxxModel.php, arguments : model_name , table_name[=model_name]' ;
 protected 
$usage 'php spark create:model [model_name] ?[table_name]' ;
 protected 
$arguments = [
 
'model_name' => 'le nom du model' ,
 
'table_name' => 'le nom de la table sans le préfixe, optionnel si le nom de la table est différent du nom du model' 
 
] ; 
 protected 
$options = [] ;

 public function 
run(array $params){
 if( ! 
is_array($params) OR ! isset($params[0])){
 
CLI::error('argument model_name manquant') ; 
 
CLI::newLine() ;
 return 
false ;
 }
 
helper('inflector');
 
$model_name pascalize($params[0].'_model') ; 
 
$model_filename $model_name 
 
$table_name = (isset($params[1])) ? $params[1] : $params[0] ; 


 
# on verifie si la table existe
 
$db = \Config\Database::connect() ; 
 
$table_exists $db->tableExists($table_name) ; 
 if( ! 
$table_exists){
 
CLI::error('la table '.$table_name.' n’existe pas encore dans la base de données') ; 
 
CLI::newLine() ;
 return 
false ;
 }
 
$fields $db->getFieldData($table_name) ; 
 
$fields_names array_column($fields,'name') ;

 
$primary_key CLI::prompt('Primary Key ?'$fields_names) ;

 
$return_type CLI::prompt('Return Type ? (array | object | __EntityClassName__)',null'required') ;

 
$file_content "<?php namespace App\Models ;".PHP_EOL 
 
."use CodeIgniter\Model ;".PHP_EOL
 
."class ".$model_name." extends Model {".PHP_EOL ;


 
$file_content .= "}".PHP_EOL ;


 
CLI::write($file_content) ; 
 }



that gives :

Code:
CodeIgniter CLI Tool - Version 4.0.3 - Server-Time: 2020-05-27 12:41:37pm

Primary Key ? [id, email, password, level, civilite, prenom, nom, sign, tel, add1, add2, cp, ville, pays, created_at, updated_at, deleted_at]:
Return Type ? (array | object | EntityClassName) : array
Le champ Return Type ? (array | object | EntityClassName)  est requis. (tr: the field is required)
Return Type ? (array | object | EntityClassName) : "array" ;
Le champ Return Type ? (array | object | EntityClassName)  est requis. (tr: the field is required)
Return Type ? (array | object | EntityClassName) :

It looks that all kind of validation rule does not work.
is there a special class to write "use" for validation to work ?
What am I coding wrong ?

(sorry my english is bad)

sending mail in html

$
0
0
I try different code but none works with me I am using CI4

PHP Code:
$email = \Config\Services::email();
$email->setFrom('email@example.com');
$email->setTo($sendto);
$email->setSubject($subject);
$email->setMessage($texte);
$email->mailType('html');

$email->send(); 

I got an error on $email->mailType('html');

I tried $email->set_mailtype("html"); same

I tried

PHP Code:
$config['mailtype'] = 'html'
$email = \Config\Services::email();
$email->initialize($config);

$email->setFrom('email@example.com');
$email->setTo($sendto);
$email->setSubject($subject);
$email->setMessage($texte);
$email->send(); 

No error but I receive the html code as text

How is the correct way of sending html mail

How to apply MySQLi options to database for numeric data type

$
0
0
I'm trying to get correct data type of numeric results from database (all return as strings).

I'm using MySQLi and the Connection Class (CodeIgniter\Database\MySQLi\Connection) doesn't seems to set up the option MYSQLI_OPT_INT_AND_FLOAT_NATIVE and doesn't have a way to do that from config/Database.

I've thinking to extend the Connection class, but the Option (i think) have to be set before mysqli real_connect is called (then, i have to rewrite all the function connect). On despite of that, i've try to extend Connection class without success. Any idea of how to achive this?

Of course, another solution would be to implement an entity for each data model, but i'm trying to get crude data to the frontend without this overhead.

There is a simple way to set up this configuration?

Codeingniter 4 Installation Issue on a live server

$
0
0
After installing CI4 on a live server, I keep on this on each of the pages
Quote:
No input file specified.
any solution?

Codeigniter CSV file undefined index

$
0
0
I'm trying to display the content of CSV file, using Codeigniter.
I used a library CSVReader (found here https://github.com/alemohamad/ci-csv-rea...Reader.php)
I got this error message :
A PHP Error was encountered Severity: Notice Message: Undefined index: head2

Here is my code. Please tell me what is wrong. Thanks

-- File contents

head1;head2
EBBST02;col
EBBST08;lad
EBBST12;vad
EBBST1;saz
EBBST19;xed
EBBSS28;red


--Controller


Code:
public function import(){
        $data = array();
        $memData = array();
        // If import request is submitted
        if($this->input->post('importSubmit')){
            // Form field validation rules
            $this->form_validation->set_rules('file', 'CSV file', 'callback_file_check');

            // Validate submitted form data
            if($this->form_validation->run() == true){

                // If file uploaded
                if(is_uploaded_file($_FILES['file']['tmp_name'])){
                    // Load CSV reader library
                    $this->load->library('CSVReader');

                    // Parse data from CSV file
                  // $csvData = $this->csvreader->parse_csv($_FILES['file']['tmp_name']);
                    $result =  $this->csvreader->parse_file($_FILES['file']['tmp_name']);
                    $data['csvDatadisp'] =$result;


            }else{
                $this->session->set_userdata('error_msg', 'Invalid file, please select only CSV file.');
            }
        }
        //redirect('uploadria');
        $this->load->view('chargement/ria.php', $data);
    }


--View

Code:
<!-- Data list table -->
        <table class="table table-striped table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th>Header 1</th>
                  <th>Header 2</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($csvDatadisp)){ foreach($csvDatadisp as $index => $value){ ?>
                <tr>
                    <td><?php echo $value['head1'] ?></td>
                    <td><?php echo $value['head2'] ?></td>
                </tr>
                <?php } }else{ ?>
                <tr><td colspan="5">No row found...</td></tr>
                <?php } ?>
            </tbody>
        </table>

Email Class TLS 587 SASL ERROR

$
0
0
Codeigniter 3

Hello, seems I always have problems with CI and email.

I run a properly configured Postfix / Ubuntu email server. I have several apps that authenticate via TLS port 587, with a valid user / pass.

I can't seem to get CI to work however.

here is my latest email.php config:
Code:
$config = array(
'protocol' => 'smtp', // smtp, mail, sendmail
'smtp_timeout' => 30, //in seconds
'smtp_crypto' => 'tls',
'smtp_host' => 'mail2.myserver.com',
'mailpath' => '/usr/bin/sendmail',
'smtp_port' => 587,
'smtp_auth' => TRUE,
'smtp_user' => 'user@mydomain.com',
'smtp_pass' => 'thepass',
'mailtype' => 'text',
'charset' => 'utf-8',
'crlf' => "\r\n",
'smtp_keepalive' => TRUE,
'send_multipart' => FALSE,
'newline' => "\r\n",
'wordwrap' => TRUE
);

Then the result from $this->email->print_debugger();
Code:
hello: 250-mail2.mydomain.com
250-PIPELINING
250-SIZE 15240000
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-SMTPUTF8
250 CHUNKING

starttls: 220 2.0.0 Ready to start TLS

hello: 250-mail2.mydomain.com
250-PIPELINING
250-SIZE 15240000
250-ETRN
250-AUTH PLAIN
250-AUTH=PLAIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-SMTPUTF8
250 CHUNKING

Failed to send AUTH LOGIN command. Error: 535 5.7.8 Error: authentication failed: Invalid authentication mechanism

Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.

Date: Thu, 28 May 2020 00:27:29 +0000
From: "My Email" <support@domain.com>
Return-Path: <support@domain.com>
To: orders@domain.com
Subject: =?UTF-8?Q?My=20Domain=20Email=20Test?=
Reply-To: <support@domain.com>
User-Agent: CodeIgniter
X-Sender: support@domain.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <5ecf057157707@domain.com>
Mime-Version: 1.0


Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Testing the My Domain Order Email


I've been tweaking config values for a few hours. Nothing seems to help. Any thoughts appreciated.

update form validation

$
0
0
hello, I have a problem with select options, it is necessary that when entering the edit page, bring the selected item as it appears in the database, when the post is executed if there are validations errors return to the edit page but with the select option selected according to last choice of the user, example when entering the database the option FORD the user changes to VW and submits the form and does not pass the validation of other fields must return to the edition form with the selected VW option.---- MODEL
public function updaterecord($data)
    {
        $id = $data['UsuID'];
        return $this->where('UsuID', $id)
            ->set([
                'UsuLogin' =>  $data['UsuLogin'],
                'UsuNome' =>   $data['UsuNome'],
                'UsuCPF' =>    $data['UsuCPF'],
                'UsuNivel' =>  $data['UsuNivel'],
                'UsuStatus' => $data['UsuStatus']
            ])
            ->update();
    }----CONTROLE
public function update($id = NULL)
    {
        if ($this->request->getMethod() === 'post') {
            $data = $this->request->getPost();
            if($this->usuarioModel->updaterecord($data) == false){
                $session = session();
                $msgerrors = ['errors' => $this->usuarioModel->errors()];
                $session->setFlashdata($msgerrors, $data);
                return redirect()->back()->withInput();
            }
        }else{
            $data['dados'] = $this->usuarioModel->showid($id);
            echo view('includes/header');
            echo view('includes/menu');
            echo view('usuario_editar', $data);
            echo view('includes/footer');        }----VIEW<?php
              $v1=''; $v2 = '';
              if($dados[0]['UsuStatus'] === "0" || old('UsuStatus') === "0"){
                $v1 = 'selected';
              }else{
                $v1='';
              }
              if($dados[0]['UsuStatus'] === "1"  || old('UsuStatus') === "1"){
                $v2 = 'selected';
              }else{
                $v2='';
              }
          ?>
          <div class="form-group col-md-3 cb">
            <label for="cbusustatus">Ativo - Status</label>
            <select class="form-control" id="cbusustatus" name="UsuStatus">
              <option value="0"  <?php echo $v1 ?>>0-Sim </option>
              <option value="1" <?php echo $v2 ?>>1-Não </option>
            </select>
          </div>

help with My Model.

$
0
0
Good Day Everyone. Please urgently help with My Model. I want to get users from table users in db. Model returns Null/ array(0). Below is my code for the controller and model. Thanks in advance 

Unknown column 'stud.id' in 'where clause'

$
0
0
Hi! I encounter the error "Unknown column 'stud.id' in 'where clause'. I don't have any stud.id in my files and also in my database. What do you think the problem with this? I'm using Codeigniter 4.

Below is my code on my Controller:


Code:
    $model = new Mod_Stud();
    $id = $this->request->getVar('stud_id');

    $data = [
                'stud_id' => $this->request->getVar('stud_id'),
                'lname' => $this->request->getVar('lname'),
                'fname' => $this->request->getVar('fname'),
                'mname' => $this->request->getVar('mname'),
    ];

    $save = $model->update($id,$data);
    return redirect()->to( base_url('/') );

Code for my Model:

Code:
    protected $table = 'stud';
    protected $allowedFields = ['stud_id', 'sy', 'dpt', 'grd', 'lname', 'fname', 'mname', 'gender', 'bday', 'birthplace', 'religion', 'nationality', 'country', 'address', 'f_name', 'f_occ', 'm_name', 'm_occ', 'g_name', 'g_rel', 'created_at', 'updated_at'];

Can not use CURL in codeigniter 4

$
0
0
It is not possible to use pure php curl request in ci4 without using the curl request class?
my curl response here work in ci3 buth is returning null here in ci4

PHP Code:
$ch curl_init('https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify');                                                                      
            curl_setopt
($chCURLOPT_CUSTOMREQUEST"POST");
            curl_setopt($chCURLOPT_POSTFIELDS$data_string);                                              
            curl_setopt
($chCURLOPT_RETURNTRANSFERtrue);
            curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
            curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    
            $response 
curl_exec($ch);
    
            $header_size 
curl_getinfo($chCURLINFO_HEADER_SIZE);
            $header substr($response0$header_size);
            $body substr($response$header_size);
    
            curl_close
($ch);
    
            $resp 
json_decode($responsetrue); 

When try to var dump $resp it return empty and my payment gateway notify success in the payment dashbord.

Paypal Integration

Google eCommerce Tracking?

$
0
0
Hi,

can anyone help me how to setup "Google eCommerce Tracking" in my CI website.


Thanks
KC

web hosting and ci4

$
0
0
Hi
sorry my english, i'm italian and i don't speak english very well.
i am trying to install ci4 on a web hosting but i have the error attached.
Can anyone help me?


.jpg   error.jpg (Size: 9.39 KB / Downloads: 1)

suggest to change the position of the parameters of the update in class Model

$
0
0
I think, when i use update(), I always need to set the data, but not use the primary key every time. So suggest to change the position of the parameters from 

public function update($id = null, $data = null)
to
public function update($data = null, $id = null)

Setup for Apache on Ubuntu Server

$
0
0
My apologies, I know this topic has been addressed several times already on this forum. However, I can't get my installation to work properly.

This is my setup: I have an Ubuntu 18.04 server, with Apache. I've setup my virtual host like this:

Code:
<VirtualHost *:80>
    ServerAdmin admin@admin.com
    ServerName jules
    ServerAlias jules
    DocumentRoot /var/www/jules/appstarter/public
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>


.env like this:
Code:
CI_ENVIRONMENT = development

#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------

app.baseURL = 'http://jules/'

I installed the appstarter trough composer in /var/www/jules/appstarter/ , and I when i go to http://jules, I see the welcome page for CodeIgniter, so far so good.

Now of course I want to remove index.php, so I've set $indexPage = ''; in Config/App.php

I tried all sorts of different things for the RewriteBase directive in .htaccess, but no matter what I do, http://jules/login does not work, but http://jules/index.php/login does. What could be wrong?

.htaccess in /var/www/jules/appstarter/public:

Code:
# Disable directory browsing
Options All -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # If you installed CodeIgniter in a subfolder, you will need to
    # change the following line to match the subfolder you need.
    # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
    RewriteBase /appstarter/

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to the front controller, index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
    ServerSignature Off
# Disable server signature end

For RewriteBase I've tried '/appstarter/', 'appstarter', '/appstarter', '/appstarter/public', '/', etc.

Integrate Microsoft Teams

$
0
0
Use of online services where to upload link files etc.
Now we use Microsoft Teams for video calls and I was wondering if anyone has found a way to integrate it with Codeigniter.

Thanks

About global mysql connection on CI 4

$
0
0
Hello there,

I was using CI 3, but today i downloaded version 4. I could not set $db variable global to use every function?

Anyone can give me example code ?

Thanks...

PHP Code:
<?php namespace App\Controllers;

ini_set('display_errors',1);
class 
Home extends BaseController
{
    public function 
__construct()
    {

        
$db = \Config\Database::connect();
}
    public function 
index()
    {
        
$query $this->db->query('SELECT * FROM cats');
    
  $results $query->getResult();
print_r($results);
$data = [];
    
//    $data['cats'] = $results;
        
return view('index');

    }


    
//--------------------------------------------------------------------


ci_session cookie rejection warning

$
0
0
Hi!
I have noticed Firefox giving the following warning in the console:

Cookie “ci_session” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value, without the “secure” attribute. To know more about the “sameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Cookies

Anything I can fix as a user?

error returning a view with $data from ajax

$
0
0
I have got a error 500 when from a controller called from a ajax function if in the controller return a view with params.

the js/ajax call:

Code:
function insertFotosNew(url,id){
        var form = document.querySelector('#new-fotos-form');
        var fd = new FormData(form);
        var url_return = '<?=base_url('propiedad_edit/')?>/'+id;

        $.ajax({
            type: "POST",
            url: '<?=base_url('subir_fotos')?>',
            data: fd,
            contentType: false,
            processData: false,
            success: function (resultado) {
                console.log(resultado);
                $('#modal-new-foto').modal('hide');
                $('#productoForm').submit();

            },
            error: function (resultado) {
                alert('Se ha producido un error al conectar con el servidor.');
            }
        });
     }

the controller code:

PHP Code:
namespace App\Controllers\Administracion\Propiedades;

use 
App\Controllers\Repositories\ProductosFotosRepository;

class 
SubirFotos extends PropiedadesBaseController
{
    protected $response;
    protected $productosFotosRepository;

    /**
     * SubirFotos constructor.
     */
    public function __construct(){
        parent::__construct();
        $this->productosFotosRepository = new ProductosFotosRepository();

    }

    /**
     * @return View
     */
    public function run(){
        $todo       $this->request->getPost();
        $files      $this->request->getFiles();

        $data = array();

        if(count($files) > 0) {
            $this->respuesta $this->propiedadNewFotoUpload($todo['id_producto'], $files);
            $data['fotos'] =  $this->productosFotosRepository->getProductoFotos($todo['id_producto']);
        else  {
            $this->respuesta->mensaje 'No hay ficheros para subir';
            $this->respuesta->estado EXIT_ERROR;
        }

        echo view('Administracion/Propiedades/propiedades_form_fotos'$data);

    }



The same error if echo the view:
PHP Code:
echo  view('Administracion/Propiedades/propiedades_form_fotos'$data); 

If only echo (or return) the view without %data, no occurs the error 500.

This in CI3 not produces this error.

Can help?

Tanks

CI4.0.3 Error CORS ON GET

$
0
0
I am using REST API but much problems with CORS in apache + ubuntu 16.0.4.

I have errors CORS when my application (AngularJS) try to do the GET and don't have the '?' on end of URL.  Example: GET api.xxx:8080/controller?/

Anybody have solution to this?

My APP.php

public $uriProtocol = 'REQUEST_URI';
public $indexPage = '';

My .htaccess
Code:
# Disable directory browsing
Options All -Indexes

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</IfModule>

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # If you installed CodeIgniter in a subfolder, you will need to
    # change the following line to match the subfolder you need.
    # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
    # RewriteBase /

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to the front controller, index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
    ServerSignature Off
# Disable server signature end
Viewing all 14136 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>