php gettype fix - php

Following function I created is to store data in a database with the correct type.
I have several questions:
It makes sense to me to turn empty strings in to NULL. Are there consequences I am not considering?
What is a good max_length value for sqlite3 text. I know blob and text length constrains are the same, but are there any other considerations like displaying the data in a shell, etc.
Is there a simple way to check if data is an image, and what type, since mime is not available at this stage?
Does something stick out that I am missing?
public static function getType($value, $max_length = 50){
$type = gettype($value);
if($type == 'NULL'
|| $type == 'boolean'
|| $type == 'integer'
|| $type == 'double'
|| $type == 'object'
|| $type == 'resource'
|| $type == 'array'
)
return array('type'=>$type,'value'=>$value);
if($type == 'string' && empty($value))
return array('type'=>'NULL','value'=>$value);
if($type == 'string' && strlen($value) > $max_length)
return array('type'=>'blob','value'=>$value);
if($type == 'string' && substr($value, 0,1) === '0')
return array('type'=>'string','value'=>$value);
if($type == 'string' && is_numeric($value)){
$int = (int) $value;
$float = (float) $value;
if($int == $value){
$value = $int;
$type = 'integer';
}elseif($float == $value){
$value = $float;
$type = 'double';
}
}elseif($type == 'string'){
return array('type'=>$type,'value'=>$value);
}else{
$type = 'blob';
}
return array('type'=>$type,'value'=>$value);
}

Related

Solution for eval

I am doing custom search for table. I have three search parameters: from, to and status. I have used eval() to filter result according to received parameter. Below is my code:
$search = ($from != "" || $to != "" || $status != "" );
if ($search) {
if ($from != '') {
$condition[] = '$from == $res["from_number"]';
}
if ($to != '') {
$condition[] = '$to == $res["to_number"]';
}
if ($status != '') {
$condition[] = '$status == $log["status"]';
}
$search = "if(" . implode(' && ', $condition) . '){ return false; } else { return true; }';
}
After getting the conditions I am using eval
if (eval($search)) {
}
My problem is I don't want to use eval(). It may cause security issues. Ladder if else is not possible, it would be very lengthy. Any other solution?
e.g. If i have passed value for status then i want check like
if($status == $log["status"]) {
}
if i have passed to & from number then it should be like:
if($from == $res["from_number"] && $to == $res["to_number"]) {
}
Don't use eval - it is potentially dangerous and not recommended to use.
Your code can be like this:
$result = false;
if ($from != "" || $to != "" || $status != "") {
if ($from != '' && $from != $res["from_number"]) $result = true;
if ($to != '' && $to != $res["to_number"]) $result = true;
if ($status != '' && $status != $log["status"]) $result = true;
}
if ($result) {
// ........
}

Function always returning true no matter input

I trying to create a function that matches the first number in a string to a state. For example if the user inputs a number that starts with 3, and the state 'vic', then the form should not present any errors. However no matter what is entered the function always returns true. Any help would be appreciated.
$state = array('Please Select', 'VIC', 'NSW', 'QLD', 'NT', 'WA', 'SA', 'TAS', 'ACT'); //In the form this is a drop down menu
$selected_key = $_POST['state'];
$postcode = $_POST["postcode"]; //The full number entered by the user
$errMsg .= validatePS($postcode, $selected_key);
function validatePS($ps, $state) {
$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;
if (($digit == 3) or ($digit == 8) && ($state == 'vic'))
{
$post = true;
}
if (($digit == 1) or ($digit == 2) && ($state == 'nsw'))
{
$post = true;
}
if (($digit == 4) or ($digit == 9) && ($state == 'qld'))
{
$post = true;
}
if ($valid == false) {
$errMsg .= "<p>Match the correct postcode to state</p>";
}
return $errMsg;
}
if ($errMsg !=""){
echo "<p>Please correct the following errors...</p>"; //Prints out errors
echo "<p>$errMsg</p>";
}
You have two "flag" variables - $post which you are updating and $valid which you rely on. If you reduce them to one variable, you should get the behavior you want:
function validatePS($ps, $state) {
$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;
if (($digit == 3) or ($digit == 8) && ($state == 'vic'))
{
$valid = true;
}
if (($digit == 1) or ($digit == 2) && ($state == 'nsw'))
{
$valid = true;
}
if (($digit == 4) or ($digit == 9) && ($state == 'qld'))
{
$valid = true;
}
if ($valid == false) {
$errMsg .= "<p>Match the correct postcode to state</p>";
}
return $errMsg;
}
Note that you could clean up this code considerably by using logical operators instead of multiple if statements:
function validatePS($ps, $state) {
$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;
if ((($digit == 3) or ($digit == 8) && ($state == 'vic')) ||
(($digit == 1) or ($digit == 2) && ($state == 'nsw')) ||
(($digit == 4) or ($digit == 9) && ($state == 'qld'))) {
$errMsg .= "<p>Match the correct postcode to state</p>";
}
return $errMsg;
}

Session Userdata Type not works in particular function in Codeigniter

I use this code in home function it get the usertype and works nice.
function home()
{
$type = $this->session->userdata('type');
if($type == "admin")
{
$this->load->view('index');
}
else if($type == "QA" || "SC" || "CDC")
{
$this->load->view('aindex');
}
}
But when I use same code in jobsheet function it's not working. Code below
function jobsheet()
{
$type = $this->session->userdata('type');
$this->load->model('Ipss_model');
$var1['job'] = $this->Ipss_model->AllJobSheet();
$var2['division'] = $this->Ipss_model->AllDivision();
$var3['tItem'] = $this->Ipss_model->transactionItem();
$data = $var1 + $var2 + $var3;
if($data['job'] != NULL )
{
if($type == "SC" || "CDC")
{
$this->load->view('jobsheet',$data);
}
else if($type == "admin" || "QA" )
{
$this->load->view('jobsheetQA',$data);
}
}
else
{
$this->load->view('jobsheetEmpty',$data);
}
}
Please help me about this. Thanks in advance.
To check weather array is empty or not you can use empty(). Also change your || condition like below.
So you condition would be
if(!empty($data))
{
if($type == "SC" || $type =="CDC")
{
$this->load->view('jobsheet',$data);
}
else if($type == "admin" || $type == "QA" )
{
$this->load->view('jobsheetQA',$data);
}
}
check your array() before using it in if condition
with -:
echo "<pre>";
print_r($data);
die();

Clean Conditional Code

i have this variable.
$productId = 2; // Testing ID
$value->id; // Contains INT
$value->datePurchaseEnd; // Contains UNIXTIME or NULL
The conditional i want to make.
if ($value->id == $productId) return true;
but if $value->datePurchaseEnd; is not NULL then also compare it with current time and it must bigger than current time to return TRUE;
For now this is the code i made:
if( $value->id == $productId){
if( $value->datePurchaseEnd == NULL ){
$return = TRUE; break;
}else{
if( $value->datePurchaseEnd > mktime() ){
$return = TRUE; break;
}
}
}
But i feel this code is not good.
Is there any suggestion to make better code with conditional above?
I would say either
if( ($value->id == $productId) && ($value->datePurchaseEnd == NULL || $value->datePurchaseEnd > mktime() )) {
$return = true;
break;
}
or
if($value->id == $productId) {
if($value->datePurchaseEnd == NULL || $value->datePurchaseEnd > mktime()) {
$return = true;
break;
}
}
Depends on if the conditions need an else
if( $value->id == $productId){
$return = ($value->datePurchaseEnd == NULL || $value->datePurchaseEnd > mktime());
break;
}
or
$return = $value->id == $productId && ($value->datePurchaseEnd == NULL || $value->datePurchaseEnd > mktime());
break;
If your code is not in a loop, I do prefer the inline conditional:
return $value->id == $productId && ($value->datePurchaseEnd == null || $value->datePurchaseEnd > mktime())

Need help converting a snippet of code from PHP to Javascript

below is a snippet of code that I started with... then I made some changes based on the commented suggestion from stackoverflow user. (Please see below for my progress so far)
ORIGINAL
$valid = true;
// basic validation
$phoneNumber = str_replace( ' ', '', $phoneNumber );
if ( strlen( $phoneNumber ) < 10 || !is_numeric( $phoneNumber ) ) {
$valid = false;
}
$areaCode = substr($phoneNumber, 0, 3);
$prefix = substr($phoneNumber, 3, 3);
$mainPhone = substr($phoneNumber, 3, 7);
// perform the same regex matching:
if ($valid) {
$regex = '/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/';
$valid = preg_match($regex, $areaCode);
}
if ($valid) {
$regex = '/^(?!\d[1]{2}|[5]{3})([2-9]\d{2})([. -]*)\d{4}$/';
$valid = preg_match($regex, $mainPhone);
}
// perform the original web validation:
if ( $valid ) {
// validate area code
if (
$areaCode == '000' ||
$areaCode == '111' ||
$areaCode == '222' ||
$areaCode == '333' ||
$areaCode == '444' ||
$areaCode == '555' ||
$areaCode == '666' ||
$areaCode == '777' ||
$areaCode == '999' ||
$areaCode == '123' || (is_string($areaCode) && !is_numeric($areaCode))) {
$valid = false;
}
}
if ( $valid ) {
// validate prefix
if ( $prefix == '123' ||
$prefix == '000' ||
$prefix == '111' ||
$prefix == '555' || (is_string($prefix) && !is_numeric($prefix))) {
$valid = false;
}
}
if ( $valid ) {
// validate main phone number
if ( $mainPhone == '2222222' ||
$mainPhone == '3333333' ||
$mainPhone == '4444444' ||
$mainPhone == '6666666' ||
$mainPhone == '7777777' ||
$mainPhone == '8888888' ||
$mainPhone == '9999999' || (is_string($phoneNumber) && !is_numeric($phoneNumber))) {
$valid = false;
}
}
return $valid;
NEW JAVASCRIPT VERSION (SO FAR)
below is a snippet of code that I am converting so far... I still have some PHP stuff in there can you guys help me out to remove/replace what this snippet needs to say to make it work?
function is_numeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function phonenumberIsValid(phonenumber)
{
var valid = true;
// basic validation
var phonetest = phonenumber.replace(' ','');
if ( strlen( phonetest ) < 10 || !is_numeric( phonetest ) ) {
valid = false;
}
var areaCode = phonetest.substr(0,3);
var prefix = phonetest.substr(3,3);
var mainPhone = phonetest.substr(3,7);
// perform the same regex matching that LeadMaster does:
if(valid){
valid = areaCode.match('/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/');
}
if(valid){
valid = mainPhone.match('/^(?!\d[1]{2}|[5]{3})([2-9]\d{2})([. -]*)\d{4}$/');
}
// perform the original web validation:
if(valid){
// validate area code
if (
areaCode == '000' ||
areaCode == '111' ||
areaCode == '222' ||
areaCode == '333' ||
areaCode == '444' ||
areaCode == '555' ||
areaCode == '666' ||
areaCode == '777' ||
areaCode == '999' ||
areaCode == '123' || (!is_numeric(areaCode)) {
valid = false;
}
}
if(valid) {
// validate prefix
if ( prefix == '123' ||
prefix == '000' ||
prefix == '111' ||
prefix == '555' || (!is_numeric(prefix)) {
valid = false;
}
}
if(valid) {
// validate main phone number
if ( mainPhone == '2222222' ||
mainPhone == '3333333' ||
mainPhone == '4444444' ||
mainPhone == '6666666' ||
mainPhone == '7777777' ||
mainPhone == '8888888' ||
mainPhone == '9999999' || (!is_numeric(phoneNumber)) {
valid = false;
}
}
return valid;
}
PregMatch can be replaced with "myString".match so for instance.
if ($valid) {
$regex = '/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/';
$valid = preg_match($regex, $areaCode);
}
would become
if(valid){
valid = areaCode.match('/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))/');
}
and
str_replace("search","replace",$myString)
becomes
myString.replace("search","replace")
In fact most of this can be worked out yourself by typing things like "str_replace javascript" into google and looking for the previous stack overflow answer :)

Categories