Stack of codes.
Please comment below your opinion. We will try to improve and bring more accurate contents for you.

Tuesday, 27 February 2018

Download File in php function. Force Download

Download File using php function. Force Download.
Here, $filepath = File Full path, where the file exists.

$filename = File name of the file , which have to download ,LIKE: file1.txt
header('Content-Description: File Transfer');

header('Content-Type: application/force-download');

header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");

header('Content-Transfer-Encoding: binary');

header('Expires: 0');

header('Cache-Control: must-revalidate');

header('Pragma: public');

header('Content-Length: ' . filesize($filename));

ob_clean();

flush();

//showing the path to the server where the file is to be download

readfile($filepath . $filename); 

exit;

How to protect and hide PHP source code?

How to protect and hide PHP source code?

In the time of open-source there are multiple benefits of making your code available to all. However when deploying or selling your PHP code to a client you might want to protect and hide it because of different business reasons or security.
There are multiple approaches to check based on the use cases:
  • Obfuscation – makes code difficult to read by a human in order to hide its logic or purpose. In most cases the reverse-engineering of such code is still possible so obfuscation doesn’t provide proper code protection if you need it.
  • SaaS – Software as a service is code licensing approach where the code is accessed from a server based on licenses and subscriptions to enabled users. Consider this kind of way if you want to make sure that the code is not available to end-users or that it is used only on request.
  • License agreements and contracts are the usual approach to make agreements between coders with clients.
For more .. 

Monday, 26 February 2018

on every third block ul tag will close and new tag open in php

on every third block ul tag will close and new tag open in php::

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
  <h2>Basic List Group</h2>
<?php 
$products = array(1,2,3,4,5,6,7,8,9,10);
?>
<?php foreach ($products as $key => $prod) { ?>
<?php if( ($key+1)==1 || (($key+1)%3)==1 ) { ?>
<ul class="list-group">
<?php } ?>
<li class="list-group-item">First item</li>
<?php if( (($key+1)%3)==0 ){ ?>
</ul>
<?php } ?>
<?php } ?>
</div>
</body>
</html>

Saturday, 24 February 2018

Change Server url dynamically for xampp or LIVE server in php


Here, whitelist array contains all the ip address that we uses for xampp or Local server.



All all local ip address in the whitelist array and filter easily which is for local and which is for LIVE server url.




<?php 

$whitelist = array( '127.0.0.1', '::1', '192.168.2.10' );

if(in_array( $_SERVER['REMOTE_ADDR'], $whitelist)){

    $serverHost = 'http://'.$_SERVER['HTTP_HOST'].'/mentor/';

}else{

    $serverHost = 'http://'.$_SERVER['HTTP_HOST'].'/';

}


$PATH = $serverHost."abcsite/assets/";

?>

Codeigniter 3.1.6 HMVC Download

You can download the HMVC structure of Codeigniter 3.1.6 HMVC .
For Download Click Here...

CodeIgniter-HMVC-3.1.6

Server Requirements For Codeigniter 3.1.6

Server Requirements

PHP version 5.6 or newer is recommended.
It should work on 5.3.7 as well, but we strongly advise you NOT to run such old versions of PHP, because of potential security and performance issues, as well as missing features.
A database is required for most web application programming. Currently supported databases are:
  • MySQL (5.1+) via the mysql (deprecated), mysqli and pdo drivers
  • Oracle via the oci8 and pdo drivers
  • PostgreSQL via the postgre and pdo drivers
  • MS SQL via the mssqlsqlsrv (version 2005 and above only) and pdo drivers
  • SQLite via the sqlite (version 2), sqlite3 (version 3) and pdo drivers
  • CUBRID via the cubrid and pdo drivers
  • Interbase/Firebird via the ibase and pdo drivers
  • ODBC via the odbc and pdo drivers (you should know that ODBC is actually an abstraction layer)

Monday, 19 February 2018

17 useful functions for manipulating arrays in PHP

17 useful functions for manipulating arrays in PHP::


FunctionExplanationExample
sizeof($arr)
This function returns the number of elements in an array.
Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array.
Code:
$data = array("red", "green", "blue");

echo "Array has " . sizeof($data) . " elements";
?>

Output:
Array has 3 elements
array_values($arr)
This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.
Use this function to retrieve all the values from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>

Output:
Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr)
This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.
Use this function to retrieve all the keys from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>

Output:
Array
(
[0] => hero
[1] => villain
)
array_pop($arr)
This function removes an element from the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val)
This function adds an element to the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr)
This function removes an element from the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>

Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val)
This function adds an element to the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>

Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr)
This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
while (list($key, $value) = each($data)) {
echo "$key: $value \n";
}
?>

Output:
hero: Holmes
villain: Moriarty
sort($arr)
This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.
Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
Code:
$data = array("g", "t", "a", "s");
sort($data);
print_r($data);
?>

Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr)
The function exchanges the keys and values of a PHP associative array.
Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns.
Code:
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>

Output:
Array
(
[apple] => a
[ball] => b
)
array_reverse($arr)
The function reverses the order of elements in an array.
Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values.
Code:
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>

Output:
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr)
This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.
Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries.
Code:
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));
?>

Output:
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr)
This function selects one or more random elements from an array.
Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list.
Code:
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>

Output:
Today's color is red
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.
Use this function to scan a set of index-value pairs for matches, and return the matching index.
Code:
$data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>

Output:
Found blue
array_slice($arr, $offset, $length)
This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.
Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data.
Code:
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>

Output:
Array
(
[0] => strawberry
[1] => mango
)
array_unique($data)
This function strips an array of duplicate values.
Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key.
Code:
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>

Output:
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
array_walk($arr, $func)
This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.
Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%.
Code:
function reduceBy10(&$val, $key) {
$val -= $val * 0.1;
}

$data = array(10,20,30,40);
array_walk($data, 'reduceBy10');
print_r($data);
?>

Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)

Saturday, 17 February 2018

On Click Copy the text in javascript

$(".copy-mediaUrl").on('click' , function(){
var b = $(this);
var media_id = 'mediaurl-'+ b.data('id');

var $temp = $("<input>");
$("body").append($temp);
$temp.val( $('#'+ media_id).text() ).select();
document.execCommand("copy");
$temp.remove();
alert('Image Link Copied!');
});

Copy Container Text in JavaScript

<script type="text/javascript">

function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();

  /* Copy the text inside the text field */
  document.execCommand("Copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
</script>

tinymce image path showing as ../../

Stack Of Codes: Get TinyMCE to use full image url instead of relat...: #Get TinyMCE to use full image url instead of relative one:: Make sure in the javascript initialization you are using, that you have...





relative_urls : false,
remove_script_host : false,
convert_urls : true,


LIKE::
<script>
tinymce.init({
selector: '.rte',
height: 500,
theme: 'modern',
plugins: [
'lists link image media',
'searchreplace visualblocks code fullscreen',
'insertdatetime table contextmenu paste',
'textcolor'
],
toolbar1: 'undo redo | styleselect | bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media',
image_advtab: true,
templates: [
{ title: 'Test template 1', content: 'Test 1' },
{ title: 'Test template 2', content: 'Test 2' }
],
content_css: [
],
relative_urls : false,
remove_script_host : false,
convert_urls : true,
});
</script>

Get TinyMCE to use full image url instead of relative one

#Get TinyMCE to use full image url instead of relative one::


Make sure in the javascript initialization you are using, that you have these lines in it:

relative_urls : false,
remove_script_host : false,
convert_urls : true,


LIKE::
<script>
tinymce.init({
selector: '.rte',
height: 500,
theme: 'modern',
plugins: [
'lists link image media',
'searchreplace visualblocks code fullscreen',
'insertdatetime table contextmenu paste',
'textcolor'
],
toolbar1: 'undo redo | styleselect | bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media',
image_advtab: true,
templates: [
{ title: 'Test template 1', content: 'Test 1' },
{ title: 'Test template 2', content: 'Test 2' }
],
content_css: [
],
relative_urls : false,
remove_script_host : false,
convert_urls : true,
});
</script>

Check whether server is http or https


# Check whether server is http or https
<?php
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
$uri = 'https://';
} else {
$uri = 'http://';
}
$uri .= $_SERVER['HTTP_HOST'];
echo $uri;
?>

How to delete a file in php

<?php
  $file_to_delete = $_GET['file'];
  if (is_file($file_to_delete)){
    echo (unlink($file_to_delete) ? "File Deleted" : "Problem deleting file";

  }
?>

Check when edit if the field is not duplicate Entry


Check when edit if the field is not duplicate Entry

if($this->input->post('user_name') != $original_value) {
   $is_unique =  '|is_unique[users.user_name]'
} else {
   $is_unique =  ''
}

$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean'.$is_unique);

Wednesday, 14 February 2018

Calculate Date Difference in php

#Date Difference 
$date_1 = '2018-02-16';
$date_1 = '2018-02-18';

$dateDifference = dateDifference($date_1, $date_2);
print_r($dateDifference);


function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);
    
    $interval = date_diff($datetime1, $datetime2);
    
    return $interval->format($differenceFormat);
    
}


//RESULT FORMAT:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds'        =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day'                                    =>  1 Year 3 Month 14 Days
// '%m Month %d Day'                                            =>  3 Month 14 Day
// '%d Day %h Hours'                                            =>  14 Day 11 Hours
// '%d Day'                                                        =>  14 Days
// '%h Hours %i Minute %s Seconds'                                =>  11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds'                                        =>  49 Minute 36 Seconds
// '%h Hours                                                    =>  11 Hours
// '%a Days                                                        =>  468 Days


Monday, 12 February 2018

Select all Checkbox in Javascript

Select all Checkbox in Javascript::


<script type="text/javascript">
$(document).ready(function(){
$("#checkbx_selectall").on('change', function() {
if(this.checked){
            $('.__chckbx_select').each(function(){
                this.checked=true;
            });
        }else{
             $('.__chckbx_select').each(function(){
                this.checked=false;
            });
        }
    });


    $('.__chckbx_select').on('change',function(){
        if($('.__chckbx_select:checked').length == $('.__chckbx_select').length){
            $('#checkbx_selectall').prop('checked',true);
        }else{
            $('#checkbx_selectall').prop('checked',false);
        }
    });
});
</script>

Convert stdClass object to array in PHP

Convert stdClass object to array in PHP
 
 
The easiest way is to JSON-encode your object and then decode it back to an array:
 
$array = json_decode(json_encode($object), True);
Or if you prefer, you can traverse the object manually, too:
 
foreach ($object as $value)
    $array[] = $value->post_id;

codeigniter $this->db->like is case sensitive

There is no case insensitive version of the like function. What you can do is transform both sides of the comparison to lower case, so that you take that out of the equation.

$this->db->like('LOWER(' .$field. ')', strtolower($value));

OR
$this->db->like('LOWER(field_name)', strtolower($value));

Sunday, 11 February 2018

Want to Disable Windows Update in PC ?

Want to Disable Windows Update in PC ?
Please Follow this instructions..
Press, start button + R
then, press ENTER
type: services.msc   &
then, Press ENTER.
Choose Windows Update,
right Click & Select properties,


Check window update option is disabled or not - stackofcodes.in


Here, Check is Windows Update Option is Disabled Or not?
If Disabled , then OK.
If Enabled, right click and choose Disable.
then Apply  & Ok.



Just Disable  as Above shown dropdown if It is enableed  - stackofcodes.in


codeigniter-file-upload-required-validation

We write for validation:: 

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

Now have to write like, :

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

HTML Input=“file” Accept Attribute File Type (CSV)

HTML Input=“file” Accept Attribute File Type (CSV)




<input id="fileSelect" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" /> 


# Selective File types to upload / chosen

Valid Accept Types:
For CSV files (.csv), use: 

<input type="file" accept=".csv" />
For Excel Files 97-2003 (.xls), use: 

<input type="file" accept="application/vnd.ms-excel" />
For Excel Files 2007+ (.xlsx), use: 

<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
For Text Files (.txt) use: 

<input type="file" accept="text/plain" />
For Image Files (.png/.jpg/etc), use: 

<input type="file" accept="image/*" />
For HTML Files (.htm,.html), use:

<input type="file" accept="text/html" />
For Video Files (.avi, .mpg, .mpeg, .mp4), use:

<input type="file" accept="video/*" />
For Audio Files (.mp3, .wav, etc), use:

<input type="file" accept="audio/*" />
For PDF Files, use:

<input type="file" accept=".pdf" /> 
DEMO:

NOTE:

If you are trying to display Excel CSV files (.csv), do NOT use:

text/csv
application/csv
text/comma-separated-values (works in Opera only).
If you are trying to display a particular file type (for example, a WAV or PDF), then this will almost always work...

 <input type="file" accept=".FILETYPE" />

Check if uploaded file is CSV Format or not in php

$csv_mimetypes = array(
    'text/csv',
    'text/plain',
    'application/csv',
    'text/comma-separated-values',
    'application/excel',
    'application/vnd.ms-excel',
    'application/vnd.msexcel',
    'text/anytext',
    'application/octet-stream',
    'application/txt',
);

if (in_array($_FILES['upload']['type'], $csv_mimetypes)) {
    // possible CSV file
    // could also check for file content at this point
}

Popular Posts

Stack Of Codes, stackofcodes, Stack your codes here, Open your coding for all, Php coding, Codeigniter, blogger, Stack of codes Developers, Php Framework, stackofcodes.in, best coding site, Stack the codes, place the code in stack, Stack of codes is the largest, most trusted online community for developers to learn and share their programming knowledge and build their carrers.

Labels

PHP CodeIgniter SQL Facebook HTML Connect mysqli Constructor Destructor Stack Of Codes Update SQL codeignitre delete files from folder Aadhaar Agent Align center image Alternative Control Structure Back Slash Browser Browser version CSS Calculate Date Difference in php Cannot modify header information Check image exists CodeIgniter get_where CodeIgniter-HMVC-3.1.6 Codeigniter 3.1.7 Connect and select database Constants Constructor and Destructor Convert stdClass object to array in PHP Copy Image from URL Date Calculator]php Date Difference Disable Window Update Documents exists Enable Window Update File exists Gas Linking with Aadhaar Get TinyMCE to use full image url instead of relative one Get all files from folder How to delete a file in php Image Corrupted Image Exists in php Ip address Jquery Checkbox check all Make slug in Javascript or Jquery Multiple Submit Buttons in a form Mysqli connect Only variable references should be returned by reference Open and Close html ul tag and close the ul on evry third block Phar Php Version For Codeigniter 3.0 Platform Read All files in Directory Reduce the image file size using PHP Rename Table Robots.txt Generator Robots.txt Generator - SEO Tools - SEObook Scraping Data Scraping Data From Website Scrollbar Design Select Checkbox Server Requirements For Codeigniter 3.1.6 Simple Carousel demo Slug Sub string in Php Substring TinyMCE URL Conversion Example TinyMCE settings to get image path correct UAC Warning in windows pro Unique Check Unique Check in Codeigniter Virtual hosts WSDL cache Win 8.1 with UAC Warning XAMPP to send mail from localhost Xampp apache - XAMPP installation best frameworks best javascript frameworks check if contains http:// in php clean url clear cache codeigniter $this->db->like is case sensitive data containing apostrophes deselect Checkbox all duplicate field entry escape_str every third block ul tag will close facebook Share facebook server foreach etc front Slash get_where in codeigniter hash_hmac headers already sent how to make robot.txt file for my website? htaccess http:// or https:// iS mobile if-else iv size for all mobile / tablet display javascript json_decode in array php looking for a job make url with hyphen media queries. mysql_real_escape_string mysqli real escapr string server down slug in Javascript some function of xamp is possible disabled sql - How to split a single column values to multiple column values tinymce image path showing as ../../ unlink File url contains http:// or https:// while window update