php list files in directory and save to disk - javascript

I want to list the files in "archives/" and write the decoded array to disk (file name = "archives/events.txt") But what I have doesn't create that file.
xhr.send(data); // gives: Uncaught ReferenceError: data is not defined
What am I doing wrong?
function LISTevents () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "json-events.php");
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
json-events.php
<?php
// create list of events files in archives/* on server
$files1 = scandir('archives');
file_put_contents('archives/events.txt', print_r($files1, true));
?>

<?php
function list_contents($dir, $suffix) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'events.txt') {
if (substr($file, -strlen($suffix)) == $suffix) {
$contents[] = $file;
}
}
}
foreach ($contents as $key => $item) {
if (strlen($item) != 14) {
unset($contents[$key]);}
}
foreach ($contents as $key => $item) {
if (substr($item,0,1) != "2") {
unset($contents[$key]);}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/events.txt', $contents_json);
}
list_contents('archives','.txt');
?>

Related

i want to save or download an image from blob url or data

im doing a paste event from clipboard, it creates a blob url. Now i dont how to save or get the file. How can i save it to my computer? I think im totally wrong in getting the blob in my php. im getting it as a string then trying to save it
This is my code for creating the blob
<?php
if( isset( $_FILES['file'] ) ) {
$file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
header("Content-Type: " . $_FILES['file']['type'] );
die($file_contents);
}
else {
header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>
<script type="text/javascript">
document.onpaste = function (e) {
var items = e.clipboardData.items;
var files = [];
for( var i = 0, len = items.length; i < len; ++i ) {
var item = items[i];
if( item.kind === "file" ) {
submitFileForm(item.getAsFile(), "paste");
}
}
};
function submitFileForm(file, type) {
var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
var formData = new FormData();
formData.append('file', file, "image_file");
formData.append('extension', extension );
formData.append("mimetype", file.type );
formData.append('submission-type', type);
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.open('POST', '<?php echo basename(__FILE__); ?>');
xhr.onload = function () {
if (xhr.status == 200) {
var img = new Image();
img.src = (window.URL || window.webkitURL)
.createObjectURL( xhr.response );
document.getElementById("nye").appendChild(img);
document.getElementById("nye").style.display = "none" ;
var x = document.getElementById("image");
x.setAttribute("type", "text");
x.setAttribute("value", img.src);
document.getElementById("image").appendChild(x);
}
};
xhr.send(formData);
}
</script>
This is my code that's save to my computer, it runs but i juts recive a blank jpg file
<?php
$data = $_POST['url'];
$filePath = $uploadDir . $name;
$contents_split = explode(',', $data);
$encoded = $contents_split[count($contents_split)-1];
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
}
$fp = fopen('sample23.jpg', 'w');
fwrite($fp, $decoded);
fclose($fp);
?>
it saves but i think the file is blank.

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

AJAX function gives void, fread (php) output to html div

This is a PHP function that reads first the title then the content of a txt file that has been uploaded,
<?php
$q = $_REQUEST["q"];
$output = "";
if ($q !== "") {
$bestand = fopen("Blogs.txt", "r");
if (!$bestand) {
echo "Kon geen bestand openen";
}
while (!feof($bestand)) {
$blog = fgets($bestand);
$blog = explode(",", $blog);
$i = 0;
foreach ($blog as $key) {
$i++;
if ($i % 2 == 0) {
$output = $key;
}
elseif (!$i % 2 == 0) {
$Blogname = fopen("Blogs/$key", "r");
$Blogtext = fread($Blogname, filesize("Blogs/$key"));
$output = $Blogtext;
}
}
}
fclose($bestand);
}
?>
but then i wanted to have it show up in html instead of php so i search solution and found AJAX but have been struggling for hours on why it doesn't work
function Getblog() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "Blogreader.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var para = document.createElement("div");
var t = document.createElement(this.responseText);
para.appendChild(t);
document.getElementById("BlogDiv").appendChild(para);
}
};
}
This is the Javascript code that gives a void function.
What i want it to do is make a DIV of the output of a the php function
<a> <input type="button" onclick="Getblog()"></a>
<div id="BlogDiv"></div>
And this is the refresh button and the div where they are going to be showed

Jquery file uploading JSON empty error

I'm following these videos (https://www.youtube.com/watch?v=Be-GSVO7PGQ&index=9&list=PLfdtiltiRHWHCzhdE0N1zmeFHlEuqxQvm) to create a jquery upload page to my website.
I get the following error on Chrome:
Uncaught SyntaxError: Unexpected end of input
And I get the following error on Firefox Firebug:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Currently, my code looks like this:
upload.php:
<form action="upload_process.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend><h3>Upload files</h3></legend>
<input type="file" id="file_upload" name="file_upload[]" required multiple>
<input type="submit" id="submit_upload" name="submit_upload" value="Upload">
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
Uploaded files will appear here.
</div>
</fieldset>
</form>
<script src="js/upload.js"></script>
<script>
document.getElementById('submit_upload').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file_upload'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload_process.php',
finished: function(data) {
console.log(data);
},
error: function() {
console.log('not working');
}
});
});
</script>
upload.js
var app = app || {};
(function(o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
console.log(uploaded);
}
if (typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if (typeof o.options.error === 'function') {
o.options.error(uploaded);
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
};
setProgress = function(value) {
};
o.uploader = function(options) {
o.options = options;
if (o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
};
}(app));
and my upload_process.php
<?php
//require_once('core/init.php');
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['mp4', 'png', 'bmp', 'mp3', 'txt'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file_upload'])) {
foreach($_FILES['file_upload']['name'] as $key => $name) {
if ($_FILES['file_upload']['error'][$key] === 0) {
$temp = $_FILES['file_upload']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
$db = new DB();
$user = new User();
$units = new Units();
$size = filesize("uploads/" . $file);
$formattedSize = $units->formatSizeUnits($size);
$db->insert('files', array(
'user_id' => $user->data()->id,
'name' => $name,
'size' => $formattedSize,
'address' => 'uploads/' . $file . '',
'created' => date('Y-m-d H:i:s'),
'type' => $ext
));
/*Redirect::to('index');
Session::flash('');*/
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed
));
}
}
I know that the problem is propably that this:
uploaded = JSON.parse(this.response);
this.response returns nothing.
I just can't figure out why it returns nothing.

PHP parse Meta Tags of an aspx page failure

In my project I have a PHP function that parses an HTML page and retrieves meta tags correctly. When I run my function for an aspx page this fails and doesn't create return data even though the aspx page in question has correctly set the meta tags.
The function is:
function getUrlData($url)
{
$result = false;
$contents = getUrlContents($url);
if (isset($contents) && is_string($contents))
{
$title = null;
$metaTags = null;
preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );
if (isset($match) && is_array($match) && count($match) > 0)
{
$title = strip_tags($match[1]);
}
preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="? ([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 3)
{
$originals = $match[0];
$names = $match[1];
$values = $match[2];
if (count($originals) == count($names) && count($names) == count($values))
{
$metaTags = array();
for ($i=0, $limiti=count($names); $i < $limiti; $i++)
{
$metaTags[$names[$i]] = array (
'html' => htmlentities($originals[$i]),
'value' => $values[$i]
);
}
}
}
$result = array (
'title' => $title,
'metaTags' => $metaTags
);
}
return $result;
}
function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
$result = false;
$contents = #file_get_contents($url);
// Check if we need to go somewhere else
if (isset($contents) && is_string($contents))
{
preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
{
if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
{
return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
}
$result = false;
}
else
{
$result = $contents;
}
}
return $contents;
}
How is it possible to read meta tags from aspx pages?
Thanks in advance
AM
There might be a easier way to do this using get_meta_tags
e.g.
<?php
// Load
$tags = get_meta_tags('http://www.example.com/');
// Debug
echo "<pre>";
print_r($tags);
echo "</pre>";
?>

Categories

Resources