Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Saturday, February 22, 2014

How to save data url into file on PHP

I have a simple script below written on PHP that will save the data url in a file. The example below will save the file on PDF and PNG file. You will notice here that the only difference are the file type and the file name which should comply with the file type you are saving. From the script below, you should be able to figure out how to save the other file types.

This is for saving an image file "PNG", you can also try "JPEG" and other image files.

<?php

$base_url = 'http://www.example.com/';
$file_type = 'image/png';
$file_base = $_POST['dataurl'];
$file_name = "file-".time().".png";

$file_base = str_replace('data:'.$file_type.';base64,', '', $file_base);
$file_base = str_replace('[removed]', '', $file_base);

file_put_contents(getcwd()."/files/$file_name", base64_decode($file_base));
echo $base_url."files/$file_name";

?>


The script below is for saving an application data "PDF" file.

<?php

$base_url = 'http://www.example.com/';
$file_type = 'application/pdf';
$file_base = $_POST['dataurl'];
$file_name = "file-".time().".pdf";

$file_base = str_replace('data:'.$file_type.';base64,', '', $file_base);
$file_base = str_replace('[removed]', '', $file_base);

file_put_contents(getcwd()."/files/$file_name", base64_decode($file_base));
echo $base_url."files/$file_name";

?>


Hope this will help a lot with your development. Happy coding guys!!

Saturday, December 8, 2012

How to transfer files via SFTP in PHP

It's been a long time since my last post and good I'm back again. Anyway, below is my simple script to transfer files via SFTP in PHP. Hope this helps.

<?php

// set your sftp credential (host, port, username, password)
// local file (source file)
// remote file (destination file)


$host = '<host server to connect>';
$port = '<port to connect>';
$user = '<username to sftp>';
$pass = '<password to sftp>';
$lfile = '/path/to/local/file';
$rfile = '/path/to/remote/file';

// use ssh2 php module to connect

// if ssh2 is not installed/enable, please install/enable)
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $user, $pass);

// use sftp to connect
$sftp = ssh2_sftp($connection);

// open stream connection to remote server
$stream = @fopen('ssh2.sftp://'.$sftp.$rfile, 'w');

try {
    if (!$stream) throw new Exception("Could not open remote file: $rfile");

    // get data of the local file
    $data = @file_get_contents($lfile);
    if ($data === false) throw new Exception("Could not open local file: $lfile.");

    // write the data to stream remote file
    if (@fwrite($stream, $data) === false) throw new Exception("Could not send data from file: $lfile.");
    echo 'done!';

} catch (Exception $e) {
    // echo error message
    echo $e->getMessage();
}

// closing the stream
fclose($stream);

?>


Hope this helps and please leave a post if you like it. Thanks!!

Thursday, January 5, 2012

File upload with style using jQuery and CSS

This post is an improved version of my previous post "How to put a style on input file type using CSS and jQuery". The improvement is due to the problem on IE sucks with security issues.

My previous post I have is basically working and will teach you how to open a dialog box and select the file you want to upload with a styled layout.

However, the problem on IE is that it doesn't accept the approach of jQuery or Javascript, that triggers the click event of the input file element that causes an error "Access is Denied" when submitted.

Good thing I was able to find a way to trick IE. Please see below on how I do it and hopefully will be able help developers.

First, we need to understand what IE's requirement are to make it work. So, basically for the file upload to work on IE, the user should have to click on the input file element without using jQuery or Javascript to do it for us.

Given the requirement of IE and the style to put in, the best solution for me is to use CSS opacity and z-index.

In logic, what you need to do is #1. set your input file element on top of your styled textbox using z-index, this is for user to be able to click the file input element. #2. set the input file element as invisible using the opacity equal to zero "0", this is to hide the input file element and the styled textbox will be visible instead. That way, we can satisfy IE and at the same time, be able to style the file upload.

As for the sample script I made, please see below.
The sample compose of 2 scripts: index.html and upload.php

index.php

<html>
<head>
        <title>File Upload</title>

        <style type="text/css">
        div.inputContainer {
                position: relative;
        }
        div.inputStyled {
                position: absolute;
                top: 0px;
                left: 0px;
                z-index: 1;
        }
        input.inputHide {
                position: relative;
                text-align: right;
                -moz-opacity:0 ;
                filter:alpha(opacity: 0);
                opacity: 0;
                z-index: 2;
        }
        </style>

        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
                $('#docufile').change(function() {
                        var vals = $(this).val();
                        val = vals.length ? vals.split('\\').pop() : '';

                        $('#document').val(val);
                });

                $('#btnSubmit').click(function() {
                        $('#frmAdd').submit();
                });
        });
        </script>
</head>
<body>
<form id="frmAdd" name="frmAdd" action="upload.php" method="post" enctype="multipart/form-data" encoding="multipart/form-data">
        <div class="inputContainer">
        <div class="inputStyled">
                <input name="document" id="document" type="text">
                <input name="button" type="button">
        </div>
        <input type="file" class="inputHide" name="docufile" id="docufile"/>
        </div>
        <input type="submit" value="submit" id="btnSubmit"/>
</form>
</body>
</html>


upload.php

<?php

$docufile = '';
if (@$_FILES['docufile']['tmp_name']) {
        $docufile = upload_file($_FILES['docufile']);
}

echo $docufile;

function upload_file($docu=null) {
        $upload_dir = "files/";
        $docu_file='';

        if (!$docu['error'] == 0) return '';
        if (!@is_uploaded_file($docu['tmp_name'])) return '';

        $filename = preg_replace("/\s+/", "", $docu['name']);
        if (!file_exists($upload_dir.$filename)) {
                $docu_file = $filename;
        } else {
                $rand = 1;
                while(file_exists($upload_dir.$rand."-".$filename)) {
                        $rand ++;
                }
                $docu_file = $rand."-".$filename;
        }

        $upload_file = $upload_dir.$docu_file;
        if (!@move_uploaded_file($docu['tmp_name'], $upload_file)) {
                return '';
        }

        return $docu_file;
}
?>



Quote for the day:
If you want to reach your potential, you need to add a strong work ethic to your talent. If you want something out of your day, you must put something in it. Your talent is what God put in before you were born. Your skills are what you put in yesterday. Commitment is what you just put in today in order to make today your masterpiece and make tomorrow a success. - john m.

Tuesday, December 20, 2011

How to put a style on input file type using CSS and jQuery

I came to this development where in I need to put a style on input file element. This is actually a challenge for me, but was able to find a way to do it. The button and inputbox is normally display in one call of an element. However, in CSS we can't style it the way we do with a normal input box, text area, etc.. and the only way for us to style it is to use jQuery/Javascript with a simple cheat using CSS.

First, we need to have a style for our inputbox and button.., that is actually for you to decide on how you want it to be.

Second, setup the HTML with the input file type element together with a styled inputbox and button. Please see below on how it will look like and take note of the id attribute I put in to be use for jQuery.

<input type="text" id="inputbox" name="inputbox" class="myinputbox"/>
<input type="button" id="button" name="button" class="mybutton"/>
<input type="file" id="inputfile" name="inputfile"/>


Once you've setup your HTML, we need to use the jQuery to trigger the #inputfile whenever we click on #inputbox or #button. Please see below.

$('#inputbox, #button').click(function() {
    $('#inputfile').trigger('click');
});


We also need to get the value of the #inputfile and change the value of the styled #inputbox as it changes. This is normally the filename of the file you selected on the open file dialog box.

$('#inputfile').change(function() {
    var data = $(this).val();
    var file = data.length ? data.split('\\').pop() : '';
    $('#inputbox').val(file);
});


Now, whenever you click on #inputbox and #button, the open file dialog box should appear and any change of value on #inputfile should reflect on #inputbox.

Lastly, we need to hide the #inputfile and retain the styled #inputbox and #button with a functional input file type element.

We can't use style="display:none" coz in some browsers JS will not work if the element is HIDE. So, the best way to do it is to set the opacity to "0" zero. This is a simple cheat to hide the elements without disabling them.

You will also have to consider other browsers, so the style should support all browsers. Please see below.

-moz-opacity:0;
filter:alpha(opacity:0);
opacity:0;


In summary, your HTML script should be like this.

<html>
<head>
<title>How to put a style on input file type using CSS and jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <input type="text" id="inputbox" name="inputbox" class="myinputbox"/>
    <input type="button" id="button" name="button" class="mybutton"/>
    <input type="file" id="inputfile" name="inputfile" style="opacity:0"/>
</body>
<html>
<script type="text/javascript">
$(document).ready(function() {
    $('#inputbox, #button').click(function() {
        $('#inputfile').trigger('click');
    });

    $('#inputfile').change(function() {
        var data = $(this).val();
        var file = data.length ? data.split('\\').pop() : '';
        $('#inputbox').val(file);
    });
});
</script>


Hope this helps a lot of developers.
Please see also my new post "File upload with style using jQuery and CSS".

Sunday, April 3, 2011

File handling in PERL

We have 2 ways on how to write to a file in PERL.

The script below will create and write to a file overwritten the data inside the file. The script will automatically creates a file if it doesn't exist. An error will return if there's a file permission denied or directory path doesn't exist.

open FHFILE, "> file1.txt" or die "file can't be created: $!";
print FHFILE "test data\n";
close FHFILE;

The script below will create and append to a file. Same with #1, it automatically creates a file and an error will return if there's a file permission denied or directory path doesn't exist.

open FHFILE, ">> file1.txt" or die "file can't be created: $!";
print FHFILE "test data\n";
close FHFILE;

The script below will read the file then pass the data into an array. An error will return if file is not readable.

open FHFILE, "< file1.txt" or die "error reading file: $!";
@arrData = <FHFILE>;
close FHFILE;

Thursday, February 3, 2011

How to create a file transfer script via FTP in PERL

For you to be able to do a file transfer from your server to destination server, your server should be able to establish connection to destination server.

You only need the 4 details from the destination server:
  • Destination Server IP
  • Destination Port where you are connected into (by default is 22)
  • FTP Account Username
  • FTP Account Password.

Lets assume you have now the credentials and your server is allowed to connect to destination server via the IP and Port provided. We can now develop the script that will transfer files from your server to destination server.

Just follow the simple steps below with the complete code at the end for your reference.

1. We need the FTP library to be installed in your server.
  • Net::FTP 
2. Once installed, initialize Net::FTP by passing the [DESTINATION SERVER IP] and [DESTINATION SERVER PORT]. Save it to an object variable say $ftp, this is for you to be able to call the methods available for your script.

$ftp = Net::FTP->new([DESTINATION SERVER IP],Port=>[DESTINATION SERVER PORT]);

3. You can also get the return message or status of every object call by calling $object->message. The $object is the return object on step #2.

$ftp->message;

4. Submit the login credentials by calling $object->login(<username>, <password>).

$ftp->login([USERNAME], [PASSWORD]);

5. If successful, you can change or create your destination working directory by executing $object->cwd(<directory>) or $object->mkdir(<directory>).

$ftp->cwd($ftp_dir) or $ftp->mkdir($ftp_dir);

6. If your okay with your working directory, you can now transfer files from your server to destination server by calling $object->put(<source file>, <destination file>).

$ftp->put("[FILEPATH AND FILENAME OF SOURCE SERVER]", "[FILENAME OF DESTINATION SERVER]");

7. Then close the connection by calling $object->quit.

$ftp->quit;


That's it!! Hope you were able to follow the 7 simple steps above. You can also get the complete code with added functionality to support temporary files and renaming. Please see below.

#!/usr/bin/perl

use Net::FTP;

$ftp_ip = "<your destination ip>";
$ftp_port = "<your destination port>";
$ftp_user = "<your ftp account username>";
$ftp_pass = "<your ftp account password>";
$ftp_dir = "<your destination working directory>";

$ftp_src_file = "<your source file to be transfered include the full source path>";

$ftp_dest_file_temp = "<your temporary destination filename>";
$ftp_dest_file_good = "<your final destination filename>";

# create new instance
$ftp = Net::FTP->new($ftp_ip,Port=>$ftp_port) || die "ERROR: Unable to connect to host [$ftp_ip:$ftp_port]";
var_dump($ftp->message);

# login
$ftp->login($ftp_user, $ftp_pass) || die "ERROR: Unable to login [$ftp_user]";
var_dump($ftp->message);

# change working directory
$ftp->cwd($ftp_dir) or $ftp->mkdir($ftp_dir);
var_dump($ftp->message);

# transfer files
$ftp->put("$ftp_src_file", "$ftp_dest_file_temp") || die "ERROR: Transfer failed!",$ftp->message;
var_dump($ftp->message);

# rename files
$ftp->rename("$ftp_dest_file_temp", "$ftp_dest_file_good") || die "ERROR: Rename Failed!",$ftp->message;
var_dump($ftp->message);

# closing the ftp connection
$ftp->quit;

echo "done!";

1;

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.