SQLite database path not working - sqlite

This is my source code in which I used SQLite database in my PHP source code. When I run the script it give me this error
Warning: sqlite_query() [function.sqlite-query]: no such table:
books in D:\wamp\www\sqllite\index.php on line 13
Error in query: SQL logic error or missing database
I think the error is at the path of database
<?php
$db = $_SERVER['DOCUMENT_ROOT']."umer.db";
$handle = sqlite_open($db) or die("Could not open database".sqlite_error_string(sqlite_last_error($handle)));
$query = "SELECT * FROM books";
$result = sqlite_query($handle, $query) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));
if (sqlite_num_rows($result) > 0) {
echo "<table cellpadding=10 border=1>";
while($row = sqlite_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
sqlite_close($handle);
?>

The error is probably the path, which is determined by this line:
$db = $_SERVER['DOCUMENT_ROOT']."umer.db";
To troubleshoot this you should try an
echo $db;
And then compare that to your actual path - from there you should be able to adjust your string.
If the path is still correct, double check your file permissions and make sure it is readable by the user that is running the php process.
Good luck!

php will start looking for the database file relative to the directory where the currently running file came from so constructs like("../../databases/mydb.sq3") are usually more portable than using an absolute path or a path relative to DOCUMENT_ROOT as these can be changed at a whim.
Your program is almost certainly not finding the database file, in these circumstances sqlite will create a new empty file, and, causes great confusion by raising a "table not found" error when you try to use the database.
Look for an empty "umber.db" appearing somewhere unexpected and this will give you some indication of where you are going wrong.

Related

Download all files in all folders from URL

I'd like to recursively download all files from nested folders from this URL to my computer in the same nested structure:
https://hazardsdata.geoplatform.gov/?prefix=Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings%20HYDA/
I've tried several different approaches, using curl and RCurl, including this and some others. There are multiple file types within this folder. But I keep running into cryptic error message such as Error in function (type, msg, asError = TRUE) : error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
I'm not even sure how to begin.
in their javascript you'll find the url https://hazards-geoplatform.s3.amazonaws.com/ and there you'll find a xml file containing the path to (seemingly?) all their files, from there it shouldn't be hard, so
1: download the XML list of files from https://hazards-geoplatform.s3.amazonaws.com
2: each of the XML's <content> tag describes a file or a folder. filter out all the tags that is not relevant to you, that means if the content->key tag does not contain the text Brookings HYDA, filter it out.
3: the remaining content tags contain your download path and save path, for every key tag that ends with /: this is a "folder", you can't download a fol6der, just create the path, for example if the key is
<Contents>
<Key>Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence/</Key>
this means you should create the folders Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence and move on, however if the key's value does not end with /, it means you should download it, for example if you find
<Contents>
<Key>Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence/200724-CityBrookings-AirportInfo_Email.pdf</Key>
<LastModified>2022-03-04T17:54:48.000Z</LastModified>
<ETag>"9fe9af393f043faaa8e368f324c8404a"</ETag>
<Size>303737</Size>
<StorageClass>STANDARD</StorageClass>
</Contents>
it means the save filepath is Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence/200724-CityBrookings-AirportInfo_Email.pdf
and the url to download the file is https://hazards-geoplatform.s3.amazonaws.com/ + urlencode(key), in this case:
https://hazards-geoplatform.s3.amazonaws.com/Region8%2FR8_MIT%2FRisk_MAP%2FData%2FBLE%2FSouth_Dakota%2F60601300_BrookingsCO%2FBrookings%20HYDA%2FHydraulics_DataCapture%2FCorrespondence%2F200724-CityBrookings-AirportInfo_Email.pdf
idk how to do it with curl/r, but here's how to do it in PHP, happy porting
<?php
declare(strict_types=1);
function curl_get(string $url): string
{
echo "fetching {$url}\n";
static $ch = null;
if ($ch === null) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_ENCODING => '',
CURLOPT_FOLLOWLOCATION=>1,
CURLOPT_VERBOSE=>0
));
}
curl_setopt($ch, CURLOPT_URL, $url);
$ret = curl_exec($ch);
if(curl_errno($ch)) {
throw new Exception("curl error ".curl_errno($ch).": ".curl_error($ch));
}
return $ret;
}
$base_url = 'https://hazards-geoplatform.s3.amazonaws.com/';
$xml = curl_get($base_url);
$domd = new DOMDocument();
#($domd->loadHTML($xml));
$xp = new DOMXPath($domd);
foreach($xp->query("//key[contains(text(),'Brookings HYDA')]") as $node) {
$relative = $node->nodeValue;
if($relative[-1] === '/'){
// it's a folder, ignore
continue;
}
$dir = dirname($relative);
if(!is_dir($dir)) {
mkdir($dir, 0777, true);
}
$url = $base_url . urlencode($node->nodeValue);
file_put_contents($relative, curl_get($url));
}
after running that for a few seconds i have
$ find
.
./fuk.php
./Region8
./Region8/R8_MIT
./Region8/R8_MIT/Risk_MAP
./Region8/R8_MIT/Risk_MAP/Data
./Region8/R8_MIT/Risk_MAP/Data/BLE
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence/200724-CityBrookings-AirportInfo_Email.pdf
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Correspondence/2D_Exceptions_2021Update.pdf
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/DCS_Checklist_Hydraulics_BrookingsCoSD.xlsx
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Simulations
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Simulations/RAS
./Region8/R8_MIT/Risk_MAP/Data/BLE/South_Dakota/60601300_BrookingsCO/Brookings HYDA/Hydraulics_DataCapture/Simulations/RAS/0.2PAC
soo it seems to be working.
the last output from the command is
fetching https://hazards-geoplatform.s3.amazonaws.com/Region8%2FR8_MIT%2FRisk_MAP%2FData%2FBLE%2FSouth_Dakota%2F60601300_BrookingsCO%2FBrookings+HYDA%2FHydraulics_DataCapture%2FSimulations%2FRAS%2F0.2PAC%2FPostProcessing.hdf
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65019904 bytes) in /home/hans/test/fuk.php on line 17
meaning some of their files are over 134MB in size - it's easy to optimize the curl code to write directly to disk instead of storing the entire file in ram before writing to disk, but since you want to do this in R anyway, i won't bother optimizing the sample php script.

How to fix the base64_encode and base64_decode to avoid injection?

I am using a theme option for WordPress with base64_encode and base64_decode. Since base64_ risk for the code injection, need to change that code.
Actually I have no idea how to do that.
The code contain base64_encode is like this:
new AjaxUpload(<?php echo ($value['id']); ?>, {
action: '<?php echo THEME_DIR; ?>/admin/upload-file.php',
name: '<?php echo ($upload_security)?>',
data: {
upload_path : '<?php echo base64_encode(UPFW_UPLOADS_DIR); ?>'
},
onSubmit: function(file, ext){
//Check if file is an image
if (! (ext && /^(JPG|PNG|GIF|jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
jQuery('#<?php echo ($value['id']); ?>loader').addClass('activeload');
},
onComplete: function(file, response){
//On completion clear the status
status.text('');
//Successful upload
if(response==="success"){
$file = file.toLowerCase().replace(/ /g,'_').replace(/(_)\1+/g, '_').replace(/[^\w\(\).-]/gi,'_').replace(/__/g,'_').replace(/#/g, '_');
//Preview uploaded file
jQuery('#<?php echo ($value['id']); ?>preview').removeClass('uploaderror');
jQuery('#<?php echo ($value['id']); ?>preview').html('<img class="preview" src="<?php echo UPFW_UPLOADS_URL; ?>/'+$file+'" alt="<?php echo ($value['id']); ?> Image" />').addClass('success');
//Add image source to hidden input
jQuery('input#<?php echo ($value['id']); ?>').attr('value', '<?php echo UPFW_UPLOADS_URL; ?>/'+$file);
//Append thumbnail to gallery
jQuery('.thumbs').append('<a class="preview" href="<?php echo UPFW_UPLOADS_URL; ?>/'+$file+'"><img src="<?php echo UPFW_UPLOADS_URL; ?>/'+$file+'" /></a>');
//Save Me Fool
activate_save_animation();
} else{
//Something went wrong
jQuery('#<?php echo ($value['id']); ?>preview').text(file+' did not upload. Please try again.').addClass('uploaderror');
}
jQuery('#<?php echo ($value['id']); ?>loader').removeClass('activeload');
}
});
and the code content base64_decode is like this:
<?php
//Upload Security
$upload_security = md5($_SERVER['SERVER_ADDR']);
$uploaddir = base64_decode( $_REQUEST['upload_path'] ) . "/";
if( $_FILES[$upload_security] ):
$file = $_FILES[$upload_security];
$file = $uploaddir . strtolower(str_replace('__', '_', str_replace('#', '_', str_replace(' ', '_', basename($file['name'])))));
if (move_uploaded_file( $_FILES[$upload_security]['tmp_name'], $file)):
if(chmod($file,0777)):
echo "success";
else:
echo "error".$_FILES[$upload_security]['tmp_name'];
endif;
else:
echo "error".$_FILES[$upload_security]['tmp_name'];
endif;
endif;
?>
Would really appreciate your help.
Thank you.
Moving this from comments to an answer because this is going to get detailed and hopefully it'll become one of those cool Stack Overflow answers people link to all over the place and I'll get all sorts of upvotes and job offers and free drinks at the local bar. Well, I'll settle for the upvotes. Or the drinks.
Hey, I'm home today. The baby's asleep. I've got some time to ramble.
base64
Things weren't always as standardized as they are now. For example, the computer I take my username from, the Commodore 64, encoded characters using Commodore's proprietary PETSCII instead of ASCII. Lots of IBM Mainframes used their own EBCDIC encoding, which was based on six-bit character encodings their older machines used. Six bits can represent the values 0-63, or 64 distinct characters.
There's also the fact that some characters are special. They represent things like tabs, invisible spaces, and data transfer control protocols. ASCII 7 is "BEL" and that would actually ring the bell on an ASR-33 teletype. But those characters are in different places and mean different things in the different character encodings.
To make sure email & Usenet worked between these ancient systems and the current standards, early Internet pioneers came up with base64 encoding, which encoded 8-bit data six bits at a time into a set of 64 "printable" (not control) characters. You still needed to decode it to eight bits at the other end, but any old 6-bit or 7-bit systems it passed through along the way couldn't mess it up.
So all base64_encode() and base64_decode() do is encode the data using a limited, standard set of characters. It's handy for storing binary data (like photos) in databases or encoding them in HTML <img> tags. It's a way around backslash escaping, which used to happen automatically sometimes in PHP. But it's not a kind of encryption or anything.
But base64 encoded text is friendly to old mainframes, not people. For example, "Hello World" becomes SGVsbG8gV29ybGQ=. And that's why people use it to hide evil code or things they don't want changed like copyright notices or links back to the theme builder's web site:
echo 'Get great answers at Stack Overflow';
becomes
eval(base64_decode('ZWNobyAnR2V0IGdyZWF0IGFuc3dlcnMgYXQgPGEgaHJlZj0iaHR0cDovL3N0YWNrb3ZlcmZsb3cu
Y29tIj5TdGFjayBPdmVyZmxvdzwvYT4nOw=='));
And that is what the WordPress.org theme review team doesn't want to see. That's the use of base64 they're concerned about. It's a way for people to obfuscate code, make it so people can't read it. It's risky, and it's against the spirit of open source.
Your example code
This code is dangerous:
data: {
upload_path : '<?php echo base64_encode(UPFW_UPLOADS_DIR); ?>'
}
UPFW_UPLOADS_DIR is a directory somewhere on your server, and it's just being base64 encoded. That means your JavaScript AJAX code sends a variable upload_path which has a value like L3Zhci93d3cvbXlzaXRlL3dwLWNvbnRlbnQvdXBsb2Fkcw== -- that's just /var/www/mysite/wp-content/uploads base64 encoded.
The PHP code on the server takes that value and decodes it:
$uploaddir = base64_decode( $_REQUEST['upload_path'] ) . "/";
then attaches the filename to that directory to build a file path:
$file = $uploaddir . strtolower(str_replace('__', '_', str_replace('#', '_', str_replace(' ', '_', basename($file['name'])))));
and moves the uploaded file to that new path:
if (move_uploaded_file( $_FILES[$upload_security]['tmp_name'], $file)):
This code is a back door to upload files anywhere your web server software(Apache, Nginx or similar) can write to on the disk
I could post to your /admin/upload-file.php script and give it an upload_dir like L3Zhci93d3cvbXlzaXRlL2luZGV4LnBocA==. Your code would take my file and replace WordPress's main index.php file (/var/www/mysite/index.php) with it.
Instead of sending the upload_dir to the browser and trusting you'll get back the same thing you sent, your code should just use UPFW_UPLOADS_DIR directly:
$file = UPFW_UPLOADS_DIR . '/' . strtolower(str_replace('__', '_', str_replace('#', '_', str_replace(' ', '_', basename($file['name'])))));
It looks like your upload code is a stand-alone PHP script instead of using WordPress's AJAX functionality. If that's the way you'd prefer it, you can bootstrap WordPress by including wp-load.php so its variables, constants (like UPFW_UPLOADS_DIR), and API are available in your code.

crontab centos wordpress wp-load

I am using on centos server crontab
* * * * * php -q /var/www/domain.com/public_html/script.php
script.php contents:
<?php
require_once( '/var/www/domain.com/public_html/wp-load.php' );
global $wpdb;
$results = $wpdb->get_var("SELECT post_date FROM wp_posts WHERE id = 70");
$fn = "/var/www/domain.com/public_html/file.txt";
$file = fopen($fn, "a+");
fwrite($file, $results."\n");
fclose($file);
?>
When I go directly to: http://www.domain.com/script.php it executes fine and writes to file, when crontab is want to execute i didnt get writen result from db to file.txt... What is the problem ? it seem wont to load wp-load.php? any ideas ?
Crontab is working, when I comment wp-load.php it writes to file...
Without insight in your system, this might be related to permissions. What user runs this via the web interface, and what user runs this via cron?
In any case, you should put error checking in your PHP script:
$file = fopen($fn, "a+");
if (! $file)
print("Oops, cannot open $file\n");
See e.g. w3schools for an example of error reporting in such things.

Unable to decode json file in a controller

I'm a new symfony user, and I'm actually trainning myself on it.
Here is my problem:
echo $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
$channels = json_decode($this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json'));
var_dump($channels);
I would like to decode a JSON file in my controller, but here is what the echo and vardump give me:
/Symfony/web/bundles/tlfront/js/channels.json ( the echo)
null (the var_dump)
It seems that the path to the file is correct but json_decode doesn't work.
json_last_error() returns 4 which is JSON_ERROR_SYNTAX
But, when I run the json string in http://jsonlint.com/ it returns Valid JSON
Any ideas or advices ?
Dude, it has nothing to do with Symfony... json_decode only accepts strings:
http://php.net/manual/es/function.json-decode.php
That's why you're getting the syntax error. Just read the file with file_get_contents and you're done:
$path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
$content = file_get_contents($path);
$json = json_decode($content, true);
BTW, Symfony comes bundled with Finder, a really nice tool to search and get all the files you need: http://symfony.com/doc/current/components/finder.html

PHPExcel throwing error, locale? Not using locale

I'm trying to use PHPExcel, and it's throwing an error for even the most basic things, and even for a script copied from somewhere ( http://blog.clock.co.uk/phpexcel-example/ ).
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>/home/.../public_html/pear/PEAR/PHPExcel/PHPExcel/Calculation.php</b> on line <b>1685</b><br />
The outputted file has this as the very top of the file, for which Excel (or Open Office) says is not a valid file. If I remove those two lines, everything is fine and Excel (or OO) can open it with no problems and everything the script does is there.
Calculation.php line 1685:
foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) {
And the function it is in:
private function __construct() {
$localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/';
foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) {
$filename = substr($filename,strlen($localeFileDirectory)+1);
if ($filename != 'en') {
self::$_validLocaleLanguages[] = $filename;
}
}
$setPrecision = (PHP_INT_SIZE == 4) ? 12 : 16;
$this->_savedPrecision = ini_get('precision');
if ($this->_savedPrecision < $setPrecision) {
ini_set('precision',$setPrecision);
}
} // function __construct()
I installed PHPExcel via PEAR.
I didn't see a "locale" directory anywhere in the PHPExcel setup, so I tried creating it but still have the same problem.
I'm not setting or using a locale feature.
It would appear then that there is a problem in the PEAR installation of PHPExcel, which I'll need to investigate.
You can find the locale directory and files in the source repository on github (https://github.com/PHPOffice/PHPExcel/tree/master/Classes) or in the standard zip distributions; but it would probably be better to use the full zip installation in case there are any other problems with the PEAR instal
I met this problem in PHP 5.3 + PHPExcelv1.7.6(2011-02-27) .
I solved this by updating to PHPExcel v1.8.0(2014-03-02)

Resources