...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
January 3, 2012

How to get Controller, Action, URL informations with CodeIgniter

Question by noname.cs

I have these urls:

How to get controller name, action name from these urls. I’m codeigniter newbie. Are there any helper function to get this info

Ex:

$params = helper_function( current_url() )

Where $params becomes something like

array (
  'controller' => 'system/settings', 
  'action' => 'edit', 
  '...'=>'...'
)

Answer by Jonathan Sampson

You could use the URI Class:

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

I’ve also been told that the following work, but am currently unable to test:

$this->router->fetch_class();
$this->router->fetch_method();

Answer by Starx

As an addition

$this -> router -> fetch_module(); //Module Name if you are using HMVC Component
Read more
January 2, 2012

"var_dump" functions

Question by Joseph the Dreamer

by the function name itself, var_dump() dumps everything about a provided parameter EXCEPT the functions of an object.

is there a way of dumping out these functions?

Answer by zerkms

You cannot get the object’s methods, but you can get the class methods:

var_dump(get_class_methods('classname'));

or

var_dump(get_class_methods(get_class($object)));

Answer by Starx

You can use ReflectionClass API too

An Example:

$cls = new ReflectionClass("classname");
var_dump($cls -> getMethods());
Read more
January 1, 2012

Set php session via ajax

Question by ShadowBroker

I’m trying to build my ajax login system but i’m having some problems with php sessions.

This is the ajax code i use in my index.php:

    $("#buttonLogin").click(function(){
        $.post("<?php echo $AJAX ?>/ajaxLogin.php",{
            Username : $("#loginUsername").val(),
            Password : $("#loginPassword").val()
        }, 
        function(result){
            if(result == "OK"){
                window.location.href = "<?php echo $PUBLIC?>/home.php";
            } else {
                $("#loginMessageError").show();
            }
        });
    });

And this is the ajaxLogin.php that is called via ajax

<?php
require_once("../settings.php");
require_once($ABS_ENGINE."/classUser.php");

$user = new User();
if($user->loginUser($_POST["Username"], $_POST["Password"])){
    $UserID = $user->getUserId($_POST["Username"]);
    session_start();
    $_SESSION['UserID'] = $UserID;
    echo "OK";
} else {
    echo "ERROR";
}
?>

When i’m in home.php and i try to echo $_SESSION[“UserID”] i get the following error:

Notice: Undefined index: UserID in C:xampphtdocswebnameresourcestemplatesheaderHome.php on line 23

Probably this is not correct because session must be set before any output but if i try to echo $_SESSION['UserID'] = $UserID; line it’s session variable is correctly displayed.

Answer by Starx

Better check if session_start() is present in home.php. Without this you will not be able to read the session data.

When you are doing echo $_SESSION['UserID'] = $UserID; you will assigning and accessing at a same line, so it will obviously work.

Read more

How to skip links containing file extensions while web scraping using PHP

Question by Spoilt

Here is a function that validates .edu TLD and checks that the url does not point to a .pdf document or a .doc document.

public function validateEduDomain($url) {
    if( preg_match('/^https?://[A-Za-z]+[A-Za-z0-9.-]+.edu/i', $url) && !preg_match('/.(pdf)|(doc)$/i', $url) )  {
        return TRUE;
    }
    return FALSE;

Now I am encountering links that point to jpg, rtf and others that simple_html_dom tries to parse and return its content. I want to avoid this happening by skipping all such links. The problem is that the list is non-exhaustive and I want the code to skip all such links. How am I supposed to do that??

Answer by Maerlyn

Tring to filter urls by guessing what’s behind it will always fail in a number of cases. Assuming you are using curl to download, you should check if the response document-type header is among the acceptable ones:

<?php

require "simple_html_dom.php";

$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //default is to output it

$urls = array(
  "google.com", 
  "https://www.google.com/logos/2012/newyearsday-2012-hp.jpg", 
  "http://cran.r-project.org/doc/manuals/R-intro.pdf",
);
$acceptable_types = array("text/html", "application/xhtml+xml");

foreach ($urls as $url) {
  curl_setopt($curl, CURLOPT_URL, $url);
  $contents = curl_exec($curl);

  //we need to handle content-types like "text/html; charset=utf-8"
  list($response_type) = explode(";", curl_getinfo($curl, CURLINFO_CONTENT_TYPE));

  if (in_array($response_type, $acceptable_types)) {
    echo "accepting {$url}n";
    // create a simple_html_dom object from string
    $obj = str_get_html($contents);
  } else {
    echo "rejecting {$url} ({$response_type})n";
  }
}

running the above results in:

accepting google.com
rejecting https://www.google.com/logos/2012/newyearsday-2012-hp.jpg (image/jpeg)
rejecting http://cran.r-project.org/doc/manuals/R-intro.pdf (application/pdf)

Answer by Starx

Update the last regex to something like this

!preg_match('/.(pdf)|(doc)|(jpg)|(rtf)$/i', $url) )

will filter out the jpgs and rtf documents.

You have to add the extensions to the regex above to omit them..

Update

I dont think its possible to block all sort of extensions and i personally do not recommend it for scraping usage also. You will have to skip some extensions to keep crawling.. why dont you change you regex filter to the ones you would like to accept like

preg_match('/.(html)|(html)|(php)|(aspx)$/i', $url) )
Read more

How to make 2 level scrolling tab in CSS like this in HTML 5

Question by Jitendra Vyas

I need to make tabs like this which is having horizontal scroll and I’m using HTML 5 figure and figure caption

HTML example

<div class="footernav">
  <a href="javascript:void(0)">
    <figure> <img src="http://lorempixel.com/200/200/fashion/" class="fluid">
        <figcaption>
                <h3>Product Name</h3>
        </figcaption>
    </figure>
  </a>
</div>

CSS

.footernav {white-space;no-wrap; padding-top: 0.2%; border-top: 1px solid white; overflow: auto; white-space:nowrap; padding-bottom: 1.9%;}
.footernav a { text-decoration: none; font-weight: bold; display: inline-block; padding-right: 1.5%; padding-left: 1.5%; text-align: center; margin-top: 1.1em; overflow:hidden; }
.footernav figure:last-child { margin-right: 0; }
.footernav img { min-width: 118px; max-width: 118px; padding:3px;  }
figure{margin:0}
.footernav a:hover,
.footernav a.selected { border-top-left-radius: 15px;
border-top-right-radius: 15px; background:red}
.footernav h3 { color: #000; font-weight: 700; margin-top: 0; margin-bottom: 0.3em; font-size: 1.1em; text-transform: uppercase; margin-top:0.5em }

see here http://jsfiddle.net/jitendravyas/XnAsL/1/ (Link updated)

Now how to 2nd level and make it like the below picture?

Both level should scroll.

enter image description here

Answer by Starx

I just used a simplest logic i could think of.

Check the update of your fiddle here.

I just copied your div, gave them a common class to denote as sub item. Then used a rel attribute on the original link to show those boxes.

$(".link").click(function() {
    var rel = $(this).attr('rel');
    $(".subtabs").hide();
    $("#"+rel).show();
});

Update:

Since you want a CSS solution, in order to denote sub items the best(or only) way is too nest them inside. But your current markup pattern, will not allow it. as an inline element will contain a block element. Although this will be valid under HTML5 (which of course is still in experimental phase), does not render as expected (in fact the div will pop right out of the tag). So you have to change the markup style to something fit.

As per our discussion, this fiddle does what is needed.

Update II

Since you said, scripting will be done by someone else. A simple snippet will get the job the job done. A particular row will be selected and will remained selected when the user clicks it… You can check the fiddle of this here

$(".footernav > li").click(function() {
    $(this).toggleClass("selected");
});


P.S.
Second row positioning is not working properly inside the fiddle’s box. So you might have test in a seperate page.

Read more

Validating with php

Question by Jeff Davidson

I’m trying to validate my user server side with php and its saying I’m getting an Fatal error: Call to undefined function reGenPassHash() in /home/xtremer/public_html/kowmanager/application/models/loggedin.php on line 13 now I have the model that includes the reGenPassHash function auto loaded so I thought it’d be available to use but for some reason its not because of this message. Someone explain why?

Model:

public function check_login($username, $password)
{
    $generated_password = reGenPassHash($password);
    $query = "SELECT user_id WHERE username = ? AND password = ?";
    $result = $this->db->query($query, array($username, $generated_password));

    if ($result->num_rows == 1)
    {
        return $result->row(0)->user_id;

    }
    else
    {
        return false;
    }

}

Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Usermanagement extends CI_Controller { 

public function __construct()
{
    parent::__construct();
}   

public function index()
{
    //Config Defaults Start
    $msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
    $cssPageAddons = '';//If you have extra CSS for this view append it here
    $jsPageAddons = '';//If you have extra JS for this view append it here
    $metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
    $siteTitle = '';//alter only if you need something other than the default for this view.
    //Config Defaults Start


    //examples of how to use the message box system (css not included).
    //$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');

    /**********************************************************Your Coding Logic Here, Start*/

    if(!$this->session->userdata('logged_in'))
    {
        $bodyContent = "login";//which view file
    }
    else
    {
        $bodyContent = "cpanel/index";//which view file
    }

    $bodyType = "full";//type of template

    /***********************************************************Your Coding Logic Here, End*/

    //Double checks if any default variables have been changed, Start.
    //If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.      
    if(count($msgBoxMsgs) !== 0)
    {
        $msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
    }
    else
    {
        $msgBoxes = array('display' => 'none');
    }

    if($siteTitle == '')
    {
        $siteTitle = $this->metatags->SiteTitle(); //reads 
    }

    //Double checks if any default variables have been changed, End.

    $this->data['msgBoxes'] = $msgBoxes;
    $this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
    $this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
    $this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
    $this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
    $this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
    $this->data['bodyType'] = $bodyType;
    $this->data['bodyContent'] = $bodyContent;
    $this->load->view('usermanagement/index', $this->data);
}

function login()
{
    $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[50]|xss_clean');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|max_length[12]|xss_clean');

    if ($this->form_validation->run() == FALSE)
    {
        $this->index();
    }
    else
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $user_id = $this->loggedin->check_login($username, $password);

        if(! $user_id)
        {
           redirect('/'); 
        }
        else
        {
            $this->session->set_userdata(array(
                'logged_in' => TRUE,
                'user_id' => $user_id
            ));
            redirect('cpanel/index');
        }
    }
}

function logout()
{
   $this->session->sess_destroy();
   $this->index();
}       

}

/* End of file usermanagement.php */ 
/* Location: ./application/controllers/usermanagement.php */ 

EDIT :

I’m trying to make sure my logic is correct. Should I be working with the regenPassHash function call in my controller instead?

EDIT 2 :

This is an example of how my password functions look (getfunc model):

<?php
function GenPassHash($logPass)
{
    $usersalt = substr(md5(uniqid(rand(), true)), 0, 11);
    $encPass = sha1($logPass);
    $sltPass = $encPass . $usersalt;$encSPass = sha1($sltPass);
    $passArray = array($encSPass,$usersalt);
    return $passArray;
}
function reGenPassHash($postDpass, $storeSalt)
{
    $logPass = $postDpass;
    $encPass = sha1($logPass);
    $sltPass = $encPass . $storeSalt;
    $encSPass = sha1($sltPass);
    return $encSPass;
}

//useage
$logPass = "catcher05";//this could be your posted variable from registration

$passforDB = GenPassHash($logPass);
echo "<pre>";
print_r($passforDB);
echo "</pre>";
echo "Encrypted Password: " . $passforDB[0] . "<br />";
echo "Salted Value: " . $passforDB[1] . "<br />";

echo "----------------------------------<br />";
//in this example I post $passforDB[1] with the below function to stimulate having pulled it from a DB
echo reGenPassHash($logPass, $passforDB[1]); //you would query based on your username being posted and only pull the salt and encrypted pass you would use the salt in this function

?>

Controller:

function login()
{
    $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[50]|xss_clean');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|max_length[12]|xss_clean');

    if ($this->form_validation->run() == FALSE)
    {
        $this->index();
    }
    else
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $generated_password = $this->getfunc->reGenPassHash($password);

        $user_id = $this->loggedin->check_login($username, $password);

        if(! $user_id)
        {
           redirect('/'); 
        }
        else
        {
            $this->session->set_userdata(array(
                'logged_in' => TRUE,
                'user_id' => $user_id
            ));
            redirect('cpanel/index');
        }
    }
}

Model:

public function check_login($username, $password)
{
$query = "SELECT * WHERE username = ".$username."";
$result = $this->db->query($query);

if ($result->num_rows == 1)
{
    $passwordDB = $result->row(0)->password;
    $passwordDB2 = $result->row(0)->password2;


    return $result->row(0)->user_id;

}
else
{
    return false;
}

}

Answer by Starx

The only error i saw with your code, is that you are calling your method the wrong way. For any class method, you need a objects to access the methods.

This might $this. in your case or something else in other cases.

Try using $this -> reGenPassHash() to call the method only if it relies with in the model, or you will need respective object modifier.

UPDATE:

  1. Include your GenPassHash() & reGenPassHash() on your controller.
  2. Instead of $this->getfunc->reGenPassHash() use $this->reGenPassHash()
Read more

How to make Table Joins in PHPmyAdmin

Question by Mark

I have 2 Tables in phpmyadmin that need joining

tracklisting is my one and catelogue is the other, and are saved as innodb

They both have a column CAT.NO and would like it to be joined on this column. In catelogue it is the primary and in tracklisting it’s indexed

catelogue is my parent and tracklisting would be the child as it doesn’t have info for every record in catelogue. I believe this would be correct unless I’m wrong

How do I do this so that when I query on a column in tracklisting it only brings up the matches for ‘catelogue’ because I want to know what album it’s on and not my entire 60000+ catelogue

Can this be done with phpmyadmin’s interface or is this a sql statement

Many thanks

EDIT:

This was the code that worked

SELECT *
FROM tracklisting
INNER JOIN catelogue ON catelogue.`CAT NO.` = tracklisting.`TRACKLISTING CAT NO.`
WHERE tracklisting.`ARTIST` LIKE 'placebo'

Thanks to everyone that helped out

Answer by Starx

I dont know if this can be done with the interface, but with sql

SELECT * 
FROM 
  tracklisting t 
  INNER JOIN catelouge c on c.catno=t.catno 
WHERE t.id = 1
Read more

How to use the float:left property in CSS without having the trouble I have?

Question by Prateek

i’m trying to create a flow layout and i’m having some trouble using float:left property in css.

I have one parent container which has 100% width and 100% height. It contains three containers:
The header, the menu container, and the content container.
The menu is a vertical menu,not a horizontal menu. It comes below the header and then the content container floats left on the menu container.
Now the problem is i want to make it flowlayout. When i reduce the resolution,the floating content container comes below the menu container. I want the content to float with a flowlayout without coming below the menu container.Please provide a solution to this.
Thanks!

Here is the link to the code.

http://jsfiddle.net/VdE7Y/

Answer by Scott

Remove the width and float from the #content css.

Set the background color of #wrapper to be whatever color you want the background of #content to be.

add display: inline-block; to the #content css.

Updated fiddle —-> HERE

Answer by Starx

The problem is the min-width you have for #menu-cont

The layout you are trying to have is very hard to maintain.

Read more
December 30, 2011

Sending a get variable to php file through getJSON?

Question by holyredbeard

Is it possible to send a parameter (eg. a get variable) with getJSON to a php file, and if so how to do it?

The code below doesn’t work, but hopefully it shows what I try to accomplish.

var url = "http://www.address.com/"

$.getJSON('http://anotheraddress.com/messages.php?url=+escape(url))', function(data) {
    // code here
});

Answer by James Thorpe

$.getJSON accepts another parameter for data:

var url = "http://www.address.com/"

$.getJSON('http://anotheraddress.com/messages.php', { url: escape(url) }, function(data) {
    // code here
});

Answer by Starx

Your jquery might look something like this

$.getJSON("messages.php", 
{
   data1: value1,
   data2: value2,
   url: escape(url)
},
function(data) { 
    alert(data.yourval);
});

The only thing you should remember while using getJSON is that, the php page message.php should return JSON string as a response. SO you have do something like this at the end of the file.

echo json_encode($responseArray);
// Remember not to echo or output anything or the JQuery will not execute

Read more
...

Please fill the form - I will response as fast as I can!