Posts Tagged ‘web hosting’


How To Create a File With PHP And Write Content To It

One of my tasks for a project was to create an XML file with simple XML fields to be able to index content in to a Solr Search Core.

So today I will teach you how to create an file with php and write content to it.

Lets get started.

Step 1

Write a function / method that will create the file and write content to it.

function my_file_writer($filename){

// Code goes here
}
Step 2

In this step I want to grab content from my mysql database tables.

function my_file_writer($filename){

// connect to db.
 echo "connecting...
 ";
$con = mysql_connect("localhost","username","password");
 if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }
mysql_select_db("database_name", $con) or die('Could not connect: ' . mysql_error());
echo "Connected
 ";
// select  latest articles.
 echo "Selecting data...
 ";
$result = mysql_query("SELECT id, title, content FROM table") or die('Could not select data: ' . mysql_error());
echo "Selected
 ";
}
Step 3

Here we are going to add a while loop to grab the mysql data we selected and put it into the right format for writing it to our file.

function my_file_writer($filename){

// connect to db.
 echo "connecting...
 ";
$con = mysql_connect("localhost","username","password");
 if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }
mysql_select_db("database_name", $con) or die('Could not connect: ' . mysql_error());
echo "Connected
 ";
// select  latest articles.
 echo "Selecting data...
 ";
$result = mysql_query("SELECT id, title, content FROM table") or die('Could not select data: ' . mysql_error());
echo "Selected";
$stringData = ""; // we put the first part of the $stringData variable outside the loop
 while($row = mysql_fetch_array($result))
 {
// set variables
 $page_id = $row['id'];
 $page_url = $row['url'];
 $pagetitle = $row['title'];
$bodytext = $row['content'];
 $bodytext = strip_tags($bodytext); // Here we strip all html tags from the body text
$stringData .= "
 $page_id
http://your-url-here.com/pagename
 $pagetitle
 $bodytext
\n\n";
} // end of while loop
$stringData .= ""; // we put the final part of the $stringData variable at the end outside of the while loop
}
?>
Step 4

In this step we start creating and writing to the file.

$fh = fopen($filename, 'w'); // we create the file, notice the 'w'. This is to be able to write to the file once.

 fwrite($fh, $stringData); // here we write the data to the file.
 echo "Writing file...
 ";
echo "Closing file...
 ";
 fclose($fh); //here we close our file
echo 'Finished!';
Step 5

all thats left to do is to close the mysql connection.

mysql_close($con); // close the connection

Step 6

Now you can create your file and run the script.

my_file_writer("Your_File_Name.xml");

Conclusion

As you can see it’s really easy to create a file and add any content you want to it. You should be able to see a file with the name you gave it after you ran your script. Any suggestion is welcome.


PHP API Development: Dreaming Of Your Own API? Make It Possible Today!

I have often dreamed of creating an API for one of my sites but I’ve always set it aside as I thought it would be too much work to do. One day I just decided it’s time to do the research and get started with building my own API and it wasn’t as difficult as I thought.

So you are probably eager to start with this one? OK I’ll show you how!

First thing, you need to have a database in place with data. I’m not going to show you how to build a database with tables as it’s one of the basics you need to know. I’m sure most of you are past the basics.

The first part of the code

if($_GET['q'] == "all" && $_GET['type'] == 'json'){

//get a connection to mysql
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());
//run a while loop get your data.
while($place = mysql_fetch_array($result, MYSQL_ASSOC)) {
$places[] = array('location'=>$place);
}
$output = json_encode(array('map' => $places));
echo $output;
mysql_close($con);
}

First off we select all data from our database. You can set search criteria for different results for example for getting particular users details from your social network, but in this example we select everything.

In the example above I select all data from my android maps app database for locations and places. We then do some JSON encoding to put the data in the correct format. All you need to do to use the output data is to grab it and use a JSON decode method

The output of the data in JSON format.

{“map”:[{“location”:{“idgmaps”:”15″,”lat”:”-25.926813935317035″,”lon”:”27.828453713378963″,”address”:”cradle of human kind”,”title”:”Cradle of Humankind”,”description”:”The 47 000-hectare Cradle of Humankind is blessed with a greater wealth of early human history than almost any other place on earth. \r\n\r\nThe Cradle contains more than twelve major fossil sites and dozens of minor ones. The Maropeng Visitors Centre at the Cradle of Humankind (near Johannesburg) was opened in 2005. The tumular building is designed to look like an ancient burial mound, though from the rear it looks like a modern structure. \r\n\r\nInside, a journey through the evolution of life is presented, and the architecture is symbolic of this journey. Maropeng means returning to the place of origin in Setswana, the local indigenous language. It is a reminder that the ancestors of all humans, wherever they live today, originally came from Africa.”,”tags”:”Maropeng, Cradle of Human Kind, Early Humans”,”idurls”:”17″,”url_name”:”Early humans”,”url”:”http:\/\/newhistory.co.za\/part-1-chapter-1-early-humans\/”}}

 

The second part of the code

In this part we switch the data format to output XML.

elseif($_GET['q'] == "all" && $_GET['type'] == 'xml'){

//get a connection to mysql
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());
//run a while loop get your data.
while($location = mysql_fetch_array($result)) {
$output = '<?xml version="1.0" encoding="utf-8"?>';
$output .= '<data>';
$output .= "<lat>".$location['lat']."</lat>";
$output .= "<long>.".$location['lon']."</long>";
$output .= "<description>.".$location['description']."</description>";
$output .= '</data>';
print $output;
}
mysql_close($con);
}else{
echo "<h1>No results to show for you query</h1>";
}

The second par t of the code we switched over to XML output. The only big difference is the elseif and the XML tags I added in the while loop.

Here’s the complete code.

<?php

if($_GET['q'] == "all" && $_GET['type'] == 'json'){
//get a connection to mysql
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());
//run a while loop get your data.
while($place = mysql_fetch_array($result, MYSQL_ASSOC)) {
$places[] = array('location'=>$place);
}
$output = json_encode(array('map' => $places));
echo $output;
mysql_close($con);
}elseif($_GET['q'] == "all" && $_GET['type'] == 'xml'){
//get a connection to mysql
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result2 = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());
//run a while loop get your data.
while($location = mysql_fetch_array($result2)) {
$output = '<?xml version="1.0" encoding="utf-8"?>';
$output .= '<data>';
$output .= "<lat>".$location['lat']."</lat>";
$output .= "<long>.".$location['lon']."</long>";
$output .= "<description>.".$location['description']."</description>";
$output .= '</data>';
echo $output;
}
mysql_close($con);
}else{
echo "<h1>No results to show for you query</h1>";
}
?>
Hope you enjoyed this tutorial. Please leave a comment, let me know what you think?

Appending data to a MySQL database field that already has data in it

Need to “add” data to a field that already contains data without erasing whats currently there. For example if the field contains HTML, I need to add additional HTML to the field. Is there a SQL call that will do this or do I need to call the data in that field, concatenate the new data to the existing data, and reload it into the database?

Yes you can use the following query to append data to database field.

UPDATE Table SET Field=CONCAT(Field,'your extra html');
and you can also do it with specific where condition
UPDATE myTable SET html=concat(html,'<b>More HTML</b>') WHERE id='10' 


CSS Triangle

HTML

You can make them with a single div. It’s nice to have classes for each direction possibility.

<div class="arrow-up"></div>
<div class="arrow-down"></div>
<div class="arrow-left"></div>
<div class="arrow-right"></div>

CSS

The idea is a box with zero width and height. The actual width and height of the arrow is determined by the width of the border. In an up arrow, for example, the bottom border is colored while the left and right are transparent, which forms the triangle.

.arrow-up {
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;

        border-bottom: 5px solid black;
}

.arrow-down {
        width: 0;
        height: 0;
        border-left: 20px solid transparent;
        border-right: 20px solid transparent;

        border-top: 20px solid #f00;
}

.arrow-right {
        width: 0;
        height: 0;
        border-top: 60px solid transparent;
        border-bottom: 60px solid transparent;

        border-left: 60px solid green;
}

.arrow-left {
        width: 0;
        height: 0;
        border-top: 10px solid transparent;
        border-bottom: 10px solid transparent; 

        border-right:10px solid blue;
}


Save your website bandwidth with PHProxy and ip2nation
What is ip2nation?

There is currently numerous companies on the net charging for databases or files containing knowledge about where an IP is apportioned (as in which country). This knowledge is in fact obtainable free at ARIN, APNIC, RIPE etcetera. Though, those files are not in any way optimized for queries & are indeed very slow. This is where ip2nation.com comes in.

We utilitize these files to generate a MySQL database table with the appropriate indexes. We have also optimized the table & removed unneccesary information in order to make queries lightning speedy. In order to utilitize the table you may find help in the PHP examples under “Sample scripts”.

What is PHPProxy?

PHProxy is a web HTTP proxy programmed in PHP meant to bypass firewalls and access otherwise inaccessible resources (i.e. blocked sites). If the server this script is run on can access a resource, so are you able to!

With the proxy script PHProxy and the information IP location database from ip2nation it is simple to block visitors which are coming from other countries then your target group. In this tutorial you will learn how to add the necessary code to your PHProxy powered proxy web-site.

Step 1

Download ip2nation and import the sql file into your database (test).

Step 2

Download PHPProxy and add the following code to the index.php file

$DBHOST = 'localhost';
$DBUSER = 'user';
$DBPASS = 'password';
$DATABASE = 'test';
$my_countries = array('in', 'us');
$use_ip2nation = true; //true for blocking countries

Step 3

Find the following code in index.php

function proxify_css_url($url)
{
$url = trim($url);
$delim = strpos($url, ‘”‘) === 0 ? ‘”‘ : (strpos($url, “‘”) === 0 ? “‘” : ”);

return $delim . preg_replace(‘#([\(\),\s\'”\\\])#’, ‘\\$1’, complete_url(trim(preg_replace(‘#\\\(.)#’, ‘$1’, trim($url, $delim))))) . $delim;
}
Add the following code after that to check if the resulting country is in our list or not. if its in our list it will go ahead.

if ($use_ip2nation) {
$db = mysql_connect($DBHOST, $DBUSER, $DBPASS);
mysql_select_db($DATABASE);
$sql = "SELECT country FROM ip2nation WHERE ip < INET_ATON('".$_SERVER['REMOTE_ADDR']."') ORDER BY ip DESC LIMIT 0,1";
$res = mysql_query($sql);
$country = mysql_result($res, 0, 'country');
mysql_free_result($res);
if (!in_array($country, $my_countries)) {
show_report(array('which' => 'index', 'category' => 'error', 'group' => 'resource', 'type' => 'otherthan_in_us'));
}
}

Step 4

Add the following code in index.inc.php.

$show_web_form = true;

Find the following code index.inc.php (near line 83)

case ‘hotlinking’:
$message = ‘It appears that you are trying to access a resource through this proxy from a remote Website.<br />’
. ‘For security reasons, please use the form below to do so.’;
break;

Add the following code after that

case 'otherthan_in_us':
$message = 'Sorry this service is only for india and us.
Click topsite in the footer part.';
$show_web_form = false;
break;

Add the following code to allow user to view form or not before starting of <form> tag in index.inc.php

if ($show_web_form) {

and add this code after </form> tag to show alternate stuff to user.

} else {
// show custom content for blocked user to tell that they are blocked for the content
};

 


Tutorial: Create a zip file from folders on the fly

Sometimes in web programming when dealing with multiple files or directory download operations, it is better to serve the user with a single zip file rather than let the user manually download the file one by one using direct link download . To overcome this problem, we have to create a zip file on the fly without have to manually create it using any commpresion tools or softwares.

PHP has some functions dealing with file compression that enables us to create zip file on the fly. In this tutorial i will use PHP CreateZipFile classs package from Rochak Chauhan. I have made some examples below to explain how to craete zip file on the fly from multiple files or directory.

Example 1, create zip file from existing files:

<?php

include_once 'CreateZipFile.inc.php';
$createZip = new CreateZipFile;
$createZip->addDirectory('/');
$filecontent1 = file_get_contents('fileone.txt');
$filecontent2 = file_get_contents('filetwo.txt');
$createZip->addFile($filecontent1, '/fileone.txt');
$createZip->addFile($filecontent2, '/filetwo.txt');
$zipFileName = 'myzip.zip';
$handle       = fopen($zipFileName, 'wb');
$out           = fwrite($handle, $createZip->getZippedFile());
fclose($handle);
$createZip->forceDownload($zipFileName);
@unlink($zipFileName);
?>
To create zip file:
  • add a directory into zip file using addDirectory method
  • add files into directory using addFile method
  • create zip file temporary for download and delete it after the file is downloaded
Example 2, create zip file for a directory with it’s contents/subdirectories
<?php

include_once 'CreateZipFile.inc.php';
$createZip = new CreateZipFile;
$createZip->zipDirectory('/testdir', '');
$zipFileName = 'myzip.zip';
$handle       = fopen($zipFileName, 'wb');
$out           = fwrite($handle, $createZip->getZippedFile());
fclose($handle);
$createZip->forceDownload($zipFileName);
@unlink($zipFileName);
?>
To create zip file for a directory, use zipDirectory method that takes two arguments, first is the name of directory that want to be zipped and second is directory name for zipped file.

Oradour-sur-Glane: The Village Massacred in WW2 and Preserved Since Then

On 10 June 1944, at around 2 PM, four days after the Allied invasion of Normandy, approximately 150 Waffen-SS soldiers entered the tranquil village of Oradour-sur-Glane in the Limosin region of south central France. For no apparent reason, Hitler’s elite troops destroyed every building in this peaceful village and brutally murdered a total of 642 innocent men, women and children, a tragedy which has gone down in history as one of the worst war crimes committed by the German army in World War II.

A new village of Oradour-sur-Glane was built after the war, at the northwest of the site of the massacre, where ruined remnants of the former village still stand as a memorial to the dead and a representative of similar sites and events. Its museum includes items recovered from the burned-out buildings: watches stopped at the time their owners were burned alive, glasses melted from the intense heat, and various personal items and money.

To this day there is no universally agreed explanation as to why the SS acted as they did, or why they chose Oradour for their attack. The town had been far from any center of conflict, was not, nor had ever been an active resistance stronghold.

There is one theory has to what may have happened. On June 9, 1944, the day before the massacre, a German office named Helmut Kämpfe was kidnapped by the Resistance and taken to Breuilaufa by way of Limoges where he was killed the same day. Whilst he was being driven through Limoges, Kämpfe managed to throw his personal papers out of the vehicle as a clue to his whereabouts; they were found and handed in to his commanding officer Sylvester Stadler.

The same day, another officer, Karl Gerlach and his driver were kidnapped by the Resistance and might have been taken to Oradour-sur-Vayres, about 35 miles away to the south of Oradour-sur-Glane. The two towns are very similar in appearance and Gerlach might have mistaken Oradour-sur-Glane for Oradour-sur-Vayres. Gerlach managed to escape and he report to Stadler what had happened.

Sylvester Stadler believed that the kidnapped officer Kämpfe was being held prisoner at Oradour-sur-Glane. He ordered Adolf Diekmann and his soldiers to proceed to Oradour-sur-Glane and take about thirty villagers hostages to negotiate the release of Helmut Kämpfe. Diekmann instead ordered the population exterminated and the village burned to the ground.

Stadler felt Diekmann had far exceeded his orders and began a judicial investigation. Diekmann was killed in action shortly afterward during the Battle of Normandy, and a large number of the third company, which had committed the massacre, were themselves killed in action within a few days, and the investigation was suspended.

The massacre at Oradour-sur-Glane was not the only collective punishment reprisal action committed by the Waffen SS: other well-documented examples include the French towns of Tulle, Ascq, Maillé, Robert-Espagne, and Clermont-en-Argonne; the Soviet village of Kortelisy (in what is now Ukraine); Lithuanian village of Pirčiupiai; the Czechoslovakian villages of Ležáky and Lidice (in what is now the Czech Republic); the Greek towns of Kalavryta and Distomo; the Dutch town of Putten; Serbian towns of Kragujevac and Kraljevo; Norwegian village of Telavåg; and the Italian villages of Sant’Anna di Stazzema and Marzabotto. Furthermore, the Waffen SS executed hostages (random or selected in suspect groups) throughout France as a deterrent to resistance.

This slideshow requires JavaScript.

Photo creditPhoto creditPhoto creditPhoto creditPhoto creditPhoto creditPhoto creditPhoto creditPhoto creditPhoto creditPhoto credit