Showing posts with label examples. Show all posts
Showing posts with label examples. Show all posts

Sep 9, 2011

How to make tar and tar.gz archives with PHP

This question is somewhat painful for me. Maybe I am too stupid. Anyway, if you want to make tar archive without using exec, for example on Windows machine without tar tool or any other stupid reason, here is how to do it with PHP. Its actually very easy if you know how to do it.

For example lets have a directory called dir and we want to make an archive with its content. The solution for our problem is Phar.

Here is the code that do the job:

<?php

// we want to archive all files from this directory
$dir = "dir/";

// the name of our new tar
$phar = new Phar("ourarchive.phar.tar");

// build from our dir
$phar->buildFromDirectory($dir);

// we are using gzip comppression
$phar->compress(Phar::GZ);

?>
Look carefully at the name of our archive - the parameter that we give when we create Phar object. It ends with phar.tar. If you use only .tar it will return error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'Cannot create phar 'ourarchive.tar', file extension (or combination) not recognised
This is not fun if you are trying to create tar and you receive this message. So using file name that ends with phar.tar will fix the problem.

If you receive error:
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Unable to add newly converted phar "/www/pro/ourarchive.phar.tar" to the list of phars, a phar with that name already exists'
most likely your tar file already exist.

Learn here how to make Zip archives with PHP

How to make Zip archives with PHP - part 1

Actually working with zip archives isn’t that obvious that it looks from the documentation. But if you want an adventure try to make tar or tar.gz. Actually in one of my next posts I will describe the procedure. Now, we are talking about zip here.

Example: Create archive and add file to it
<?php
 // the file that we want to compress
 $file = "path/filetocompress.txt";

 
 // how we want to name the file in the archive
 $name = "filename.txt";
 
 // we need to create new object
 $zip = new ZipArchive();

 
 // we are using ZipArchive::open with flag CREATE to make new zip archive
 if ($zip->open("ournew.zip", ZipArchive::CREATE) === TRUE) {

  
  // here the first parameter is the file on our system
  // the second is the name to be used for this file in our new zip 
     $zip->addFile($file, $name);

     
     // close is used for both close and save
     $zip->close();
 } else {

     echo 'Error';
 }
?>

Fast PHP example - FTP file upload

Here is one fast and simple example on how to do FTP file uploads with PHP.
<?php

$ftp_server = "ftp.server.url";

$ftp_user = "user";
$ftp_password = "password";

$file_to_upload = "localfile.txt";
$remote_location = "/location/file.txt";

// set up connection or exit with message
$flink = ftp_connect($ftp_server) or exit("Can't connect to ftp server: $ftp_server");

// login or at least try  
if(ftp_login($flink, $ftp_user, $ftp_password)) {

 
 // if login successful use ftp_put to upload the file
 // if you upload binary files use mode FTP_BINARY
 if(ftp_put($flink, $remote_location, $file_to_upload, FTP_ASCII)) {

  echo "Success! File is uploaded!";
 } else {
  echo "Can't upload file";

 }
} else {
 echo "Can't login with this user & password";

}

// close the connection
ftp_close($flink);

?>
You can get more information at http://www.php.net/manual/en/ref.ftp.php

Oct 27, 2009

Intro to Struts (1.x) - Practical Example

This would be simple and easy tutorial on how to use Apache Struts in Java web projects.

What do you need for this tutorial?
  • Java
  • Tomcat
  • Java IDE (For example Eclipse or NetBeans)
  • Struts 1.x version http://struts.apache.org/download.cgi#struts1310

I’ll write another document for Struts 2.x. They are different frameworks with somehow different ideas but both are excellent choice.

For clearness it would be very simple code - I won’t use packages or other good practices. Consider this only as an introduction not a reference.

Struts programming is centered at the MVC pattern. MVC stands for Model-View-Controller, an idea to separate the business logic, application data and the presentation layer. I won’t discuss here what the advantages of using MVC architecture in web application are – just make a fast search, there is plenty of information out there.

Let’s start with creating a new project. Our web application would ask visitors for a name and redirect them to a Hi! page. At part 2 it won’t like some of the visitors and will return back them with an error message.

Here is my directory and file structure for Struts1Example project:
Struts1Example
 src
  NameAction.java
  NameActionForm.java
 webroot
  WEB-INF
   classes
   lib
   struts-config.xml
   web.xml
  ask.jsp
  greet.jsp

Lets start with writing our ActionForm – I’ll name the class NameActionForm. It would be very plain – only one field and a setter-getter pair. Here is the code:

NameActionForm.java
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;


public class NameActionForm extends ActionForm {
 private String name = null;

 
 public void reset(ActionMapping mapping, 
    HttpServletRequest request) {

        this.name = null;
 }

 public String getName() {

  return name;
 }

 public void setName(String name) {

  this.name = name;
 }
}

And our action:

NameAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class NameAction extends Action {

 public ActionForward execute(ActionMapping mapping, 
    ActionForm form,
    HttpServletRequest request, 
    HttpServletResponse response) {
  return mapping.findForward("success");
 }
}

In Struts the Action class goal is to process a request, do the logic and pass a forward object (ActionForward). Our Action is very simple – it is doing nothing, just passes our forward object. The “success” forward is defined in our struts-config.xml.

We will have two jsp files – ask.jsp and greet.jsp. In ask.jsp we will ask visitors for a name.
ask.jsp
<%@ page language="java" contentType="text/html; 
  charset=utf-8" %>

<%@ taglib uri="http://struts.apache.org/tags-html" 
  prefix="html" %>

<html:html>

<head>
<title>Say Hi!</title>
</head>
<body>
 <html:form action="nameAction">
  What's your name?
  <html:text property="name"></html:text>

  <html:submit>Send!</html:submit>
 </html:form>
</body>
</html:html>

greet.jsp
<%@ page language="java" contentType="text/html; 
  charset=utf-8" %>

<%@ taglib uri="http://struts.apache.org/tags-bean" 
  prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" 

  prefix="html" %>
<html:html>
<head>
<title>Say Hi!</title>
</head>
<body>

Hi, <bean:write name="nameForm" property="name" />
</body>
</html:html>

And now the cool part – web.xml

web.xml
<?xml version="1.0"?>
<web-app>
  <display-name>Struts 1x Example</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
     org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>

      <param-name>config</param-name>
      <param-value>
       /WEB-INF/struts-config.xml
      </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>

 </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

And our struts configuration – struts-config.xml

struts-config.xml
<?xml version="1.0" ?>
<struts-config>

    <form-beans>
     <form-bean 
      name="nameForm" 
      type="NameActionForm"/>

    </form-beans>

    <global-forwards>
        <forward
            name="/nameAction"
            path="/nameAction.do"/>

    </global-forwards>
    
    <action-mappings>         
       <action path="/nameAction" 
         type="NameAction" 

         input="ask.jsp" 
          name="nameForm" >
        <forward name="success" 

          path="/greet.jsp"/>
        <forward name="failure" 
          path="/ask.jsp"/>

       </action>
    </action-mappings>
</struts-config>

struts-config.xml is used to initialize Struts. It describes the action mappings for the project and must be placed in the WEB-INF directory. We have a form-bean tag describing our NameActionForm and an action-mapping for our NameAction.

This is our base code. In some future post I’ll add field validation, error handling and some other good stuff.

Nov 6, 2008

Intro to JQuery - part 2 - JQuery examples

If this is your first encounter of JQuery, I recommend the post – Intro to JQuery.

This is a short document on how-to use JQuery API. Necessary knowledge for this post includes JavaScript, HTML and CSS basics.


Let’s change the last example of the previous post a little. We can handle the logic without the counter variable:


<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
var c = parseInt($(this).html());
$(this).html(c + 1);
});
} );
</script>



We can add more complex code with the html(), not only one number. For example:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
$(this).html(String($(this).html() + "<br/><b>We added a row!</b>"));
});
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
This is our test div element.
</div>
</body>
</html>



Be careful to add a correct html for the html() function value or you will end with unexpected results.

JQuery have more methods for DOM manipulations. For full list of these methods I recommend reading the documentation - http://docs.jquery.com/Manipulation

Very power JQuery functionality is the opportunity to easily traverse the DOM tree. One very useful element in this part is the each(). It is used to execute a function within the context of every matched element. This is simple example of its usage:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div").each(function () {
$(this).css({border : "medium double Red", backgroundColor: "orange"});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div>First div element
</div>
<div>Second div element
</div>
</body>
</html>



And now a little more complex example:
The code bellow gets all the <p>(paragraph) childs of the <div> elements and sets them a css class “our class”. There are many other ways to achieve the same thing, this is just example of using each() and children().


<html>
<head>
<title>JQuery basic tutorial</title>
<style type="text/css">
.ourclass {
border : medium double #FFA500;
width: 90px;
height: 90px;
}

</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div ").each(function () {
$(this).children("p").each(function () {
$(this).addClass("ourclass");
});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div style="border : 1px solid Black;">First div element<div></div>
</div><br/>
<div style="border : 1px solid Black;">Second div element with two paragraphs
<p>First <b>p</b></p>
<p>Second p</p>
</div>
<p style="border : 1px dotted Black;">This is a paragraph but it is not a div child</p>
</body>
</html>

Popular Posts