PHP Read file content based on pathname - javascript

UPDATED:
I am using RecursiveIteratorIterator to scan the directories to read index.html file.
Now, based on the Pubname and Pubversion, i am trying to read the corresponding index.html file, to get the values of Readability Grade, Readability Score etc. (by storing the values in local storage)
The values are fetched from local storage if i use the html and JS code separately, but after i integrate into php, it is not working.
Code:
<?php
//error_reporting(0);
//Get Pub version
function get_version($path){
$needle = "=";
if(($pos = strpos($path, $needle)) != 0){
$bits = str_split($path, $pos + strlen($needle));
$integer_count = 0;
for($x = 0; $x < strlen($bits[1]); $x++){
if(is_numeric($bits[1][$x])){
$integer_count++;
}else{
break;
}
}
if($integer_count > 0){
$bits = str_split($bits[1], $integer_count);
return $bits[0];
}
}
return -1;
}
$it = new RecursiveDirectoryIterator("C:\Users\Sachin_S2\Desktop\Script");
foreach(new RecursiveIteratorIterator($it,RecursiveIteratorIterator::SELF_FIRST) as $file) {
//IGNORE FILE TYPES
//$filetypes = array("jpg", "png", "pdf", "css", "csv","log","txt");
$htmlfiles = array("html");
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $htmlfiles)) {
// skip dot files while iterating
$it->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$files = array($file);
$pathname = $file->getPathname();
print_r($pathname);
$version = get_version($pathname);
if($version > 0){
// use $version to read correct file
include 'html/home.html';
}
echo '*********************************************************************************'.'<br/><br/>';
}
}
html/home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SEO Metrics</title>
</head>
<body>
<!--Begin script code-->
<form name="myform3">
<!--
<input type="hidden" name="formvar" value="">
<input type="file" name="file" id="file">
<p id="demo"></p><br/><br/>
-->
<div class="form-group">
<label>Readability Grade:</label>
<input type="text" class="form-control" id="grade">
</div>
<div class="form-group">
<label>Readability Score:</label>
<input type="text" class="form-control" id="score">
</div>
<div class="form-group">
<label>Total Word Count:</label>
<input type="text" class="form-control" id="words">
</div>
</form>
<!--END script code-->
<!--Custom JS code-->
<script src="js/home.js"></script>
</body>
</html>
js/home.js
$(document).ready(function() {
document.getElementById('file').onchange = function() {
const file = this.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
let arr = allLines;
arr.forEach((kv) => {
if (kv.includes("Flesh-Kincaid Grade Level")) {
var fetch_grade = kv.replace(/<\/?[^>]+(>|$)/g, "");
var formated_grade = fetch_grade.split(":").pop(); //Remove part of the string before ":"
localStorage.setItem("Readability_Grade", formated_grade);
document.getElementById('grade').value = localStorage.getItem("Readability_Grade").replace(/\s/g, ""); //Assign localStorage to text box
localStorage["Readability_Grade"] = grade.value;
//alert(formatedgrade);
}
if (kv.includes("Flesh Reading Ease Score")) {
var fetch_score = kv.replace(/<\/?[^>]+(>|$)/g, "");
var formated_score = fetch_score.split(":").pop();
localStorage.setItem('Readability_Score', formated_score);
document.getElementById('score').value = localStorage.getItem("Readability_Score").replace(/\s/g, "");
//alert(formatedscore);
}
if (kv.includes("Reuse Metrics Score")) {
var metricscore = kv;
//alert(metricscore);
}
if (kv.includes("Total words")) {
var totalwords = kv.replace(/<\/?[^>]+(>|$)/g, "");
var total_words_formated = totalwords.split(":").pop();
localStorage.setItem('Word_Count', total_words_formated);
document.getElementById('words').value = localStorage.getItem("Word_Count").replace(/\s/g, "");
//alert(totalwords);
}
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
};
});
Output:
On reading this php script, i should be able to read index html (for each file paths - based on pubname and version), and get the values of Readability_Grade and score etc., which i am not able to get.

Firstly get the version number from the string, below is a method to do just that.
function get_version($path){
$needle = "Pub=";
if(($pos = strpos($path, $needle)) != 0){
$bits = str_split($path, $pos + strlen($needle));
$integer_count = 0;
for($x = 0; $x < strlen($bits[1]); $x++){
if(is_numeric($bits[1][$x])){
$integer_count++;
}else{
break;
}
}
if($integer_count > 0){
$bits = str_split($bits[1], $integer_count);
return $bits[0];
}
}
return -1;
}
And then you can use it like this.
foreach ($paths as $path){
$version = get_version($path);
if($version > 0){
// use $version to read correct file
}
}
Thats if I undertoood your question.
Disclaimer: Quickly typed up but should work.

Related

Parse file only one time using papaParse

I want to create a web app to make simple actions on a csv. For example, the user would upload a csv file then all columns would show up on a form, the user could select some columns to remove them from the file and finally the user could download the modified file.
I have already done something working but there is definitely room for improvement. The most important one is that in my current solution I have to parse the file two times because Papaparse is asynchronous, one time to get the columns and another time to remove columns from the user input.
Is there a way to parse the file only one time and then use the resulting object through the rest of the code ?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSV Manipulator</title>
<link rel="stylesheet" href="style.css" />
</head>
<script src="script.js"></script>
<script src="papaparse/papaparse.min.js"></script>
<body>
<div id="csv_columns">
<label for="file">choose csv file</label>
<input id="input-file" autocomplete="off" type="file" id="file" name="file">
<input type="button" value="download CSV" onclick="downloadCSV()">
</div>
<div id="schema_select">
<form action="#">
<label for="schema">Schema</label>
<select name="schema" id="schema" multiple>
</select>
<button id="submit-option">Submit</button>
</form>
<input type="text" , autocomplete="off" name="csv-file-name" id="csv-file-name">
</div>
</body>
</html>
window.onload = function () {
inputElement = document.getElementById("input-file")
inputElement.onchange = function (event) {
var fileList = inputElement.files;
parseDatatoGetSchema(fileList[0])
}
var newCsvFileName = document.getElementById("csv-file-name").value
var submitOption = document.getElementById("submit-option");
submitOption.addEventListener("click", function (event) {
var columnsToRemove = handleSubmit(event)
console.log(columnsToRemove)
parseDataRemoveColumns(inputElement.files[0], columnsToRemove, newCsvFileName)
});
}
function removeColumns(parsedCsv, columnsToRemove) {
newParsedCsv = []
for (i = 0; i < parsedCsv.data.length; i++) {
newObj = {}
for (key in parsedCsv.data[i]) {
if (!(columnsToRemove.includes(key))) {
newObj[key] = parsedCsv.data[i][key]
}
}
newParsedCsv.push(newObj)
}
return newParsedCsv
}
function showCsvSchema(results) {
//Data is usable here
var schemaForm = document.getElementById("schema")
// ajoute le nœud texte au nouveau div créé
for (i = 0; i < Object.keys(results.data[0]).length; i++) {
var opt = document.createElement('option');
opt.value = Object.keys(results.data[0])[i];
opt.innerHTML = Object.keys(results.data[0])[i];
schemaForm.appendChild(opt);
}
}
function handleSubmit(event) {
event.preventDefault();
var schemaSelect = document.getElementById("schema")
columnsToRemove = [...schemaSelect.selectedOptions].map(o => o.value)
return columnsToRemove
}
function parseDatatoGetSchema(url) {
csvData = []
Papa.parse(url, {
header: true,
dynamicTyping: true,
complete: function (results) {
showCsvSchema(results)
}
});
}
function parseDataRemoveColumns(url, columnsToRemove, newCsvFileName) {
csvData = []
Papa.parse(url, {
header: true,
dynamicTyping: true,
complete: function (results) {
newParsedCsv = removeColumns(results, columnsToRemove)
unParsedNewCsv = Papa.unparse(newParsedCsv)
downloadCSV(unParsedNewCsv, newCsvFileName)
}
});
}
function downloadCSV(unparse_csv, newCsvFileName) {
var csvData = new Blob([unparse_csv], { type: 'text/csv;charset=utf-8;' });
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, `${newCsvFileName}.csv`);
}
else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', `${newCsvFileName}.csv`);
tempLink.click();
location.reload()
}

How to save input form data as an array in PHP

I have a form which takes a student name, subject and age. When submitted, it saves the data as an array in txt file. Next time, when I put new data and submit it, it creates a new array in that txt file instead of appending it to the previous array.
<?php
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = [];
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.txt', $str, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="name">Subject:</label>
<input type="text" name="subject" id="subject">
<label for="name">Age:</label>
<input type="number" name="age" id="age">
<input type="submit" name="submitButton">
</form>
</body>
</html>
output looks like this:
however I want to save it like below:
How could I do that?
If you really have to see your nice array in text use this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$expl = explode("[".$int."] => Array", $fgc);
while (count($expl) > 1) {
$expl2 = (count($expl) > 1) ? explode("[".($int+1)."] => Array", $expl[1])[0] : $expl[1];
$m = preg_match_all("#\\[([\d\w]+)\\] => ([^\n]*)#imus", $expl2, $matches);
if ($m == 0) { break; }
foreach ($matches[1] as $key => $val) {
$student[$int][$val] = $matches[2][$key];
}
$int++;
$expl = explode("[".$int."] => Array", $fgc);
}
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
$str = print_r($student, true);
file_put_contents('student.txt', $str);
print_r($student);
}
But please use a serialized version like this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$student = unserialize($fgc);
$int = count($student);
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
file_put_contents('student.txt', serialize($student));
print_r($student);
}
print_r for debug only.
Have fun ;)
You have to use JSON in order to update your array constantly.
the important point is you have to load your students in a variable and then push the new student to that variable so, in the end, you can save your students variable which contains all students in one array like you want.
Requirements to make this code works:
Create a file named student.json and put [] inside the file
Also, I highly suggest go and learn about JSON in PHP so you can have a better understanding of how this code is working now
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = json_decode( file_get_contents('student.json'), true);
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.json', json_encode($studentArray));
}

File Type and Size Validation while Uploading it using JavaScript

I am using JavaScript on an HTML form to check the size and type of images before they load.
I am using the following code: JS test.html
<!DOCTYPE html>
<html>
<head>
<title>
File Type Validation while
Uploading it using JavaScript
</title>
<style>
h1 {
color: green;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1> MyForm</h1>
<h3>
Validation of file type and size whileuploading using JavaScript?
</h3>
<!-- File input field 1 -->
<p>Upload an Image 1</p>
<input type="file" id="image1"
onchange="return TypeValidation1(); SizeValidation1();" />
<!-- File input field 2-->
<p>Upload an Image 2</p>
<input type="file" id="image2"
onchange="return TypeValidation2(); SizeValidation2();" />
<!-- Script TypeValidation file 1 -->
<script>
function TypeValidation1() {
var fileInput =
document.getElementById('image1');
var filePath = fileInput.value;
// Allowing file type
var allowedExtensions =
/(\.jpg|\.jpeg|\.png|\.gif)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('Invalid file type');
fileInput.value = '';
return false;
}
}
</script>
<!-- Script TypeValidation file 2 -->
<script>
function TypeValidation2() {
var fileInput =
document.getElementById('image2');
var filePath = fileInput.value;
// Allowing file type
var allowedExtensions =
/(\.jpg|\.jpeg|\.png|\.gif)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('Invalid file type');
fileInput.value = '';
return false;
}
}
</script>
<!-- Script SizeValidation file 1 -->
<script>
function SizeValidation1() {
const fi = document.getElementById('image1');
// Check if any file is selected.
if (fi.files.length > 0) {
for (const i = 0; i <= fi.files.length - 1; i++) {
const fsize = fi.files.item(i).size;
const file = Math.round((fsize / 1024));
// The size of the file.
if (file >= 4096) {
alert(
"File too Big, please select a file less than 4mb");
}
}
}
}
</script>
<!-- Script SizeValidation file 2 -->
<script>
function SizeValidation2() {
const fi = document.getElementById('image2');
// Check if any file is selected.
if (fi.files.length > 0) {
for (const i = 0; i <= fi.files.length - 1; i++) {
const fsize = fi.files.item(i).size;
const file = Math.round((fsize / 1024));
// The size of the file.
if (file >= 4096) {
alert(
"File too Big, please select a file less than 4mb");
}
}
}
}
</script>
</body>
</html>
The code checks the type of images but it cannot check the size.
even for the implementation of two scripts on a single "OnChange" event, I don't know if it is well-written.
help please know that I am a beginner in javaScript.
There are two combined reasons for this:
You return on the first of the two functions in the onchange. This stops javascript from calling SizeValidation1(). Therefore the code in SizeValidation1 is never called.
You use:
<input type="file" id="image1" onchange="return TypeValidation1(); SizeValidation1();" />
instead use:
<input type="file" id="image1" onchange="TypeValidation1(); SizeValidation1();" />
In the for-loop you use 'const' to define i. This should be 'var' since you in the next run of the loop vil override the value of i.
You use:
for (const i = 0; i <= fi.files.length - 1; i++) {
Instead use:
for (var i = 0; i <= fi.files.length - 1; i++) {
I hope this will be of help to you. Have a great day :-)

Javascript FileReader how can I access reader.onload?

I am currently learning Javascript. I'm working on a program with FileReader.
How can I access variable file for variable perf?
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style/style.css">
<title>FileReader</title>
</head>
<body>
<h1>FileReader</h1>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
Input: <input type="text" id="qi" value="">
<br></br>
<button onclick="check()" class="button buttonB">Check</button>
<p id="ans"></p>
<p id=".same"></p>
<script src="main.js"></script>
</body>
</html>
function check(){
var text = document.getElementById("qi").value;
console.log(`Text: ${text}`);
var perf; //The value should be `file`
if (text === perf){
console.log("Same");
document.getElementById(".same").innerHTML = "Same";
} else{
console.log("Not Same!!!")
document.getElementById(".same").innerHTML = "Not Same!!!";
}
}
function openFile(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var file = reader.result;
console.log(file);
document.getElementById("ans").innerHTML = file;
};
reader.readAsText(input.files[0]);
};
Method 1 : Compare the innerHTML you saved
var perf = document.getElementById("ans").innerHTML;
Method 2 : Save the variable in a global scope
Just save the variable file in the global scope :
Replace
var file = reader.result;
By
window.file = reader.result;
And
if (text === perf){
By
if (text === window.file){

How to obtain values of dynamically created select dropdowns in php

I am trying to obtain the values of dynamically created select dropdowns from my php page. The dropdowns were added via javascript to the page.
The error that I get is Notice: Undefined index: daySelect in C:\wamp\www\responsive2\select.php on line 7
I would like to know how to access posted select dropdowns values with php.
Thanks in advance.
Code follows
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
echo "We have something";
echo ($_POST['daySelect']); // error here
}
else
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamic Select</title>
</head>
<body>
<form id="theform" style="display: none" method="POST" name="theform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="placeHere"></div>
<button type="submit">Submit</button>
</form>
<button onclick="createSelect()">Create</button>
<script>
var elem = document.getElementById('placeHere');
var daySelect = new Array();
var theForm = document.getElementById('theform');
var numSelects = 0;
var days = ['01','02','03','04','05','06','07','08','09','10',
'11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29','30',
'31'];
function createSelect()
{
numSelects++;
daySelect.push(document.createElement('select'));
daySelect[daySelect.length -1].setAttribute('id',
daySelect[daySelect.length -1]);
daySelect[daySelect.length -1].name = daySelect[daySelect.length -1];
var opt = document.createElement('option');
opt.text = "Select";
opt.value = "";
//myArray[myArray.length - 1];
daySelect[daySelect.length -1].appendChild(opt);
for (var i = 0; i < 31; i++)
{
var opt = document.createElement("option");
opt.text = days[i];
opt.value = days[i];
//opt.className = i;
//optarr.push(opt[i]);
daySelect[daySelect.length -1].appendChild(opt);
}
elem.appendChild(daySelect[daySelect.length -1]);
theForm.style.display = "block";
//alert("HI");
}
</script>
</body>
</html>
<?php
}
?>
You need to set your select "name" and "id" to a string name. Right now you are setting those 2 attributes to the daySelect object value, which is getting interpreted as a string, so you have:
<select id="[object HTMLSelectElement]" name="[object HTMLSelectElement]">
Update the the .setAttribute and .name lines to:
daySelect[daySelect.length - 1].setAttribute('id',
'daySelect' + (daySelect.length - 1));
daySelect[daySelect.length - 1].name = 'daySelect[]';
The name is set to an array because of the [], so you could just loop through $_POST['daySelect'], with PHP, using a foreach.
Change the echo to print_r to view array values in the browser.
Hope that helps.

Categories

Resources