PHP - XML - "API"?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
crisstina
Forum Newbie
Posts: 4
Joined: Wed Apr 14, 2010 11:02 pm

PHP - XML - "API"?

Post by crisstina »

Hello Devnetwork users,

I need to test the communication between several workstations using a browser, with what I call right now an "API".

Here's what I've done so far:
USING PHP
1) Upload a picture form. Write a name for the picture
2) When user uploads the picture, the app renames the file to the one given by the user, and then generates an XML with the name of the file, the ip of the workstation, and the image itself in base64.
3) The XML is saved on a /xml folder with "name.xml"
4) The image is saved on a /image folder with "name.xxx" (xxx = jpg, gif...etc)

The PHP shows (after submission):
- XML content
- name an folders where the files were saved.


SO... Now the "API" comes to work, and this is where I am stuck...

5) The PHP app should alert the "API" to pick up the /xml/name.xml .
6) The "API" should read the alert, and pick up the file.
7) The "API" will check the xml, if it is "understandable" and then return a "Flag" to the PHP app
8) The PHP app should display in the screen, the response of the "flag" after showing the XML content.


So, my questions are:
a) Should I use PHP as the "API"? I tried with http-request but I noticed it is now disabled in PHP 5.3.1
b) What other programming language do you suggest?
c) If this is not an "API" how would you call it?
Keep in mind that the "API" receives an xml, and returns a positive or negative answer, but doesn't interact directly with the user.


Thank you all for your valuable help!!!
crisstina
Forum Newbie
Posts: 4
Joined: Wed Apr 14, 2010 11:02 pm

Re: PHP - XML - "API"?

Post by crisstina »

Here's the code I have created so far...

Code: Select all

<?php
//define a maxim size for the uploaded images in Kb
require("nusoap.php"); 
define ("MAX_SIZE","200"); 
if(isset($_POST['Submit'])) 
{
		$nombre=$_POST['nombre'];
		$hostname = $_SERVER["REMOTE_ADDR"];
		$LineLength+= 5;
		//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
		 function getExtension($str) {
				 $i = strrpos($str,".");
				 if (!$i) { return ""; }
				 $l = strlen($str) - $i;
				 $ext = substr($str,$i+1,$l);
				 return $ext;
		 }
		
		//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)  
		//and it will be changed to 1 if an errro occures.  
		//If the error occures the file will not be uploaded.
		 $errors=0;
		//checks if the form has been submitted
		 if(isset($_POST['Submit'])) 
		 {
			//reads the name of the file the user submitted for uploading
			$image=$_FILES['image']['name'];
			//if it is not empty
			if ($image) 
			{
			//get the original name of the file from the clients machine
				$filename = stripslashes($_FILES['image']['name']);
			//get the extension of the file in a lower case format
				$extension = getExtension($filename);
				$extension = strtolower($extension);
			//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
			//otherwise we will do more tests
		 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
				{
				//print error message
					echo '<h1>Extension desconocida</h1>';
					$errors=1;
				}
				else
				{
		//get the size of the image in bytes
		 //$_FILES['image']['tmp_name'] is the temporary filename of the file
		 //in which the uploaded file was stored on the server
		 $size=filesize($_FILES['image']['tmp_name']);
		
		//compare the size with the maxim size we defined and print error if bigger
		if ($size > MAX_SIZE*1024)
		{
			echo '<h1>El tamano de la imagen es mayor al requerido</h1>';
			$errors=1;
		}
		
		//we will give an unique name, for example the time in unix time format
		//$image_name=time().'.'.$extension;
		$image_name=$nombre.'.'.$extension;
		//the new name will be containing the full path where will be stored (images folder)
		$newname="images/".$image_name;
		//we verify if the image has been uploaded, and print error instead
		$copied = copy($_FILES['image']['tmp_name'], $newname);
		if (!$copied) 
		{
			echo '<h1>Error en el proceso de copia</h1>';
			$errors=1;
		}}}}
		
		//If no errors registred, print the success message
		 if(isset($_POST['Submit']) && !$errors) 
		 { 		        
		 
			echo "<h1>Archivo cargado correctamente</h1>";
		 }
			/*Generar BASE 64 y anexarla al XML */
		

		 function encode_img($img)
				{
				$fd = fopen ($img, 'rb');
				$size2= filesize($img);
				$cont = fread ($fd, $size2);
				fclose ($fd);
				$encimg = base64_encode($cont);
				return $encimg;
				} 
				$encimg= encode_img($newname);	
		//Generación de XML
		
		  $xmlBeg = "<?xml version='1.0' encoding='ISO-8859-1'?>"; 
				$rootELementStart = "<$nombre>";
				$rootElementEnd = "</$nombre>";
				$xml_document=  $xmlBeg; 
				$xml_document .=  $rootELementStart;
				$xml_document .=  "<archivo>";
				$xml_document .=  $image_name;
				$xml_document .=  "</archivo>";
				$xml_document .=  "<nombre>";
				$xml_document .=  $nombre;
				$xml_document .=  "</nombre>";
				$xml_document .=  "<imagen>";
				$xml_document .=  $encimg;
				$xml_document .=  "</imagen>";
				$xml_document .=  "<ip>";
				$xml_document .=  $hostname;
				$xml_document .=  "</ip>";
				$xml_document .=  $rootElementEnd;
				$path_dir = "xml/";
				$path_dir .=   $nombre .".xml";
		
		/* Data in Variables ready to be written to an XML file */
		
		$fp = fopen($path_dir,'w');
		$write = fwrite($fp,$xml_document);
		
		/* Loading the created XML file to check contents */
		
		$elfile = simplexml_load_file("$path_dir");
		
		echo "<br> Chequeando el archivo <br>" .$path_dir. "<br>";
		echo "<br><br>Este es el archivo XML?<br>"; 
	//	print_r($elfile);
		echo "<br><br><br>"; 
	echo "<br><br>La imagen<br>"; 
	
	// Decodificar imagen para prueba
	//		<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." />
//Print '<img src="barchart_a.php?h1=' . $height1 . '&h2=' . $height2 . '&h3=' . $height3 . '">';
Print '<img src="data:image/' . $extension . ';base64,' . $encimg . ' width="90" height="49"/>';
echo ' <img
src="data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPb
WLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVr
ApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KT
kpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxM
AF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=
" alt="British Blog Directory" width="80" height="15" />';


}
else
{

 ?>

 <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
 <form name="newad" method="post" enctype="multipart/form-data"  action="" >
 <input type="hidden" name="create_xml" value="true">
 <table>
 	<tr><td><input type="file" name="image"></td></tr>
 	<tr><td><p>
 	  <label>
      <input type="text" name="nombre" id="nombre">
      <strong>Nombre</strong></label>
 	</p>
 	    <p>
 	      <input name="Submit" type="submit" value="Cargar Imagen">
          
    </p></td></tr>
 </table>	
</form>

<?
}

?>
Post Reply