Flash sending 2 variables to php script, 1 of them being xml - php

So this is probably a simple question, but for some reason, I'm having problems with it. I have no ideia why, but I suspect the fact that sending a xml with full "< something >" tags may cause the php to behave wrongly.
So all I need is to send (from a swf as3 client) a filename and a xml. The php will write a xml file with the required filename.
Everything should be okay with the php side, because I tried it using " $_GET " variables, but whenever I try using the flash client, It just doesent work, and the php log says that "the filename variable can't be empty". Whenever I try some static filename (not using GET or POST), it works.
Sooo... Can someone help me out with this one?
Thanks.
EDIT: Code added.
var xmlURLReq:URLRequest = new URLRequest("www.url.com");
var test:URLVariables = new URLVariables;
test.filename = "01.xml";
test.xmldata = xmltosave;
xmlURLReq.data = teste;
xmlURLReq.contentType = "text/xml";
xmlURLReq.method = URLRequestMethod.POST;
var xmlSendLoad:URLLoader = new URLLoader();
xmlSendLoad.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
xmlSendLoad.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
xmlSendLoad.load(xmlURLReq);
var alertBox:alertBoxClass = new alertBoxClass();
alertBox.x = 0;
alertBox.y = 200;
function onComplete(evt:Event):void
{
try
{
var xmlResponse = new XML(evt.target.data);
alertBox.alertText.text = "Inserção de dados bem sucedida!";
addChild(alertBox);
removeEventListener(Event.COMPLETE, onComplete);
removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
writeXML()
}
}
I also tried Object and LoadVars classes instead of URLVariables, no luck so far.
EDIT: Might as well add the php code as well.
<?php
$filename = "http://url.com/".$_POST["filename"];
$xml = $_POST["xmldata"];
$file = fopen($filename , "wb");
fwrite($file, $xml);
fclose($file);
?>

I see one possible problem in your code;
You are setting the data to a URLVariables instance, but the contentType to "text/xml". It should be "application/x-www-form-urlencoded" when using URLVariables.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html#contentType
Hope that solves it!

Related

PHP DomDocument failing to handle quotes in a url

When I try to open a url like that :
http://api.anghami.com/rest/v1/GETsearch.view?sid=11754134061397734622103190992&query=Can't Remember to Forget You Shakira&searchtype=SONG&ook&songCount=1
containing a quote with the browser everything works fine and the output is good as an xml
But when I try to call it from a php file:
$url = "http:/api.anghami.com/rest/v1/GETsearch.view?sid=11754134061397734622103190992&query=Can't Remember to Forget You Shakira&searchtype=SONG&ook&songCount=1"
//using DOMDocument for parsing.
$data = new DOMDocument();
// loading the xml from Anghami API.
if($data->load("$url")){// Getting the Tag song.
foreach ($data->getElementsByTagName('song') as $searchNode)
{
$count++;
$n++;
//Getting the information of Anghami Song from the XML file.
$valueID = $searchNode->getAttribute('id');
$titleAnghami = $searchNode->getAttribute('title');
$album = $searchNode->getAttribute('album');
$albumID = $searchNode->getAttribute('albumID');
$artistAnghami = $searchNode->getAttribute('artist');
$track = $searchNode->getAttribute('track');
$year = $searchNode->getAttribute('year');
$coverArt = $searchNode->getAttribute('coverArt');
$ArtistArt = $searchNode->getAttribute('ArtistArt');
$size = $searchNode->getAttribute('size');
}
}
I get this error:
'Warning: DOMDocument::load(): I/O warning : failed to load external entity /var/www/html/http:/api.anghami.com/rest/v1/GETsearch.view?sid=11754134061397734622103190992&query=Can't Remember to Forget You Shakira&searchtype=SONG&ook&songCount=1" in /var/www/html/search.php on line 93'
Can anyone help please?
#Fracsi is correct: the URL needs to start with http:// not http:/
The other problem is that the XML has a default namespace (defined with the xmlns attribute on the root element), so you need to use
$data->getElementsByTagNameNS('http://api.anghami.com/rest/v1', 'song')
to select all the "song" elements.

Passing from Javascript canvas image info AND some vars to PHP

First of all, sorry for my bad English, I'm Italian. I'm a bit new to programming, but for my office I need to create script that's a bit complex (at least for me). Before explaining the problem i'll explain what i'm doing.
I scripted a canvas that creates an image from data input, then i send the image data to php for the saving process. The problem is that i need to send also an value of 1 of the js vars (in the example value1). I can't figure out how to pass this information together with the raw image data.
The js code for the img drawing and saving. i need to pass the value1 to the save.php
button.addEventListener("click",function(){
//saving the values of the form
var value1 = document.getElementById("value1").value;
//text on the canvas
var value1X = (maxWidth-ctx.measureText(value1).width)/2+500;
//drawing the inputed text on the canvas
ctx.drawImage(img,0,0);
ctx.fillText(value1,value1X,maxHeight);
//getting the image url and sending it to save.php for the saving process
var imageURL = c.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
}, false);
Here is the PHP file:
<?php
if (isset($GLOBALS[HTTP_RAW_POST_DATA])) {
$imageData = $GLOBALS[HTTP_RAW_POST_DATA];
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$data = base64_decode($imageData);
//here i need the value1 value from the javascript
$dirname = "value1";
$filename = "header_top.png";
$newdir = mkdir($dirname);
$path = ("the/path/to".$dirname."/");
$fp = fopen($path.$filename, 'wb');
fwrite($fp, $data);
fclose($fp);
}
I hope I was able to explain myself so you can help me.
Thank you very much.
EDIT:
I think i get it, i mean for the moment it works but i don't know if it the right way doing it.
The fact is that i'm calling a php file so i simple added at the end of the url "?dir="+value1 and it works.
ajax.open("POST", 'saving.php?dir='+value1, false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
and in the php file i simply call $_GET['dir'] to get the value.
#hendrik thank you very much for your answer, unfortunaly i can't get it work with json, maybe becouse i didn't know it.
Anyway if someone knows a better way would be nice.
I think using JSON would be a good way to send the data to your PHP file. That way you can store multiple variables in an Object or Array.
// Store your data in an Object
var imageData = {
url: 'http://adsadsf.com',
name: 'foobar.gif',
width: 500,
height: 400,
directory: 'img/'
}
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
// Send the imageData object as JSON
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify(imageData));
Unfortunately I don't know enough about PHP to explain exactly how to handle the received JSON data, but I guess you can use the json_decode method for that.
More about JSON: http://www.json.org/js.html

How to Enhance This? Get a Part of a Web Page in Another Domain

I have made this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(
function()
{
$("body").html($("#HomePageTabs_cont_3").html());
}
);
</script>
</head>
<body>
<?php
echo file_get_contents("http://www.bankasya.com.tr/index.jsp");
?>
</body>
</html>
When I check my page with Firebug, It gives countless "missing files" (images, css files, js files, etc.) errors. I want to have just a part of the page not of all. This code does what I want. But I am wondering if there is a better way.
EDIT:
The page does what I need. I do not need all the contents. So iframe is useless to me. I just want the raw data of the div #HomePageTabs_cont_3.
Your best bet is PHP server-side parsing. I have written a small snippet to show you how to do this using DOMDocument (and possibly tidyif your server has it, to barf out all the mal-formed XHTML foos).
Caveat: outputs UTF-8. You can change this in the constructor of DOMDocument
Caveat 2: WILL barf out if its input is neither utf-8 not iso-8859-9. The current page's charset is iso-8859-9 and I see no reason why they would change this.
header("content-type: text/html; charset=utf-8");
$data = file_get_contents("http://www.bankasya.com.tr/index.jsp");
// Clean it up
if (class_exists("tidy")) {
$dataTidy = new tidy();
$dataTidy->parseString($data,
array(
"input-encoding" => "iso-8859-9",
"output-encoding" => "iso-8859-9",
"clean" => 1,
"input-xml" => true,
"output-xml" => true,
"wrap" => 0,
"anchor-as-name" => false
)
);
$dataTidy->cleanRepair();
$data = (string)$dataTidy;
}
else {
$do = true;
while ($do) {
$start = stripos($data,'<script');
$stop = stripos($data,'</script>');
if ((is_numeric($start))&&(is_numeric($stop))) {
$s = substr($data,$start,$stop-$start);
$data = substr($data,0,$start).substr($data,($stop+strlen('</script>')));
} else {
$do = false;
}
}
// nbsp breaks it?
$data = str_replace(" "," ",$data);
// Fixes for any element that requires a self-closing tag
if (preg_match_all("/<(link|img)([^>]+)>/is",$data,$mt,PREG_SET_ORDER)) {
foreach ($mt as $v) {
if (substr($v[2],-1) != "/") {
$data = str_replace($v[0],"<".$v[1].$v[2]."/>",$data);
}
}
}
// Barf out the inline JS
$data = preg_replace("/javascript:[^;]+/is","#",$data);
// Barf out the noscripts
$data = preg_replace("#<noscript>(.+?)</noscript>#is","",$data);
// Muppets. Malformed comment = one more regexp when they could just learn to write proper HTML...
$data = preg_replace("#<!--(.*?)--!?>#is","",$data);
}
$DOM = new \DOMDocument("1.0","utf-8");
$DOM->recover = true;
function error_callback_xmlfunction($errno, $errstr) { throw new Exception($errstr); }
$old = set_error_handler("error_callback_xmlfunction");
// Throw out all the XML namespaces (if any)
$data = preg_replace("#xmlns=[\"\']?([^\"\']+)[\"\']?#is","",(string)$data);
try {
$DOM->loadXML(((substr($data, 0, 5) !== "<?xml") ? '<?xml version="1.0" encoding="utf-8"?>' : "").$data);
} catch (Exception $e) {
$DOM->loadXML(((substr($data, 0, 5) !== "<?xml") ? '<?xml version="1.0" encoding="iso-8859-9"?>' : "").$data);
}
restore_error_handler();
error_reporting(E_ALL);
$DOM->substituteEntities = true;
$xpath = new \DOMXPath($DOM);
echo $DOM->saveXML($xpath->query("//div[#id=\"HomePageTabs_cont_3\"]")->item(0));
In order of appearance:
Fetch the data
If we have tidy, sanitize HTML with it
Create a new DOMDocument and load our document ((string)$dataTidy is a short-hand tidy getter)
Create an XPath request path
Use XPath to request all divs with id set as what we want, get the first item of the collection (->item(0), which will be a DOMElement) and request for the DOM to output its XML content (including the tag itself)
Hope it is what you're looking for... Though you might want to wrap it in a function.
Edit
Forgot to mention: http://rescrape.it/rs.php for the actual script output!
Edit 2
Correction, that site is not W3C-valid, and therefore, you'll either need to tidy it up or apply a set of regular expressions to the input before processing. I'm going to see if I can formulate a set to barf out the inconsistencies.
Edit 3
Added a fix for all those of us who do not have tidy.
Edit 4
Couldn't resist. If you'd actually like the values rather than the table, use this instead of the echo:
$d = new stdClass();
$rows = $xpath->query("//div[#id=\"HomePageTabs_cont_3\"]//tr");
$rc = $rows->length;
for ($i = 1; $i < $rc-1; $i++) {
$cols = $xpath->query($rows->item($i)->getNodePath()."/td");
$d->{$cols->item(0)->textContent} = array(
((float)$cols->item(1)->textContent),
((float)$cols->item(2)->textContent)
);
}
I don't know about you, but for me, data works better than malformed tables.
(Welp, that one took a while to write)
I'd get in touch with the remote site's owner and ask if there was a data feed I could use that would just return the content I wanted.
Sébastien answer is the best solution, but if you want to use jquery you can add Base tag in head section of your site to avoid not found errors on images.
<base href="http://www.bankasya.com.tr/">
Also you will need to change your sources to absolute path.
But use DOMDocument

Load images to a TileList from Mysql using PHP and XML on Flash CS5

I have a mysql database with a table containing PATH's to images.
I want to load al the images to a TileList. Now i have this in PHP:
<?PHP
mysql_connect("localhost", "root", "root");
mysql_select_db("prototipo");
$result = mysql_query("select entretenimiento_id, e_nombre, e_imagen from entretenimiento");
echo "<?xml version=\"1.0\" ?><entretenimiento>";
while($row = mysql_fetch_assoc($result))
{
echo "<e_nombre>" . $row["e_nombre"] . "</e_nombre>";
echo "<e_imagen>" . $row["e_imagen"] . "</e_imagen>";
}
echo "</entretenimiento>";
?>
This is supposed to fetch me the PATH of the image, the name so it goes on the label of the tile that displays the image, and brings me also the id so i can launch another query when that image is clicked on.
All this is set into a dynamically created XML.
Now my question.... How do i load this??? What to do o AS3?? I already have the AS3 for the tilelist, i only need to load this dynamically created XML from PHP to it.
Thanks in advance. And sorry if i messed up on english, its not my main language. Im South American.
I have a partial answer:
var path:String = "http://localhost/entretenimiento.php";
xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
xmlLoader.load(new URLRequest(path));
function onLoadComplete(e:Event):void {
var xmlData:XML = new XML(e.target.data);
//trace(xmlData);
for (var i:int=0; i<xmlData.*.length(); i++)
{
myTileList.addItem({label:xmlData.e_nombre[i], source:xmlData.e_imagen[i]});
//trace(xmlData.e_nombre[i]);
}
}
Althought this shows me the images and the titles on the tiles, i also get two more tiles that are empty, and in the trace they are shown as "undefined". Any thoughts to why is this?
Here is a sample code that should works :
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
// change the path of your php file
xmlLoader.load(new URLRequest("your-file.php"));
function showXML(e:Event):void
{
var entretenimiento:XML = new XML(e.target.data);
// for each row :
for (var x:XML in entretenimiento.loc)
{
// Change the name of your tilelist
myTileList.addItem({label:x.e_nombre, source:x.e_imagen});
}
}

FLASH as3 not able to identify localhost php web address

I am trying to retrieve mysql data using php(products.php) and return the data in xml format to ADobe flash as3; but i am getting following error.
Error opening URL 'http://localhost/Flash/player/products.php'
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: http://localhost/Flash/player/products.php at php_mysql3_as3_fla::MainTimeline/frame1()
Please any suggestion or help why flash is not identifying the http://localhost/Flash/player/products.php addres. i have WAMP installed; which works fine as i have many other php projects working here.
Thanks in advance for help and suggestion.
THe following is my php code
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("test");
$query = "select * from products";
$results = mysql_query($query);
echo '<?xml version="1.0" encoding="utf-8" ?>'." \n";
echo"<GALLERY>\n";
$cnt=0;
while($line=mysql_fetch_assoc($results))
{
echo '<IMAGE TITLE="'.$cnt.'">'.$line['product'].'</IMAGE>'." \n";
$cnt++;
}
echo "</GALLERY>\n";
mysql_close($link);
?>
the php file is located at c:\wamp\www\Flash\player\products.php
below is my AS3 flash code
var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
//myLoader.load(new URLRequest("c:\\wamp\\www\\Flash\\player\\products2.xml"));
myLoader.load(new URLRequest("http://localhost/Flash/player/products.php"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(evt:Event):void {
myXML = new XML(evt.target.data);
for (var i:int = 0; i<myXML.*.length(); i++){
trace("My image number is " + (i+1) + ", it's title is " + myXML.IMAGE[i].#TITLE + " and it's URL is " + myXML.IMAGE[i]);
};
//trace("data: " + myLoader.data);;
}
In chat it turned out the problem was a firewall.
Here is another related question:
Testing movie with Flash IDE fails to load file from localhost
This might be possible:
Your movie runs in the local realm, and you are trying to load a network resource (i guess this will be the case). In that case you need to add the compile flag: -use-network=true
The php file does not exist.
You always need to catch the URLLoader events:
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
to see what happened!
See these event handlers in action: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html#includeExamplesSummary

Categories