can not download file in linux using php - javascript

<?php
// Make sure an ID was passed
include('include/function.php');
if(isset($_GET['id'])) {
// Get the ID
$id = intval($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'jio', 'jio');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `id`,`date`,`expected_date`,`comname`,`type`,`name`,`path`,`mime`, `size`, `data`,`other_detail`,`remark`,`username`
FROM `depository`
WHERE `id` = {$id}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
}
else {
echo 'Error! No image exists with that ID.';
}
// Free the mysqli resources
mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>
I am trying to download file from path location(doc root) but getting a empty file download or corrupt file download. anyone can suggest me where i am wrong in above code or use anything else.

After sending the headers you need to read the file contents and send that data - the following isn't tested but is more or less what you need to do. You will probably need to adjust the $filepath variable according to the contents of $row['path'] from the sql result.
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
/* you need to actually read the file and send it */
$filepath=$row['path'] . '/' . $row['name'];
if( !realpath( $filepath ) ) exit('Filepath '.$filepath.' is incorrect');
if( $file = fopen( $filepath, 'rb' ) ) {
while( !feof( $file ) and ( connection_status()==0 ) ) {
print( fread( $file, 1024*8 ) );
flush();
}
fclose( $file );
}
}

Related

How to hide the src of iframe or embed tag using JS/jQuery or PHP?

Im trying to hide the src url for a pdf file in an iframe / embed. Im not sure how.
I tried with all the previously exiting answers, but none of them are working.
<?php
$url = $_GET['url'];
?>
<embed id="renderedPrint" style="height:calc(100% - 4px);width:calc(100% - 4px);padding:0;margin:0;border:0;"></embed>
<script>
$(document).ready(function() {
var encryptedString = "assets/labels/" + "<?php echo $url; ?>" + ".pdf";
$("#renderedPrint").attr("src", encodeURIComponent(encryptedString));
});
</script>
But no matter which method i use (Obfuscator, php openssl_encrypt/decrypt), the output url is always visible.
I dont want users to find the iframe/embed url. I want to make it difficult to or even hide the url from the front-end.
The purpose is that i dont want users to have direct access to the generated pdf file. They may copy the iframe src url and send it to someone else. We cant stop them from downloading the pdf, but i dont want them to copy the source url from the server.
check this code
you should be add file address to DB
<?php
// get id to search on DB and get detail
$id = $_REQUEST['id'];
try {
$conn = new PDO("pgsql:host=$host;port=5432;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT url FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
// the address of file in server
$path = $row['url'];
$filename = basename($path);
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo 'check that file exists and is readable';;
}
?>

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

Send SMS if found changes in json file

I have this json file that I need to make a cron job for and receive SMS notification when data changes http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json
I need to find out if some server is on stock, so I found this code:
<?php
$cellphone = '15551234567';
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
$a = $tmp ['availability'];
$data = array();
foreach ($a as $item) {
if (!in_array($item ['reference'], $a_track)) {
continue;
}
foreach ($item ['zones'] as $zone) {
if ($zone ['availability'] == 'unavailable') {
continue;
}
$data [$item ['reference']] .= $zone ['zone'];
}
}
foreach ($data as $item => $availability) {
$message = "SYS STOCK: $item: $availability";
mail('my#email', 'OMG BUY THIS NOW!', $message);
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy& from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
$discard = file_get_contents($url);
}
The problem is that when I trigger it I receive SMS no matter if server is on stock or not and the SMSs keep coming with false positives. I also got this message :
]# /usr/bin/php /home/sys.php
PHP Notice: Undefined index: 143sys12 in /home/sys.php on line 22
I changed your code around a bit and moved the sending of the message in a function to be called when the reference is found.
Take a look:
<?php
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
foreach ($tmp['availability'] as $item) {
if (in_array($item['reference'],$a_track)) sendMeAnEmail($item);
}
function sendMeAnEmail($item){
$cellphone = '15551234567';
$message = "SYS STOCK: ". $item["reference"] . PHP_EOL;
$gotStock = 0;
foreach ($item["zones"] as $zone)
if ($zone["availability"] != "unavailable" and $zone['availability'] != 'unknown' ) {
$message .= "Available in the " . $zone["zone"]. " zone, with the " . $zone["availability"] . " status." ;
$gotStock++;
}
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy&from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
if ($gotStock > 0) {
print $message . PHP_EOL; // to check
mail('my#email', 'OMG BUY THIS NOW!', $message);
$discard = file_get_contents($url);
print "Got stock, sent mail and SMS" . PHP_EOL;
}
}

Special Characters encoding in textareas

I'm pulling contents from text files into a textarea to be used and noticed it appeared that slashes were appearing near quotes and apostrophes. I was able to resolve that by disabling magic quotes on the server, however I noticed that special characters still don't seem to display properly.
What I am trying to figure out is there a way when retrieving the file to decode/encode them properly or to encode them so they're UTF 8 compliant in the first place? Below is my coding for retrieving the files:
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file ) {
if ( ! is_dir( $file ) ) {
$filesContents[$file] = file_get_contents($directory , $file);
echo '<option value="'. $file .'">' . $file . '</option>';
}
}
?>
</select>
and below is my save script:
if($_POST['Action'] == "SAVE") {
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) {
echo 'There is no session username';
}
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) {
echo 'There is no POST desired filename';
}
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
header('Location: mysite.site/evo/codesaveindex.php?saved=1&file='.$FILENAME);
}
?>

Export HTML5 form data to CSV?

Any ideas on Exporting HTML5 Form data to CSV please?
I can only use HTML5 or Javascript or both.
Thanks
You could just display the form data in CSV format in the browser (maybe in a popup) and have the user do a File -> Save Page (assuming it doesn't have to be fully automated).
OK, this is what I'm going to have to do: 1. If there IS internet connection ... then save the data to MySQL Table. 2. Using PHP run a script on the MySQL DB to export the data to CSV.
I'll use something like this for example:
<?php
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

Categories