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

get and post ID to new join table

$
0
0
Hi everyone,
I'm coding a Stock Management System to manage order and deliveries. My system is design in a way that when an order is placed, the Admin logs in to the Order list, clicks on Stock where a page comes up and he has to provide details of the delivery including changing the status.
 But when i join tables order and stock i cant record any information in the database anymore. the system dysplays

Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`data`.`stock`, CONSTRAINT `stock_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `sm_storage` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)


Please could anyone explain how to post ids from parent table to child table

.png   Capture.PNG (Size: 21.65 KB / Downloads: 0)

codeigniter 4 routes issue

$
0
0
I have a problem with codeigniter 4 routing with slash of end. my project in a subdirectory, when be "/" in the end of url , redirect to root and show not fount.

.png   whitout_slash.PNG (Size: 4.69 KB / Downloads: 0)

.png   with_slash.PNG (Size: 5.48 KB / Downloads: 0)

Session data lost on redirect

$
0
0
Hi,
I'm struggling to to properly redirect from a filter. I'm trying to store some data in the SESSION before returning from the filter with the idea to use the data in the page redirected to.

Everything works fine when I use secure connection (https). Without a secure connection the data written to teh SESSION is gone when I try to read it on the redirection target page. These are my coockie and session settings:

PHP Code:
    public $sessionDriver            'CodeIgniter\Session\Handlers\FileHandler';
    public 
$sessionCookieName        'ci_session';
    public 
$sessionExpiration        7200;
    public 
$sessionSavePath          WRITEPATH 'session';
    public 
$sessionMatchIP           false;
    public 
$sessionTimeToUpdate      300;
    public 
$sessionRegenerateDestroy false;
    public 
$cookiePrefix   'nexus_';
    public 
$cookieDomain   '';
    public 
$cookiePath     '/';
    public 
$cookieSecure   false;
    public 
$cookieHTTPOnly false

Any help is much appreciated.

CodeIniter 4 plus Myth/Auth throws error when runnung Migrations via php spark migrat

$
0
0
I have discovered some weird bevavior, I have that one CI4 project i am working on since a couple of weeks. everything is working just fine, but until now i have just been working withe the project on my local machine. When i wanted to ron the project on my Laptop in ran into an error when i tried to run the migrations with php spark migrate -all

 
Code:
CodeIgniter CLI Tool - Version 4.0.4 - Server-Time: 2020-07-20 06:16:02am
   
   
   
    Running all new migrations...
   
    An uncaught Exception was encountered
   
   
   
    Type:        CodeIgniter\Database\Exceptions\DatabaseException
   
    Message:    Unable to connect to the database.
   
    Filename:    /opt/lampp/htdocs/sms/vendor/codeigniter4/framework/system/Database/BaseConnection.php
   
    Line Number: 425


The project includes Myth/auth, so i tried just to run "my" migration with php spark migrate . That just worked fine, no problem at all, the tables are there, no eroors. Just for fun, i moved my Math/auth migrations from the vendor folder to the "normal" Database/Migrations folder and was able to migrate them that way.

Thats very weird, especally since everything is working just fine on the PC I have been using before. There I am able to run the migrations using php spark migrate -all without any errors, when is set up a fresh MySQL/MariahDB database. But somehow only there.


I was able to reprocude the error on my laptop on my Manjaro partition, my Windows 10 partion an on my iMac.
So if you want to reproduce the error  do the following:

1.
Code:
composer create-project codeigniter4/appstarter whatever

2. renaame the `env` to .`env`
3. set `CI_ENVIRONMENT = development` and obviously uncomment that line
4. configure and uncomment your database setting in the .env
5. create a sample migration like the one from the docs using
Code:
> php spark migrate:create AddBlog

6. add the following content  to the new migration and save the file:
   
PHP Code:
<?php namespace App\Database\Migrations;
   
    
use CodeIgniter\Database\Migration;
   
    
class AddBlog extends Migration
    
{
   
            
public function up()
            {
                    $this->forge->addField([
                            'blog_id'          => [
                                    'type'          => 'INT',
                                    'constraint'    => 5,
                                    'unsigned'      => true,
                                    'auto_increment' => true,
                            ],
                            'blog_title'      => [
                                    'type'          => 'VARCHAR',
                                    'constraint'    => '100',
                            ],
                            'blog_description' => [
                                    'type'          => 'TEXT',
                                    'null'          => true,
                            ],
                    ]);
                    $this->forge->addKey('blog_id'true);
                    $this->forge->createTable('blog');
            }
   
            
public function down()
            {
                    $this->forge->dropTable('blog');
            }
    


7. run
Code:
> composer require myth/auth


8. Edit app/Config/Email.php and verify that a fromName and fromEmail are set as that is used when sending emails for password reset, etc.

9. Edit app/Config/Validation.php and add the following value to the ruleSets array: \Myth\Auth\Authentication\Passwords\ValidationRules::class

10. Ensure your database is setup correctly, then run the Auth migrations:
Code:
php spark migrate -all


11. As a result you will also have the above error. I was not able to
    get around that error, except for the system in was working with at
    first.

12. If you just use 
Code:
php spark migrate
it will migrate the sample migartion without any errors.


I was NOT able NOT to reproduce the error on three different machines, on the other hand, i was not able to reproduce the error in the PC i used first during the last couple of weeks.

Need help understanding the docs on RESTFul?

$
0
0
I'm trying to get my head around the RESTFul part of the docs. But is confused as to where the individual parts go ...

It starts of by giving this example for setting basic routes:
Code:
$routes->resource('photos');

Now, where does this go? In the \App\Config\Routes.php file, or maybe in the (resource)controller itself? Please be specific. If it's the case it has to go into the Routes.php file, then this leads me to my next question ... does this 'port' well? If I have to scatter specific elements for specific controllers a bit here and a bit there, I guess it becomes 'unmanageable' in the long term and especially if an application becomes ever so slightly complex.

Wouldn't we need a way of somehow 'grouping' these things into a single place (thinking module here) somehow? So that, if moving 'modules' between applications we wouldn't have to 'remember' where we put all these little but VERY IMPORTANT pieces (like routes for the controller in the routes config file ... )?

Maybe I'm just not getting it, or seeing to many problems down the road. Maybe someone could provide a COMPLETE example (a very basic one, though) of how to set this up, to have a fully functioning RESTFul API – that is, the auto generated stuff?

Filter controller without authentication

$
0
0
i , in ci 3 in a construct method or in every method of a controller except for login i do :


PHP Code:
if(!isset($_SESSION['user_id'])) {
            
            redirect
('user/login','refresh');
            die();
        


How can i do the same using filter ?

Missing favicon.ico is blocked by CSP?

$
0
0
How do I get rid of this error:
Code:
Content Security Policy: The page’s settings blocked the loading of a resource at [url=http://localhost/favicon.ico]http://localhost/favicon.ico[/url] (“default-src”).

This is the browser defaulting to a favicon probably because I haven't set one specifically. But how do I get rid of this? I've tried looking into the CSP of CI4 but it makes no sense in this regard. The browser is asking for a 'default' (expected) favicon.ico which I don't want to provide ... how do I tell the browser to go f... itself (in a nice and polite way of course ;  ) )?

Where do I whitelist stuff for this?

CI3 with SQL server

$
0
0
Hello everyone,

I had a conexion to Sql server with the next configuration.

PHP Code:
$db['azure'] = array(
'dsn' => '',
'hostname' => 'bck-pro-sql.database.windows.net',
'username' => 'user',
'password' => 'pass',
'database' => 'CustomerServiceDB',
'dbdriver' => 'sqlsrv',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
); 


I already installed ODBC drive, sqlrv.dll for php 7.4 and modified php.ini. But I dont know why suddenly I got the next error

Unable to connect to your database server using the provided settings.
Filename: C:/xampp/htdocs/wke/system/database/DB_driver.php
Line Number: 436


It´s weird because sometimes its working normally and all of sudden crash with that error, If a restart xampp it works for some minutes.

Pls. can you help me with some advices

merci

using phpMyAdmin to create temp tables

$
0
0
I am planning on using phpMyAdmin to write stored procedures. What I am doing in the stored procedure is creating a temporary table  called "A" and then within my CI application I will access A and generate reports. The problem is 1) I don't know how to save the SP with phpMyAdmin and 2) how can I view the table that was created within phpMyAdmin? I don't see it as being added to the Tables in phpmyAdmin.

extend basic news tutorial

$
0
0
in https://codeigniter.com/user_guide/tutor...ction.html 

One of the views has this code : 
Code:
<p><a href="/news/<?= esc($news_item['slug'], 'url'); ?>">View article</a></p>

Now this works if you followed the tutorial to the letter; but if you had any other way... let's say the lazy WAMP way its a bit of a search to find what is going wrong; (the page links to a 404)

I'm assuming this is the correct way of doing things if you are not in the root directory;

Code:
<p><a href="<?php echo base_url('news/' . esc($news_item['slug'], 'url') ); ?>">View article</a></p>

Can I change this line in the documentation ? (or is this also not the correct way)

It would be great not to force people to only use spark, which is to my humble opinion is fun but not what people are going to use any time soon in production.

CURL and clearing query after send

$
0
0
Hi,

I'm using `curlrequest` but I found a problem. When we use a service `curlrequest` we could set an option for the client. For API which I'm trying to call auth is passed as a query params so I set options like this:

PHP Code:
        $client = \Config\Services::curlrequest([
            'baseURI' => 'API',
            'query' => [
                'key' => 'key',
                'token' => 'token'
            ]
        ]); 

and everything works ok for the first request but next don't get that `query` option because it's cleared in `system/HTTP/CURLRequest.php:429`. It's this part of code:

PHP Code:
    public function send(string $methodstring $url)
    {
        
// Reset our curl options so we're on a fresh slate.
        
$curl_options = [];

        if (! empty(
$this->config['query']) && is_array($this->config['query']))
        {
            
// This is likely too naive a solution.
            // Should look into handling when $url already
            // has query vars on it.
            
$url .= '?' http_build_query($this->config['query']);
            unset(
$this->config['query']);
        } 

and I'm not sure if it's proper behavior?

Printing Query error

$
0
0
IN CI 3 when there was sql error it prints the whole error query then we find out the error and resolve it but in CI4 only it saying the there was error on line X but did not print the whole query so that we could debug it.

How can CI 4 can print the whole error query ?
Please help.

Invalid serialization data for DateTime object

$
0
0
Hi,

I create an entity and cache it. When I try to get from cache it gives me error: "Invalid serialization data for DateTime object".

This is example code:

Code:
$web = new \App\Entities\Web();
$web->created_at = date('Y-m-d H:i:s');
$cache->save('webname', $web, 300);

$web = $cache->get('webname');
if ($web) {
    echo 'cached';
    printr($web);
}

Where is the problem? How can fix this?

Thank you,

Angel

Debugbar Error CI 4.0.4

$
0
0
I have finished installing CI4.0.4 through the appstarter with composer and everything was fine. but when I pass the project to development, the debugbar does not appear and I see an error in the browser console. Can someone help me how to solve this error and show the debug bar? 

GET http://localhost/appstarter/index.php?debugbar net::ERR_ABORTED 404 (Not Found)

attached screenshots

.png   Capture1.PNG (Size: 37.99 KB / Downloads: 1)

.png   Capture2.PNG (Size: 40.25 KB / Downloads: 2)

Tinymce 4.9.8 upload image

$
0
0
Hi guys,

I need some help, I have problem with Tinymce version 4.9.8 upload image. I follow from this official guide (https://www.tiny.cloud/docs-4x/general-c...agehandler)

This is my script from view
Code:
<?= script_tag('assets/tinymce/tinymce.min.js'); ?>
    <script>
      tinymce.init({
        selector: 'textarea#post_content',
        plugins: 'image code media',
        toolbar: 'undo redo | styleselect | bold italic underline | link image media | code',
        menubar: false,
        document_base_url: '<?= base_url() ?>',
        images_upload_handler: function (blobInfo, success, failure, progress) {
        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', '<?= base_url('admin/blog/imgUpload') ?>');

        xhr.upload.onprogress = function (e) {
          progress(e.loaded / e.total * 100);
        };

        xhr.onload = function() {
          var json;

          if (xhr.status < 200 || xhr.status >= 300) {
            failure('HTTP Error: ' + xhr.status);
            return;
          }
          // console.log(xhr.responseText);
          json = JSON.parse(xhr.responseText);
          // console.log(json.location);
          if (!json || typeof json.location != 'string') {
            failure('Invalid JSON: ' + xhr.responseText);
            return;
          }

          success(json.location);
        };

        xhr.onerror = function () {
          failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
        };

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
      }
      });
    </script>

2. Controller code:
PHP Code:
    public function blogImgUpload()
    {
        
        
            $accepted_origins 
= array('http://localhost:8080');
            $imageFolder "../public/blog_img/";

            reset ($_FILES);
            $temp current($_FILES);
            
            
if (is_uploaded_file($temp['tmp_name'])){
                if (isset($_SERVER['HTTP_ORIGIN'])) {
                    // same-origin requests won't set an origin. If the origin is set, it must be valid.
                    if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
                        header('Access-Control-Allow-Origin: ' $_SERVER['HTTP_ORIGIN']);
                    } else {
                        header("HTTP/1.1 403 Origin Denied");
                        return;
                    }
                }

                /*
                If your script needs to receive cookies, set images_upload_credentials : true in
                the configuration and enable the following two headers.
                */
                // header('Access-Control-Allow-Credentials: true');
                // header('P3P: CP="There is no P3P policy."');

                // Sanitize input
                if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/"$temp['name'])) {
                    header("HTTP/1.1 400 Invalid file name.");
                    return;
                }

                // Verify extension
                if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif""jpg""png"))) {
                    header("HTTP/1.1 400 Invalid extension.");
                    return;
                }

                // Accept upload if there was no origin, or if it is an accepted origin
                $filetowrite $imageFolder $temp['name'];
                move_uploaded_file($temp['tmp_name'], $filetowrite);

                // Respond to the successful upload with JSON.
                // Use a location key to specify the path to the saved image resource.
                // { location : '/your/uploaded/image/file'}
                // $img = [
                //     'location' => base_url('blog_img/') . $temp['name']
                // ];
                $img = [
                    'location' => $filetowrite
                
];
                // echo $this->response->setJSON($img);
                return json_encode($img);
            } else {
                // Notify editor that the upload failed
                header("HTTP/1.1 500 Server Error");
            }
        
Routes.php settings
PHP Code:
$routes->group('admin', function($routes){
    ...
    
$routes->add('blog/imgUpload''Admin\BlogManagement::blogImgUpload');
        ..
}); 

1) The file is successfully upload at `blog_img/` directory
2) I receive error in chrome console 
PHP Code:
Uncaught SyntaxErrorUnexpected token in JSON at position 43
    at JSON
.parse (<anonymous>)
    at XMLHttpRequest.xhr.onload (create:150
 
output/response from json_encode
Code:
{"location":"..\/public\/blog_img\/8.png"}

I hope someone can help me..

ubuntu sessions

$
0
0
Today I discovered something, that Ubuntu (and Debian) do their own PHP sessions garbage collection but that sessions not prefixed by 'sess_' are ignored. So the CI default session name of 'ci_session' never gets deleted, on my ubuntu 18.04 box they can be found in /var/lib/php/sessions. The script /usr/lib/php/sessionclean which run every half hour does the cleaning and it was in there that I saw the prefix requirement.

Show jasperreport using Codeigniter

$
0
0
Hi there Im newbie in codeigniter and I start with codeigniter 3.
I'm having trouble with a JASPER report to create one
I'm using this library https://github.com/SIMITGROUP/phpjasperxml
And a follow this tutorial how to include the library https://forum.codeigniter.com/thread-271...#pid170641
here my javascript file


Code:
  $.ajax({
            data: {
                'c_order_id': 101010,
            },
            url: "<?php echo base_url() ?>adempiere/c_order_report",
            type: 'POST',
            dataType: 'json',
            cache: false,
            success: function(response) {
                  window.open('<?php echo base_url() ?>adempiere/c_order_report', '_blank');
            },
          
here my controller function
Code:
public function c_order_report()
{
    $c_order_id = trim($this->input->post('c_order_id', true));
    $this->load->library('PHPJasperXML');
    $ruta = __DIR__ . '/example.jrxml';
    // echo $ruta;
    // $xml =simplexml_load_file($ruta);
    $PHPJasperXML = new PHPJasperXML("en","TCPDF");
    $PHPJasperXML->debugsql=true;
    $PHPJasperXML->arrayParameter = array('para1'=>'1','para2'=>'2');
    $PHPJasperXML->load_xml_file($ruta);
    $dbdriver="psql";

    $PHPJasperXML->transferDBtoArray('localhost','adempiere','adempiere','adempiere',$dbdriver);
    $PHPJasperXML->outpage('I'); 
in the developer option of the browser I get this. https://ibb.co/RhG0mmy

.png   Captura de pantalla de 2020-08-26 16-55-04.png (Size: 38.49 KB / Downloads: 0)

Dynamic $baseURL for multiple hosts

$
0
0
I am developing an app that will have multiple domains and subdomains pointed at it.  I would like to have CodeIgniter automatically detect the Base URL.

In Config/App.php it says this:

PHP Code:
    /*
    |--------------------------------------------------------------------------
    | Base Site URL
    |--------------------------------------------------------------------------
    |
    | URL to your CodeIgniter root. Typically this will be your base URL,
    | WITH a trailing slash:
    |
    |    http://example.com/
    |
    | If this is not set then CodeIgniter will try guess the protocol, domain
    | and path to your installation. However, you should always configure this
    | explicitly and never rely on auto-guessing, especially in production
    | environments.
    |
    */ 

I also have this line commented out in my .env file:
Code:
# app.baseURL = ''


I am receiving this error:

You have an empty or invalid base URL. The baseURL value must be set in Config\App.php, or through the .env file.

How can I dynamically set the Base Site URL to use for multiple sites pointing to the app?

CI4 filter before RequestInterface

$
0
0
Hi,

I'm new in CodeIgniter 4. Is it possible to SANITIZE all request variables before using it in controller? 

number_only = '123abc456';
Code:
<?php namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class SanitizeFields implements FilterInterface
{

    protected $session;

    public function before(RequestInterface $request, $arguments = null)
    {
         $request->getVar('number_only', FILTER_SANITIZE_NUMBER_INT);
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}
Code:
<?php
//controller
public function getData()
{
    echo $this->request->getVar('number_only');
}


I don't know if it is possible to output the data in controller with the sanitize number_only variable.
Output: 123456

Thanks!

Simple wwy to generate fake data in controller

$
0
0
I have read tje docs on generating test data.But the problem is it seems to only focus on generating test data from models and for database seeding

How can I generate fake data independent of a model or database in CI4 in a normal CI4 controller
Probably using the Faker class?
Viewing all 14231 articles
Browse latest View live


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