PHP

Import large CSV data via PHP

Importing large data may cause Memory problems or timeout problems, here is how to avoid these problems.

$file = $_FILES['file']['tmp_name'];
        $handle = fopen($file, "r");
        while (($row = fgetcsv($handle, 0, ",")) !== FALSE) {
            // $row contains all the columns in a line in csv
            // insert into students(column1..., column2..., column3....) values($row[0],$row[1],$row[2]........)
         }
Advertisements

Export large data to CSV via PHP

Exporting large data may cause Memory problems or timeout problems, here is how to avoid these problems.

$query = $this->db->query("select * from students where (DATE(order_date) between '$start' and '$end') ");
                $filename = "reports.csv";
                header('Content-type: application/csv');
                header('Content-Disposition: attachment; filename='.$filename);
                

                $fp = fopen('php://output', 'w');
                $fields = $query->list_fields();
                foreach($fields as $field){
                        $header[] = $field;
                }	
                fputcsv($fp, $header);
                
                foreach ($query->result_array() as $data) {
                        //$fp = fopen('php://output', 'a');
                        fputcsv($fp, $data);
                        
                 }
                fclose($fp);
                exit;

Setting up first route,view,controller and sending data to view laravel 5

Example Route

<?php
Route::get('home','HomeController@index');  // you tell if url has /home then home controller index function handles that
?>

Then Controller will be
app/Http/Controllers/HomeController.php

<?php
namespace App\Http\Controllers;
class HomeController extends Controller
{
	//this is the funtion handling the /home
	public function index(){
		$data = "abc"; // here is sample data
	    return View::make('home/myhome', array('data' => $data));  // this is html file will be saved in views/home/myhome.blade.php
	}

}
?>

resources/views/home/myhome.blade.php

{{ $data }} 

Model relations and Querying Laravel

Posts model may look like below

    public function tags(){
        return $this->hasMany('App\Models\Posttag','post_id','post_id');
    }
    public function user(){
        return $this->belongsTo('App\Models\User','user_id');
    }
    public function comments(){
        return $this->hasMany('App\Models\Comment','post_id','post_id');
    }
    public function comments_count(){
        return $this->hasOne('App\Models\Comment','post_id','post_id')->selectRaw('post_id, count(*) as aggregate')->groupBy('post_id');
    }

Then we can query data like so

	   $data = Post::with(['tags','comments' => function($query){
			$query->with(array('owner'))->orderBy('created_at','DESC')->limit(1);
			},'user' => function($query){
                                  $query->select('id','name','profile_pic');
                       }])->get();

Upload image plus all form data using jquery

Html

<form action="" method="post" enctype="multipart/form-data" id="form_portfolio_save">
				<input type="text" name="title" id="title" placeholder=""/><br/>
				<textarea id="about_project" name="about_project">About project</textarea><br/>
				<input type="file" name="photo" id="port_image" placeholder="Add Files"/><br/>
				<input type="text" name="caption" id="caption" placeholder="Image caption"/><br/>
				<input type="button" id="submit" value="Submit" class="button submit" onclick="save_portfolio();return false;"/>
				<input type="button" class="button cancel" id="submit" value="Cancel" />
			  </form>

JQuery

function save_portfolio(){
		var fd = new FormData();
		var file_data = $('input[name^="photo"]')[0].files; 
		for(var i = 0;i<file_data.length;i++){
			fd.append("file_"+i, file_data[i]);
		}
		var  other_data = $("#form_portfolio_save").serializeArray();
		 $.each(other_data,function(key,input){
			fd.append(input.name,input.value);
		});
	   
		$.ajax({
		url : 'save_portfolio.php',
		type : "post",
		data : fd,
		cache: false,
		contentType: false,
		processData: false,
		success : function(data){
				$("#append_portfolio").append(data);
				
		}
	});
	}

PHP

include("includes/session.php");
include("includes/database.php");
if(!empty($_FILES['file_0'])){
		$filename = time().$_FILES['file_0']['name'];
		$path= "upload/user_portfolio/".$filename;
		move_uploaded_file($_FILES['file_0']['tmp_name'],$path);
	}
$query = "insert into user_portfolio(title,description,images,image_captions,employee_id) values('".$_POST['title']."','".$_POST['about_project']."','".$filename."','".$_POST['caption']."','".$_SESSION['user_details']['id']."')";
mysql_query($query);

PAYPAL PAYMENT DATA TRANSFERS (PDT)

To use PDT, you must activate PDT and Auto Return in your PayPal account profile. You must also acquire a PDT identity token, which is used in all PDT communication you send to PayPal.

Follow these steps to configure your account for PDT:

1)Log in to your PayPal account.
2)Click the Profile subtab.
3)Click the My Selling Tools button in the left column.
4)Find the Selling online section and click Update in the Website preferences row.
5)Under Auto Return for Website Payments, click the On radio button.
6)For the Return URL, enter the URL on your site that will receive the transaction ID posted by PayPal after a customer payment.
7)Under Payment Data Transfer, click the On radio button.
8)Click Save.
9)Find the Selling online section and click Update in the Website preferences row again.
10)Scroll down to the Payment Data Transfer section of the page and take note of your PDT identity token.

Create the form now with notify url and cancel url

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" accept-charset="utf-8"> 
    <p> 
    <input type="hidden" name="cmd" value="_xclick" /> 
    <input type="hidden" name="charset" value="utf-8" /> 
    <input type="hidden" name="business" value="paypal@business.example.com" /> 
    <input type="hidden" name="item_name" value="Stuffed bear" />
    <input type="hidden" name="item_number" value="BEAR05" />
    <input type="hidden" name="amount" value="20.00" />
    <input type="hidden" name="currency_code" value="USD" />
    <input type="hidden" name="return" value="http://business.example.com/order/123/" /> 
    <input type="hidden" name="cancel_return" value="http://business.example.com/order/123/" />
    <input type="hidden" name="bn" value="Business_BuyNow_WPS_SE" /> 
    <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" name="submit" alt="Buy Now" />
    </p> 
</form>

Catch the return now as $_GET[‘tx’] and repost to paypal

if(isset($_GET['tx']))
{
  $tx = $_GET['tx'];
  $request = curl_init();
  curl_setopt_array($request, array
(
  CURLOPT_URL => 'https://www.sandbox.paypal.com/cgi-bin/webscr',
  CURLOPT_POST => TRUE,
  CURLOPT_POSTFIELDS => http_build_query(array
    (
      'cmd' => '_notify-synch',
      'tx' => $tx,
      'at' => $your_pdt_identity_token,
    )),
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_HEADER => FALSE,
  // CURLOPT_SSL_VERIFYPEER => TRUE,
  // CURLOPT_CAINFO => 'cacert.pem',
));

// Execute request and get response and status code
$response = curl_exec($request);
$status   = curl_getinfo($request, CURLINFO_HTTP_CODE);
if($status == 200 AND strpos($response, 'SUCCESS') === 0)
{
    // Further processing
}
else
{
    // Log the error, ignore it, whatever 
}
// Close connection
curl_close($request);
}

Time Ago function


function time_ago($date)

		{

				if(empty($date)) {

							return "No date provided";

				}

				$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

				$lengths = array("60","60","24","7","4.35","12","10");

				$now = time();

				$unix_date = strtotime($date);

				// check validity of date

				if(empty($unix_date)) {

						return "Bad date";

				}

				// is it future date or past date

				if($now > $unix_date) {

						$difference = $now - $unix_date;

						$tense = "ago";

				} else {

						$difference = $unix_date - $now;
						$tense = "from now";}

						for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {

						$difference /= $lengths[$j];

				}

				$difference = round($difference);

				if($difference != 1) {

						$periods[$j].= "s";

				}

						return "$difference $periods[$j] {$tense}";

               }