Tuesday, 3 June 2014

Calling Python Program in PHP with response feedback progressbar

Hey all,
I have a question of about how to get response of python program in php while we executing python in php. I found this solution. Which may be useful for some of you.


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">  
 <html lang="en">  
 <head>  
   <title>Progress Bar</title>  
 </head>  
 <body>  
 <!-- Progress bar holder -->  
 <div id="progress" style="width:500px;border:1px solid #ccc;"></div>  
 <!-- Progress information -->  
 <div id="information" style="width:200px;"></div>  
 <div id="myDiv"></div>  
 <?php  
 // Total processes  
 $total = 3;  
 // Loop through process  
 for($i=1; $i<=$total; $i++){  
   // Calculate the percentation  
   $percent = intval($i/$total * 100)."%";  
   // Javascript for updating the progress bar and information  
   echo '<script language="javascript">  
   document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>";  
   document.getElementById("information").innerHTML="processed.";  
   </script>';  
 // This is for the buffer achieve the minimum size in order to flush data  
   echo str_repeat(' ',1024*64);  
   echo 'Please wait...<br/>';  
   ob_flush();  
 // Send output to browser immediately  
   flush();  
 // Sleep one second so we can see the delay  
   sleep(1);  
 }  
 // Tell user that the process is completed  
 $pyscript = 'G:\wamp\www\ll\test.py';  
 $python = 'C:\\Python27\\python.exe';  
 $cmd="$pyscript $python";  
 exec("$cmd", $output);  
 file_put_contents('test.txt', $output);  
 $myfile = fopen("test.txt", "r") or die("Unable to open file!");  
 sleep(0.5);  
 echo fread($myfile,filesize("test.txt")).'<br/>';  
 fclose($myfile);  
 echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';  
 ?>  
 </body>  
 </html>  

If you found this useful.Like my blog.Subscribe me.Please give your valuable comments about my blog.

Monday, 2 June 2014

Ajax Progress Bar file upload with Node.js and Express.js Part-1

Hello Guys,

Finally,I got it worked out.As i mentioned in my previous posts for file upload in node.js with ajax progress bar has been done successfully after two days.And the snippet is as follows.


create a file name it as server.js

 var express = require('express'),  
   app = express(),  
   multer = require('multer'),  
   img = require('easyimage');  
 var imgs = ['png', 'jpg', 'jpeg', 'gif', 'bmp']; // only make thumbnail for these  
 function getExtension(fn) {  
   return fn.split('.').pop();  
 }  
 function fnAppend(fn, insert) {  
   var arr = fn.split('.');  
   var ext = arr.pop();  
   insert = (insert !== undefined) ? insert : new Date().getTime();  
   return arr + '.' + insert + '.' + ext;  
 }  
 app.configure(function () {  
   app.use(multer({  
     dest: './static/uploads/',  
     rename: function (fieldname, filename) {  
       return filename.replace(/\W+/g, '-').toLowerCase();  
     }  
   }));  
   app.use(express.static(__dirname + '/static'));  
 });  
 app.post('/upload', function (req, res) {  
   console.log('upload function start working');  
   if (imgs.indexOf(getExtension(req.files.userFile.name)) != -1)  
     img.info(req.files.userFile.path, function (err, stdout, stderr) {  
       if (err) throw err;  
 //    console.log(stdout); // could determine if resize needed here  
       img.rescrop(  
         {  
           src: req.files.userFile.path, dst: fnAppend(req.files.userFile.path, 'thumb'),  
           width: 50, height: 50  
         },  
         function (err, image) {  
           if (err) throw err;  
           res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name, thumb: fnAppend(req.files.userFile.name, 'thumb')});  
         }  
       );  
     });  
   else  
     res.send({image: false, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});  
 });  
 var server = app.listen(3000, function () {  
   console.log('listening on port %d', server.address().port);  
 });  
Now create a folder called static.Create uploads folder and js folder and index.html.
Will keep continue writing this post.If you find this useful like my blog subscribe.If you have any doubts or suggestion feel free to comment below.

How to execute python in php || How to use exec() command for calling python in php

Hello all,

I have came through an interesting thing,that is running an python program from PHP interface. Sounds cool right! I have faced some problems and finally get it done with simple example.Which i want to share with you all. This might be helpful for you .


 <?php  
 $pyscript = 'G:\wamp\www\ll\test.py';  
 $python = 'C:\\Python27\\python.exe';  
 $cmd="$pyscript $python";  
 exec("$cmd", $output);  
 print_r($output);  
 var_dump($output);  
 ?>  


You can easily run a python program now.I have done this in windows environment.If u doing in ubuntu,there is no need for path variables.If you find this useful like my blog subscribe me.Thank you.

Sunday, 1 June 2014

Node with Express Simple file upload (latest version code)

Hello friends,

I am newbie to Node.js.When i tried to make a simple image uploading script. I find more difficulty to find exact resources or good tutorials because most of them are depreciated. Finally after a full day research,I  somewhat made my file uploading script.I found that if i share somewhere on the internet,It will be useful for others.So started this blog. Going to share my experience with node in this blog.

Now the script as follows.

This is my html file
 <html lang="en-US">
 <head>
   <meta charset="UTF-8">
   <title>File Upload showing Upload Progress</title>
   <style>
     * {
       font-family: Verdana;
       font-size: 12px;
     }
   </style>
 </head>
 <body>
 <form action="/upload" method="post" enctype="multipart/form-data" id="uploadForm">
 <input name="ImageFile" id="imageInput" type="file" />
 <input type="submit" id="submit-btn" value="Upload" />
 </form>
 <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
 </body>
 </html>


and my app.js (you can name it as you want like server.js or anything you want)
 var express = require('express');  //Express Web Server
 var bodyParser = require('body-parser'); //connects bodyParsing middleware
 var formidable = require('formidable');
 var path = require('path');   //used for file path
 var fs =require('fs-extra');  //File System-needed for renaming file etc
 var app = express();
 app.use(express.static(path.join(__dirname, 'public')));
 app.set('views', __dirname + '/views');
 app.engine('html', require('ejs').renderFile);
 /* ==========================================================
  bodyParser() required to allow Express to see the uploaded files
 ============================================================ */
 app.use(bodyParser({defer: true}));
 app.route('/').get(function(req,res)
 {
   console.log("Server started!");
    res.render('index.html');
    res.end('done');
   });
 app.post('/upload', function(req, res) {
   var form = new formidable.IncomingForm();
   form.parse(req, function(err, fields, files) {
     var targetPath= '/upload/' + files.ImageFile.name;
     fs.move(files.ImageFile.path, __dirname + '/upload/' + files.ImageFile.name, function(err) {
       if (err) return console.log(err);
       console.log('Moved successfully');
     });
     res.send('File Uploaded to ' + targetPath + ' - ' + files.ImageFile.size + ' bytes');
   });
 });
 var server = app.listen(3030, function() {
 console.log('Listening on port %d', server.address().port);
 });

To get this work successfully.Create a upload folder in your project.This script simply allows you  to make file uploaded from form to server.As my next step, I am trying to do with this ajax and some more form validation.Hope soon will hit with that.

If you have any question,feel free to ask me.If i able to answer, i will surely help you guys.If you found this helpful share it with your friends and subscribe.