Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, January 4, 2013

How to return a page before current

To create a link "Back" that allow come back to previous page before current, I use a variable called $_SERVER['HTTP_REFERER']. Hereafter, you will see a example:

...
<body>
  ...
  <a href="<?php echo $_SERVER['HTTP_REFERER']?>">Back</a>
  ...
</body>
...

Be careful when you refresh the page!

Monday, July 23, 2012

Set index.php as default page

I was programming a Web app and I noticed that always insert address of Web app, I had to type "www.mywebapp.com/index.php" to show up a web page. If I just type the next address "www.mywebapp.com", the Web server (Apache) list the directories and some files.

I would rather type "www.mywebapp.com" and same time the Web server show up the index.php. But how can I do that? Just follow the next steps:

  1. Open notepad and write the next statement "DirectoryIndex index.php"
  2. Save file as
    • Write name of file as ".htaccess"
    • Change type of file from " Text file (*.txt)" to "All files (*.*)"

Note: You must save the file on the same folder where is "index.php". If you don't save on the same folder, it will not work correctly.

Conclusion: The DirectoryIndex command allows specify a default page to display.

Friday, June 1, 2012

Decoding sign Euro in HTML & PHP


Probably you had a problem to show a Euro sign on a web page like on the next figure.


Code source:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title></title>
    </head>
    <body>
        <?php
        $str = "Price: 99,99€";
        echo htmlentities($str)."<br />";
        echo html_entity_decode($str)."<br />";
        ?>
    </body>
</html>


It happens because web page can have a charset setted UTF-8  (<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">or a ISO-8859-1 (<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">). 
To show correctly sign Euro, you must set charset ISO-8859-15 (<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15">) as you can see next picture.


Besides you set charset ISO-8859-15, you must use PHP function html_entity_decode(string) but must not use PHP function htmlentities(string).




Monday, May 28, 2012

How to create Graphs using HTML5

To develop a small web application, I would like to use the data of students' grades and translate it into a graph bar.  But how can I do that?

With HTML5, using tag <canvas>, it is possible create a graph bar without third part software. The first thing to do is write some functions in JavaScript. Before you copy code, you have to understand the coordinates on Canvas. The next figure show how coordinates are designed. It is not the same of what we learned on Math classes.


JavaScript code:

<script type="text/javascript">


        function drawLine(context,startX,startY,endX,endY,color){
            context.beginPath();
            context.moveTo(startX,startY);
            context.lineTo(endX,endY);
            context.closePath();
            context.strokeStyle=color;
            context.stroke();
        }


        function drawRectangle(context,startX,startY,width,height,fill){
            context.beginPath();
            context.rect(startX,startY,width,height);
            context.closePath();
            context.stroke();
            if(fill) context.fill();
        }


        function clearCanvas(context){
            // Store the current transformation matrix
            context.save();
            // Use the identity matrix while clearing the canvas
            context.setTransform(1, 0, 0, 1, 0, 0);
            context.clearRect(0, 0, myCanvas.width, myCanvas.height);
            // Restore the transform
            context.restore();
        }


        function drawBarChart(context,data,startX,startY,endX,
endY,chartHeight,barWidth,markDataIncrementsIn,scale){
            //draw x-axis
            drawLine(context,startX,startY,endX,startY,"#000");
            //draw y-axis
            drawLine(context,startX,startY,startX,endY,"#000");


            var maxValue=0;
            for(var i=0;i<data.length;i++){
                //extract data
                var values = data[i].split(",");
                //column name
                var name=values[0];
                //column value
                var height=parseFloat(values[1])*scale;
                //find maximum value
                if(parseInt(height)>parseInt(maxValue)) maxValue=height;
                //write data to chart
                //fill rectangle with yellow color
                context.fillStyle="#ff0";
                drawRectangle(context,startX+(i*barWidth*2),(startY-height),barWidth,height,true);
                //add column title to x-axis
                context.textAlign="left";
                //text color is black
                context.fillStyle="#000";
                context.fillText(name,startX+(i*barWidth*2),(chartHeight-25),barWidth*2);
            }


            //add some data markers to y-axis
            var numMarkers = Math.ceil(maxValue/parseInt(markDataIncrementsIn));
            context.textAlign="right";
            context.fillStyle="#000";
            var markerValue=0;
            for(var i=0;i<=numMarkers;i++){
                context.fillText((markerValue/parseInt(scale)),(startX-5),(startY-markerValue),50);
                if(i==0){
                    drawLine(context,startX,(startY-markerValue),endX,(startY-markerValue),"#000");
                }else{
                    drawLine(context,startX,(startY-markerValue),endX,(startY-markerValue),"#00f");
                }
                markerValue+=parseInt(markDataIncrementsIn);
            }
        }


        function graph(scale){
            var s=0;
            var changed=false;
            document.getElementById("range").innerHTML=scale;
            if(scale==undefined){
                s=1;
                changed=false;
            }else{
                s=scale;
                changed=true;
            }
             
            var graphCanvas = document.getElementById("myCanvas");
            //ensure that element is available within DOM
            if(graphCanvas && graphCanvas.getContext){
                //open a 2d context within canvas
                var context = graphCanvas.getContext("2d");
                //bar chart data
                var data = new Array(5);
                data[0]="Bad,2";
                data[1]="Mediocre,0.45";
                data[2]="Sufficient,5.5";
                data[3]="Good,7.2";
                data[4]="Excelent,3.9";
                //draw bar chart
                if(!changed){
                    drawBarChart(context,data,35,560,750,50,myCanvas.height,30,s,s);
                }else{
                    //clear canvas to redrawing
                    clearCanvas(context);
                    //draw bar chart
                    drawBarChart(context,data,35,560,750,50,myCanvas.height,30,s,s);
                    
                }
            }
            return true;
        }
    </script>

The second thing to do is write some HTML tags.

<body onload="graph(1);">
        <div id="title">Grades</div>
        <table>
            <tr>
                <td><canvas id="myCanvas" width="800" height="600"></canvas><td>
            <td>
                <table>
                    <tr>
                        <td>Scale : <span id="range">1</span></td>
                    </tr>
                    <tr>
                        <td><input type="range" min="1" max="501" value="1" onchange="return graph(this.value)"/></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>


The third thing to do is write CSS.

<style type="text/css">
            #title{
                text-align: center;
            }
</style>

Now put together all three parts on a single page or you can create a file to JavaScript and another to CSS and then link them on HTML page. How you can do that? Copy the next code and you can change name files.

<head>
  <link rel="stylesheet" type="text/css" href="style.css" />
  <script type="text/javascript" src="functions.js"></script>
</head>



Attention
All this code is working on Google Chrome. Also works on Safari and Opera. If you will use Internet Explorer, you will have problems. For example, you can not use slide bar and you have to type a value instead.

Tuesday, January 10, 2012

How to create a Word document with HTML & PHP

This post will explain how to create a Word document without third party software. The code will create a page with orientation landscape, view print and zoom 90% using HTML and PHP statements. 
Please ignore the page #2 after you have created a document Word.


HTML & PHP

<html
    xmlns:o='urn:schemas-microsoft-com:office:office'
    xmlns:w='urn:schemas-microsoft-com:office:word'
    xmlns='http://www.w3.org/TR/REC-html40'>
    <head>
        <title>Generate a document Word</title>
        <!--[if gte mso 9]-->
    <xml>
        <w:WordDocument>
            <w:View>Print</w:View>
            <w:Zoom>90</w:Zoom>
            <w:DoNotOptimizeForBrowser/>
        </w:WordDocument>
    </xml>
    <!-- [endif]-->
    <style>
        p.MsoFooter, li.MsoFooter, div.MsoFooter{
            margin: 0cm;
            margin-bottom: 0001pt;
            mso-pagination:widow-orphan;
            font-size: 12.0 pt;
            text-align: right;
        }


        @page Section1{
            size: 29.7cm 21cm;
            margin: 2cm 2cm 2cm 2cm;
            mso-page-orientation: landscape;
            mso-footer:f1;
        }
        div.Section1 { page:Section1;}
    </style>
</head>
<body>
    <div class="Section1">
        <h1>Hello World!</h1>
    <br clear=all style='mso-special-character:line-break;page-break-after:always' />
    <div style='mso-element:footer' id="f1">
        <p class=MsoFooter>
            Page <span style='mso-field-code:" PAGE "'></span>
        </p>
    </div>
</body>
</html>
<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=HelloWorld.doc");
?>






Tuesday, December 6, 2011

Using PHP and XSLT to Create a Word 2007 Document

You can use XSL Transformations (XSLT) to transform XML data into the Microsoft Office Open XML SDK 2.0 format that is used by Microsoft Office Word 2007, and make new Word 2007 documents from XML data. You can simplify transforming XML data into a Word 2007 document by starting with an existing Word 2007 document that has the desired layout.

Link

<a href="http://www.microsoft.com/?videoId=8184743c-dc7d-487a-bff5-b370b3c1f024&amp;from=mscomoffice&amp;src=v5:embed::" target="_new" title="Using PHP to Create Word 2007 Documents">Video: Using PHP to Create Word 2007 Documents</a>

Monday, October 31, 2011

Convert dates in PHP and MySQL

Today I was working in project and I was confronted by one problem. As I live in Europe, the date's format are not the same in United States even MySQL. US use mm/dd/yyyy format, Europe use dd/mm/yyyy and MySQL use yyyy-mm-dd.


After I researched on PHP and MySQL official sites, I wrote algorithms that allowed me insert correctly data in SQL. 


PHP to MySQL:


SQL:


create schema test;


create tabela xpto(
id int not null auto_increment,
start_date date,
end_date date,
primary key(id)
)engine=innodb;




PHP:
<?php
$start_date = "10/10/2011";
$end_date = "12/10/2011";


$query0 = "select str_to_date('$start_date','%d/%m/%Y')";
$result0 = mysql_query($query0) or die(mysql_error());
$row0 = mysql_fetch_array($result0);


$query1 = "select str_to_date('$end_date','%d/%m/%Y')";
$result1 = mysql_query($query1) or die(mysql_error());
$row1 = mysql_fetch_array($result1);


$query2 = "insert into xpto (start_date, end_date) values ('".$row0[0]."','".$row1[0]."')";
$result2 = mysql_query($query2) or die(mysql_error());
?>


To check out the data inserted, type on mysql terminal:
select * from xpto;


MySQL to PHP:
It is enough select data stored and use two functions to show date format correctly.




PHP:
<?php
mysql_connect("localhost","user","pass") or die (mysql_error());
mysql_select_db("test");


$query0="select start_date from xpto where id=1";
$result0 = mysql_query($query0) or die (mysql_error());
$row0 = mysql_fetch_array($result0,MYSQL_NUM);



$query1="select end_date from xpto where id=1";
$result1 = mysql_query($query1) or die (mysql_error());
$row1 = mysql_fetch_array($result1,MYSQL_NUM);


$start_date=$row0[0];//"2011-10-10"
$end_date=$row1[0];//"2011-10-12"


$d0 = strtotime($start_date);
$d1 = date('d/m/Y',$d0);
echo $d1."<br />";


$d2 = strtotime($end_date);
$d3 = date('d/m/Y',$d2);
echo $d3."<br />";
?>


Happy Halloween! :)

Saturday, October 22, 2011

How to install osCommerce

osCommerce (open source Commerce) is an e-commerce and can be used on web server that has PHP and MySQL installed. You can simply download on this site. After you download, you have to unzip and copy to a folder on web server.

The goal of this post is show you how to install osCommerce. I am installing on a virtual machine that works like a web server (LAMP) to simulate real scenario of installation osCommerce.

If you don't know install or configure a web server on Ubuntu, please read this post or see this video.

If you already installed LAMP, please following the next steps to install:


  1. Go to this site and download "oscommerce-2.3.1.zip";
  2. Unzip "oscommerce-2.3.1.zip";
  3. Copy to web server ;
  4. Step #3

  5. Check out the copy;
  6. Step #4

  7. Modify the permissions on specific folders;
  8. Step #5

    Step #5

  9. After modifying the permissions, will show up  the next screen. Press the button "Continue";
  10. Step #6

  11. It will show up a form where you have fill with right values. But I didn't create a database yet. For that, I went to terminal and typed "mysql -h localhost -u root -p" to login MySQL Server. And then, I created database called "oscommerce" with next command: "create schema oscommerce". Finish! Now you can fill form like you can see in third image.

    Note: I made a mistake to input "192.168.1.199" instead a right IP address which is localhost or 127.0.0.1.

  12. Step #7

    Step #7

    Step #7

  13. I agreed with those values by default. If you want to change, you are comfortable to change.
  14. Step #8

  15. The next form is about your online store. You have to give information like your online store name, owner name, owner email address, administrator username and administrator password.
  16. Step #9

  17. Please read the post-installation notes. It is very important follow the steps to finish the installation.
  18. Step #10

  19. The next image will demonstrate you how to set permissions on step #3 and #4 according the previous image.
  20. Step #11

  21. Then, type in your browser: http://localhost/oscommerce/catalog/admin. This address will drive at administrator page where you have insert administrator username and password.
  22. Step #12

  23. Follow the path Administration Tool -> Tools -> Security Directory Permissions. This page will list permissions that you have change to with command "chmod 777 ..." like you can see in first image. After you changed permissions, press F5 to reload page to see values changed. Finish! You already finished the part of administration. Now let see the online store.
  24. Step #13

    Step #13

  25. Type "http://localhost/oscommerce-2.3.1/catalog/" and press Enter. Voilá! Congratulations! You installed your online store!
  26. Step #14


And now you can do anything with your online store and sell anything. Good luck for your sales!







Tuesday, April 12, 2011

How to configure snmpd


Continuing the installation of Cacti, you need do some configuration on another machines. Without doing this configuration, an error message will show up when you try create a device. Please click on this link to see how to do.

Friday, April 8, 2011

How to install Cacti

Cacti has some prerequisites. You need to install these packages before install Cacti:
  • RRDTool;
  • NET-SNMP;
  • MySQL;
  • PHP;
  • Apache;
You will also need to install some other packages for support. To see a video that show you how to install Cacti, please click this link or you can read the tutorial below.

Apache

Open a terminal and follow the next steps:
  1. sudo apt-get install apache2
After the installation is complete, open http://localhost in your favorite browser. If everything goes fine, you will see It Works! on the top.

PHP

Now that your web server is ready, we will install PHP. Open a terminal and follow the next steps:
  1. sudo apt-get install php5 libapache2-mod-php5
  2. sudo /etc/init.d/apache2 restart
  3. sudo gedit
  4. write the following PHP code:
    1. <?php phpinfo();?>
  5. save file as info.php in  /var/www folder
  6. open your favorite browser and type http://localhost/info.php.
MySQL

Enter the following command:
  1. sudo apt-get install mysql-server-5.0 php5-mysql
  2. type your password (e.g.: root)
  3. sudo /etc/init.d/apache2 restart
  4. open http://localhost/info.php in your favorite browser and check MySQL module.
Great!!! Now you have a LAMP (Linux, Apache, MySQL, PHP) configured system.

Net-SNMP

Open terminal and type the following commands:
  1. sudo apt-get install snmp php5-snmp
  2. sudo /etc/init.d/apache2 restart
  3. Open http://localhost/info.php in your favorite browser and check SNMP module
RRDTool

RRDTool is available in the Debian repository, so you can install it through APT. Type in your terminal
  1. sudo apt-get install rrdtool
Cacti

Before continuing, be sure that you got no error previously. You are in the last step of installing Cacti.
  1. sudo apt-get install cacti
  2. select option 'apache2'
  3. type your password of the database's administrative user (e.g.: root)
  4. type your MySQL application password for cacti and retype in password confirmation (e.g.: root)
  5. To complete the configuration process, open http://localhost/cacti in your favorite browser. 
In the installation type page, you can select if it's new install  or an upgrade. As we are going to install it for the first time, we will select New Install (which is selected by default) and click Next. The path settings page automatically determines the installed paths for RRDTool, PHP, SNMP and Cacti.log as well as the versions for Net-SNMP and RRDTool and then click Next.
In login screen, the username is admin and the default password is admin. After a successful login for the first time, the system will ask you to set a new password. Enter a new password and ensure you remember it. Without this password, you cannot administer the system!

Friday, April 1, 2011

How to install plugin PHP in Netbeans

A month ago, I installed NetBeans trough Linux Ubuntu's terminal with following command: sudo apt-get install netbeans. After the instalation is completed, I noticed that I can't create PHP project. So I was searching on Net and I found out how to solve the problem. In Netbeans, was missing plugin PHP. To see how to install plugin PHP, please click this link.

Thursday, March 31, 2011

php MyAdmin

Unfortunately I haven't had time to write more posts. Recently I installed phpMyAdmin and you can click this link to see how to install.

If you don't want use phpMyAdmin, you can use MySQL Workbench. With this link you can use to download, install and use it. Sorry, I don't have video to show how to install MySQL Workbench but I think that is not really difficult to install.

Saturday, March 12, 2011

PHP5, MySQL and APACHE

I created a web application (PHP) that show the data stored in MySQL's database.
 

The materials needed are:
PHP, MySQL and Apache

Clicking this link (video) that can show how to install php, mysql and apache or following the next steps:

  1. Type 'sudo apt-get install mysql-server mysql-client;'
  2. Type 'y' when appears the question to install;
  3. Note: you have type password to user root.
  4. After the installation is finished, type 'sudo apt-get install php5' (in my case, apache was selected to install automatically)
  5. Type 'y' when appears the question to install;
  6. To check out if the web server apache is working, go to any browser and type 'http://localhost' in address bar;
  7. If  web server apache is not working, type 'sudo apt-get install apache2'
  8. Type 'y' to install apache2 web server;
  9. Congratulations, you finished the installation with success!