php to parse ascii text from file get contents - php

Good morning all, i have a new question:
I'm trying to save into mysql a set of data coming from a SIMBAD database query (it's a stellar objects dataabse).
If you enter this url into the browser: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=hd%201&OutputMode=VOTable
you get a result formated with separate lines, but if you use
<?php
$cadaart = 'http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=hd%201';
$handler = curl_init($cadaart);
$response = curl_exec ($handler);
curl_close($handler);
echo $response;
?>
or a simple file_get_content and echo the response you get a single line with all information, which makes me impossible to parse... Any idea on how to solve this?
Thanks.

The string is already with line-break,
you can use file to convert contents from that URL into an array (each line is an array element)
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

It's probably just the difference between an LF and a CRLF. The output from your URL is LF, which, in where you're viewing it (browser?), is probably not parsed as a new line.
Try $response = str_replace("\n", "\r\n", $response); and see if this makes any difference

Related

PHP sanitize strings used inside PHP PDO connection [duplicate]

I was wondering how to save PHP variables to a txt file and then
retrieve them again.
Example:
There is an input box, after submitted the stuff that was written in
the input box will be saved to a text file. Later on the results need
to be brought back as a variable. So lets say the variable is $text I
need that to be saved to a text file and be able to retrieve it back
again.
This should do what you want, but without more context I can't tell for sure.
Writing $text to a file:
$text = "Anything";
$var_str = var_export($text, true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);
Retrieving it again:
include 'filename.php';
echo $text;
Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).
Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.
$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));
(Sorry I can't comment just yet, otherwise I would)
To add to Christian's answer you might consider using json_encode and json_decode instead of serialize and unserialize to keep you safe. See a warning from the PHP man page:
Warning
Do not pass untrusted user input to unserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.
So your final solution might have the following:
$file = '/tmp/file';
$content = json_encode($my_variable);
file_put_contents($file, $content);
$content = json_decode(file_get_contents($file), TRUE);
for_example, you have anyFile.php, and there is written $any_variable='hi Frank';
to change that variable to hi Jack, use like the following code:
<?php
$content = file_get_contents('anyFile.php');
$new_content = preg_replace('/\$any_variable=\"(.*?)\";/', '$any_variable="hi Jack";', $content);
file_put_contents('anyFile.php', $new_content);
?>
Use a combination of of fopen, fwrite and fread. PHP.net has excellent documentation and examples of each of them.
http://us2.php.net/manual/en/function.fopen.php
http://us2.php.net/manual/en/function.fwrite.php
http://us2.php.net/manual/en/function.fread.php
Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)
Okay, so I needed a solution to this, and I borrowed heavily from the answers to this question and made a library: https://github.com/rahuldottech/varDx (Licensed under the MIT license).
It uses serialize() and unserialize() and writes data to a file. It can read and write multiple objects/variables/whatever to and from the same file.
Usage:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
See the github page for more information. It has functions to read, write, check, modify and delete data.

Decoding this PHP?

Okso I have some PHP that I'm working with for a client. The last guy to make his site encoded all his PHP to make it difficult for guys like me to come in and make changes. I have no idea what this is.
Ok so it started off as this:
<?php $OOO000000=urldecode('%66%67%36%73%62%65%68%70%72%61%34%63%6f%5f%74%6e%64');$OOO0000O0=$OOO000000{4}.$OOO000000{9}.$OOO000000{3}.$OOO000000{5};$OOO0000O0.=$OOO000000{2}.$OOO000000{10}.$OOO000000{13}.$OOO000000{16};$OOO0000O0.=$OOO0000O0{3}.$OOO000000{11}.$OOO000000{12}.$OOO0000O0{7}.$OOO000000{5};$OOO000O00=$OOO000000{0}.$OOO000000{12}.$OOO000000{7}.$OOO000000{5}.$OOO000000{15};$O0O000O00=$OOO000000{0}.$OOO000000{1}.$OOO000000{5}.$OOO000000{14};$O0O000O0O=$O0O000O00.$OOO000000{11};$O0O000O00=$O0O000O00.$OOO000000{3};$O0O00OO00=$OOO000000{0}.$OOO000000{8}.$OOO000000{5}.$OOO000000{9}.$OOO000000{16};$OOO00000O=$OOO000000{3}.$OOO000000{14}.$OOO000000{8}.$OOO000000{14}.$OOO000000{8};$OOO0O0O00=__FILE__;$OO00O0000=0xa68;eval($OOO0000O0('JE8wMDBPME8wMD0kT09PMDAwTzAwKCRPT08wTzBPMDAsJ3JiJyk7JE8wTzAwT08wMCgkTzAwME8wTzAwLDB4NTU0KTskT08wME8wME8wPSRPT08wMDAwTzAoJE9PTzAwMDAwTygkTzBPMDBPTzAwKCRPMDAwTzBPMDAsMHgxN2MpLCdmaFY2THhOT01GUlgwZXZjK3lTOEhXdHNZcUpuUUNQVEJacGszb0VnQXU5YjI1MW1Jai9yYTRHemxkRFU3S3dpPScsJ0FCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5Ky8nKSk7ZXZhbCgkT08wME8wME8wKTs='));return;?>~DFLKc06hc06hc064rCOFTQEWInNxkqSBgs4KNSHjxs47gXVMgMpl38aKc0L7I8rfIXpMgMpI38aKc06fI0L7IRVyc8a7I06fI0L7AFL7I8rfI8a7I0VB38rfI0L7I8rfIXVyc8rfI8rfI06fuXVCEJxYG8OZv8a4NHoBIqsqkRzo8vLZsCOeqQHu1HHe+WLFJQN2rnaWg+sHdYkM40t4FJpK/Y8yOPEj3yxHzSzCucSQ2FaxV+ayxy3CMSHuX8L4v84hyHoeHWWqstxoJYtFkqNWEqGZuJE52ntdmQOx/Qzy4CgClPsAI08Mre6HGerBdR/7gRS3uvGqknNKrqSB38rfI0L7I8rfIR85oCEx2RVyc8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K4ngyoQpIgQp2gR82RCGZunNHA0S3BPIuuqpfAqEjmYG2AFNqAXLjc+a5TyWBuRShUVpypCtqEqsMBcShkJNKIRNq/qtx3RVyEJVjEJtjoQGoDqSB3JNoaYGK4ngyoQp3uR82RFNF4qEqoQp2bvIu/qsCunE+AFNqAR82RqgC/JsyoRVyEJVI3YgWEqEW/R82RqEq2CseARVyEJV3UVEqaQgW1YGxaqSB3qEB2qgyonNIAFNqARS3UVEq2nGebRVyEJVj08aeXs4WvR82RYgFoYt2UVg4onOeoMO2RFNjmYG56nzW1CV2bvIurnNWoQVBjR82RT+uuqpfAFNjmYG56nzW1CVfwcSf4RShUVEF/qtxbvIuKVgaRTtW2QGHBPIA3qEBBcShEnzhonpB3JNoaYGK4ngyoQpIgC/2gR82RqgC/JsyoRVyEJVIp0SMuvIA3YgWEqEW/cSMjMk2RT+uEYGjmQGHAFNqAR82RT+uKVpyZQG48qtx/YGZWQEIBcShZQG40JtdbvkukQEWZCNW8qtx/YGZWQEIAFN4dnNo1JGyoQz+uvIAUalVnRPIq
I then decoded it into this:
<?php $O000O0O00 = $OOO000O00($OOO0O0O00, 'rb');
$O0O00OO00($O000O0O00, 0x554);
$OO00O00O0 = $OOO0000O0($OOO00000O($O0O00OO00($O000O0O00, 0x17c), 'fhV6LxNOMFRX0evc+yS8HWtsYqJnQCPTBZpk3oEgAu9b251mIj/ra4GzldDU7Kwi=', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'));
eval($OO00O00O0); ?>
However I have not gotten any further. Any idea on how to work with this?
Ooh, a puzzle! I like puzzles.
This decoder has two stages.
The first one assigns a number of strings, then decodes and evaluates the second stage. Here it is with some of the bad formatting and variable names removed:
$map=urldecode('%66%67%36%73%62%65%68%70%72%61%34%63%6f%5f%74%6e%64');
$base64_decode=$map{4}.$map{9}.$map{3}.$map{5};
$base64_decode.=$map{2}.$map{10}.$map{13}.$map{16};
$base64_decode.=$base64_decode{3}.$map{11}.$map{12}.$base64_decode{7}.$map{5};
$fopen=$map{0}.$map{12}.$map{7}.$map{5}.$map{15};
$fgets=$map{0}.$map{1}.$map{5}.$map{14};
$fgetc=$fgets.$map{11};
$fgets=$fgets.$map{3};
$fread=$map{0}.$map{8}.$map{5}.$map{9}.$map{16};
$strtr=$map{3}.$map{14}.$map{8}.$map{14}.$map{8};
$filename=__FILE__;
$hex_a68=0xa68;
eval($base64_decode(another base64 blob -- the second stage))
Each of the strings, besides $map and $filename, ends up getting assigned its name as contents.
The second stage, which is decoded from a Base64 blob, consists of the second part you already discovered, which I've treated similarly below:
$fh = $fopen($filename, 'rb');
$fread($fh, 0x554);
$data = $base64_decode($strtr(
$fread($fh, 0x17c),
'fhV6LxNOMFRX0evc+yS8HWtsYqJnQCPTBZpk3oEgAu9b251mIj/ra4GzldDU7Kwi=',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
));
eval($data);
This reads some encoded data from the current PHP file, modifies it using strtr(), Base64 decodes it, then evaluates that. The results of this decoding appear to be somewhat corrupted (possibly you've omitted part of the input?), but include this readable fragment of PHP code:
class asmLink
{
static function createSearchUrl ($originalUrl)
{
$originalUrl = trim($originalUrl);
$amzUrlBits = parse_url($originalUrl);
$amzScheme = $amzUrlBits['
As an aside: Your client would be well advised to consider reading their contract with the previous developer very carefully, and may want to consider legal proceedings — that developer has deliberately taken steps to prevent your client from having their site maintained by anyone else.

Fetching Limited Words In PHP Simple HTML DOM Parser

Have a look at this code
echo file_get_html('http://www.google.com)->plaintext;it will fetch full content from a website. So, my question is how to fetch limited words. Suppose it will fetch only 180 words.. any idea?
file_get_html creates a DOM object, which requires a full page load/parse so you can't necessarily grab by character count. You can, however, initiate a file handler and fread to a certain amount of bytes:
$fh = fopen('google.com');
$data = fread($fh,$length);
fclose($fh);
Or this:
$data = substr(file_get_contents('google.com'),$start,$end);

PHP - DOMDocument load XML with encoded name

Lets say that in my flash project I have script that create for me xml files dynamically (by PHP). XML file name is based on specific variable and escaped using escape(variable) in case that variable may (and mostly do) contains unsupported filename chars...
I need to know precise name of xml file later in my flash project, because I'm loading these XML files only if unescape(XMLfile) == variable . There's a lot of variables, so I can't just use String.replace() function to wipe out unsuported fileneme chars...
There's part of PHP file I'm using:
$XMLDom = new DomDocument('1.0', 'UTF-8');
$xmlId = trim($_POST['xmlId']);
if(file_exists($xmlId)){
$XMLDom ->load($xmlId);
}else{
$newXMLHandler = fopen($xmlId, 'w') or die("can't open file");
fclose($newXMLHandler);
$XMLDom ->load($xmlId);
.... rest of the code ....
$XMLDom ->save($xmlId);
}
The result of the code above is that in directory are 2 newly created XML files
One XML empty created by fopen($xmlId, 'w'), named: "fi%20le%2C%2E%40.xml"
and second one named: "fi le,.#.xml" where all my new XML data is stored...
Is there any way to load escaped named XML file by PHP?
Thanks in advance.
Arthur.
I don't feel quite confident I understand your problem, but if your question was to find the analogue function to escape() in PHP, then urlencode() looks like the best match, but you need to research what exactly is being escaped. Note, for example, that there are several different ways to percent-encode strings, especially the multibyte strings. Flash may use escapeMultibyte() or it can also use encodeURIComponent() both encode different subsets of characters, and differently - so beware!
Now, regarding file names, if your HTTP server is running on Unix system, than "fi le,.#.xml" is a valid file name, nothing to worry about - inconvenient some times, but it is a legitimate name.
touch 'fi le,.#.xml'
would create a file, no problems there. Basically, the restricted characters are the slashes and the null character ("\x00"), but it is common to restrict also the characters that may be interpreted as shell commands - this is really up to you.

Remove double-quotes from a json_encoded string on the keys

I have a json_encoded array which is fine.
I need to strip the double-quotes on all of the keys of the json string on returning it from a function call.
How would I go about doing this and returning it successfully?
Thanks!
I do apologise, here is a snippet of the json code:
{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}
Just to add a little more info:
I will be retrieving the JSON via an AJAX request, so if it would be easier, I am open to ideas in how to do this on the javascript side.
EDITED as per anubhava's comment
$str = '{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}';
$str = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $str);
echo $str;
This certainly works for the above string, although there maybe some edge cases that I haven't thought of for which this will not work. Whether this will suit your purposes depends on how static the format of the string and the elements/values it contains will be.
TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
DETAILS:
A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
In my case I saw the difference using Chrome's debugging tools. When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger. This allowed the object to be immediately treated as an object without using a JSON.parse() call. Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys. This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type. I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required. Now I can switch between the legacy and new system without any changes except the destination URL.

Categories