Posts

Creating a CSV File Using PHP

In PHP, there are functions defined to create a CSV file. There are several advantages to using these functions instead of libraries like PhpExcel. It consumes less resources and is faster.

First, let’s create a function that will create our CSV file.

<?php

function array_to_csv_function($array, $filename = "export.csv", $delimiter=";") {
    // Instead of opening a temp file, we use memory space.
    $f = fopen('php://memory', 'w');
    // We're making a loop with an array which contains our data
    foreach ($array as $line) {
        // Each array in our array is a line in our CSV file.
        fputcsv($f, $line, $delimiter);
    }
    // File initialization is reset
    fseek($f, 0);
    // Php tells the browser that it is a csv file
    header('Content-Type: application/csv');
    // Php tells the browser not to display, to save. 
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // The generated CSV is transferred to the browser.
    fpassthru($f);
}

With this function, we can create a CSV file and output it to the browser by sending a series of file names to the function. I have explained each line in the code with comments. I made this function use memory space instead of using a temporary temp file. If you want to use a temporary temp file, replace $f = fopen(‘php: // memory’, ‘w’); with $f = fopen(‘php: // output’, ‘w’); command.

We then create an array that will be an array of lines, either by pulling it from the database or from a json data, and send it to our function. That’s all. As an example, I wrote the code below;

<?php

$titles = array("Name", "Surname");
$row1 = array("Erhan", "Kılıç");
$row2 = array("Onur", "Bakır");
$content = array($titles, $row1, $row1);

array_to_csv_function($content, "export.csv");

WordPress Security Tips

It is very important to take security measures for WordPress. If you do not take your security measures, your site may be hacked or you may suffer data loss.

Security Tips During WordPress Installation

1) Create a strong user password database. It must contain uppercase letters, lowercase letters, numbers, and special characters.

2) Don’t make the database’s name and username simple and guessable names, ie database, db, admin, database.

3) WordPress asks for a prefix on the installation screen. By default, wp_ is the prefix. This is the most common of the tables in the database. Use a different prefix from the default.

4) In the user name and password selection, select a different name from admin, administrator. These are tried first because they are defaults. Likewise, create the password with upper case, lower case, number and special character so it will be strong.

Security Tips After WordPress Installation

1) Add the following codes to your .htaccess file.

# Prevent access to .htaccess file
<files .htaccess>
order allow,deny
deny from all
</files>
# remove server signing
ServerSignature Off
# limit file upload size to 10MB
LimitRequestBody 10240000
# Prevent access to wp config.php file
<files wp-config.php>
order allow,deny
deny from all
</files>
# Prevent access to wp-load.php file
<files wp-load.php>
order allow,deny
deny from all
</files>
# disable directory listing
Options All -Indexes

2) The wp-config.php file has a place called unique keys. If you have never touched it, you will see something like this.

define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');
define('AUTH_SALT', 'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT', 'put your unique phrase here');
define('NONCE_SALT', 'put your unique phrase here');

This is very important. It encrypts cookies and password records with them. When you visit http://api.wordpress.org/secret-key/1.1/salt, WordPress will give you the necessary codes to add there. Copying and pasting are enough.

3) Use plugins as little as possible. They will slow down your site and increase their vulnerability to attack.

4) Get the themes and plugins as much as possible from reliable sources such as WordPress or code them yourself. Never use warez themes or plugins.

Most importantly, always update your WordPress.

Adding Infinite Scroll Without Plugin To WordPress Theme

In this article, I will tell you how to add an infinite scroll to your WordPress theme without using the plugin. This article will be the most accurate article. Because if I have done my research to add endless scrolls myself, I have found articles that describe using plugins or methods that work in index.php but not in category.php or author.php. They did not work right on the other files. Because the sample verbs do not load in the category file according to the categorization while loading the second page and the letters of the latter. It was loading all the pages.

You can refer to the source code of AdminLteWpTheme when doing these operations. There are codes of the employee working there.

I suggest you create a child theme before adding this feature.

First, we add the following codes to the functions.php file;

//Infinite Scroll
function wp_infinitepaginate(){
 $loopFile = $_POST['loop_file'];
 $paged = $_POST['page_no'];
 $action = $_POST['what'];
 $value = $_POST['value'];
 
 if($action == 'author_name'){
 $arg = array('author_name' => $value, 'paged' => $paged, 'post_status' => 'publish' );
 }elseif($action == 'category_name'){
 $arg = array('category_name' => $value, 'paged' => $paged, 'post_status' => 'publish' );
 }elseif($action == 'search'){
 $arg = array('s' => $value, 'paged' => $paged, 'post_status' => 'publish' );
 }else{
 $arg = array('paged' => $paged, 'post_status' => 'publish');
 }
 # Load the posts
 query_posts( $arg );
 get_template_part( $loopFile );
 
 exit;
}
add_action('wp_ajax_infinite_scroll', 'wp_infinitepaginate'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'wp_infinitepaginate'); // if user not logged in

When an ajax request arrives, this function will work, will generate a loop and this loop will get our file. In our function we will receive some POST data;

“loop_file” is the name of our loop file. This file will generate HTML codes. Then we will append it with JavaScript.

The page number is “page_no”. We, therefore, determine which page we will be using.

“what” is what we want pages for. Like category, author, search, etc.

“value” contains the category slug name, author nice name, etc., if the category, author, or request.

With the If query, we create our parameters for query_posts according to what we want here. Then we can create a loop with query_posts and call our file with get_template_part.

With the add_functions function, we provide an ajax request to wp-admin/wp-ajax.php to run your function. We send an infinite_scroll in the action post while sending an Ajax request. So you can create different ajax operations with different names and functions.

Then we will create our loop file under our theme directory. You can give the name here as you like, but don’t forget, you should send this name in the “loop_file” post. I gave the name loop.php. Here you can copy your direct loop from the index.php file. I am putting it as an example in AdminLteWpTheme here.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 <!-- timeline time label -->
<li class="time-label">
 <span class="bg-green"><?php the_time('d.m.Y ') ?></span>
 </li>
 <!-- /.timeline-label -->
 <!-- timeline item -->
<li>
 <i class="fa fa-newspaper-o bg-blue"></i>
<div class="timeline-item">
 <span class="time"><i class="fa fa-clock-o"></i> <?php the_time('H:i') ?></span>
<h3 class="timeline-header"><a href="<?php the_permalink() ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?> "><?php the_title(); ?></a></h3>
<div class="timeline-body">
<div class="row">
<div class="col-lg-3 col-sm-4 col-xs-6">
 <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
 <?php $resim_yolu = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium'); if ( has_post_thumbnail() ) { ?>
 
 <img src="<?php echo $resim_yolu[0]; ?>" class="img-responsive" alt="<?php the_title(); ?>" title="<?php the_title() ?>" />
 <?php } ?>
 </a>
 </div>
<div class="col-lg-9 col-sm-8 col-xs-6">
 <?php the_excerpt_rss(); ?>
<div style="margin-top: 10px">
 <a class="btn btn-primary btn-xs" href="<?php the_permalink() ?>" title="<?php the_title(); ?>">Read more</a>
 </div>
 </div>
 </div>
 </div>
<div class="timeline-footer">
 <i class="fa fa-user"></i> <a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php the_author(); ?>"><?php the_author(); ?></a> | <i class="fa fa-folder-open"></i> <?php the_category(', ') ?> | <i class="fa fa-comments"></i> <?php comments_number('0 comment', '1 comment', '% comments' );?>
 </div>
 </div>
 </li>
 <!-- END timeline item -->
 <?php endwhile; ?>
<?php endif; ?>

Finally, we must write our JavaScript code in our files like index.php, category.php.

<script type="text/javascript">
 jQuery(document).ready(function($) {
   var count = 2;
   var total = <?php echo $wp_query->max_num_pages; ?>;
   $(window).scroll(function(){
     if ($(window).scrollTop() == $(document).height() - $(window).height()){
      if (count > total){
        return false;
      }else{
        loadArticle(count);
      }
      count++;
     }
   });
 
   function loadArticle(pageNumber){
     $('a#inifiniteLoader').show('fast');
     $.ajax({
       url: "<?php echo admin_url(); ?>admin-ajax.php",
       type:'POST',
       data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop',
       success: function (html) {
         $('li#inifiniteLoader').hide('1000');
         $("ul.timeline").append(html);
       }
     });
     return false;
   }
 });
</script>

The Count variable is our page number. Initially, it will be 2 because the second page will be uploaded when the page goes down first. Each ajax will increase the variable on demand. Our Total variable is the total number of pages. In this case, we will make sure that the function does not work when the page goes down.

$(window).scroll( function () {} ); function will send an ajax request when the page goes down and we will increase the count variable. Of course, we write an If condition (as long as the count variable is bigger than our total variable) so the code won’t work unnecessarily.

With our loadarticle() function, we first make the loading icon appear and then send the ajax request. you can review the post data by sending it. We do not forget to include what and value data in places such as category, author. As an example, I am writing in the category.php file. You can see what and value data there.

I hope this article works for you.

 

<script type="text/javascript">
 jQuery(document).ready(function ($) {
   var count = 2;
   var total = <?php echo $wp_query->max_num_pages; ?>;
   $(window).scroll(function () {
     if ($(window).scrollTop() == $(document).height() - $(window).height()) {
       if (count > total) {
         return false;
       } else {
         loadArticle(count);
       }
       count++;
     }
   });
 
   function loadArticle(pageNumber) {
     $('a#inifiniteLoader').show('fast');
     $.ajax({
       url: "<?php echo admin_url(); ?>admin-ajax.php",
       type: 'POST',
       data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=loop&what=category_name&value=<?php echo $yourcat->slug; ?>',
       success: function (html) {
         $('li#inifiniteLoader').hide('1000');
         $("ul.timeline").append(html);
       }
     });
     return false;
   }
 });
</script>

Installing Linux, Apache, MySQL and PHP (LAMP) On Ubuntu

Installing the Default LAMP Package on Ubuntu

If you want to install the LAMP in the easiest way, you need to write the following codes in the terminal.

sudo apt-get update
sudo apt-get install lamp-server^

Do not forget to type the character “^” otherwise it will fail.

Installing Linux, Apache, MySQL, PHP on Ubuntu

If you want to load all separately, you are in the right place. This is a little more painful, but it gives you a better use and the ability to load whatever you want.

Installing Apache

sudo apt-get update
sudo apt-get install apache2

That’s it. Apache installed. To check, enter http: // localhost in your web browser and it is loaded without any problems if you see “It Works!”. If you are installing on your vps server, you must type in your ip address of your VPS from the browser.

Installing MySQL

sudo apt-get install mysql-server

It will ask you to enter the MySQL user’s root password.

Installing PHP

sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

That’s all.

Installing PHP Modules

Type the following code in the terminal to list the php modules.

apt-cache search php5-

If you want to install one of them, you can install it into the terminal by typing the following code.

sudo apt-get modül ismi
sudo apt-get php5-cli

Project Euler – Problem 5 Solution

Problem: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
* https://projecteuler.net/problem=5

Php;

<?php

$number = 20;
$isFound = false;
$checkList = [11, 13, 14, 16, 17, 18, 19, 20];

while (!$isFound) {
    $divided = true;
    foreach ($checkList as $check) {
        if ($number % $check != 0) {
            $divided = false;
            break;
        }
    }
    if ($divided) {
        $isFound = true;
        echo "Number is $number";
        break;
    } else {
        $number+=20;
    }
}

Javascript;

'use strict';

var number = 20;
var isFound = false;
var checkList = [11, 13, 14, 16, 17, 18, 19, 20];

while (!isFound) {
    var divided = true;
    for (let check of checkList) {
        if (number % check != 0) {
            divided = false;
            break;
        }
    }
    if (divided) {
        isFound = true;
        console.log("Number is " + number);
        break;
    } else {
        number+=20;
    }
}

Project Euler – Problem 4 Solution

Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
* https://projecteuler.net/problem=4

Php;

<?php

/**
 * Checks number if palindrome or not!
 *
 * @param $number
 * @return bool
 */
function check_if_palindrome($number)
{
    $is_palindrome = true;
    $array  = array_map('intval', str_split($number));
    $array2  = array_map('intval', str_split($number));
    $array2_count = count($array2) - 1;
    foreach ($array as $index => $item) {
        if ($item !== $array2[$array2_count - $index]) {
            $is_palindrome = false;
        }
    }
    return $is_palindrome;
}

$value = 0;
for ($i = 100; $i < 1000; $i++) {
    for ($k = 100; $k < 1000; $k++) {
        $result = $k * $i;
        if (check_if_palindrome($result) && $result > $value) {
            $value = $result;
        }
    }
}
echo $value;

Javascript;

'use strict';

/**
 * Checks number if palindrome or not!
 * @param number
 */
function check_if_palindrome(number) {
    var is_palindrome = true,
        array = (""+number).split(""),
        array2 = (""+number).split(""),
        array2_count = array2.length - 1;

    for (var i = 0; i < array2_count; i++) {
        if (array[i] !== array2[array2_count - i]) {
            is_palindrome = false;
        }
    }

    return is_palindrome;
}

var value = 0;
for (var i = 100; i < 1000; i++) {
    for (var k = 100; k < 1000; k++) {
        var result = k * i;
        if (check_if_palindrome(result) && result > value) {
            value = result;
        }
    }
}

console.log(value);