CGI (shell script) not write in the file with echo command - html

I'm having problems to write in the file with my CGI.
I make a simple HTML formular to press a button and write a phrase in the .txt file, but it doesn't work.
The server is an Apache2.
The scrips works if executed in the terminal.
ps. The final line of CGI works, updating a HTML page URL.
file index.html
<html>
<title>BeagleBone</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<div class="w3-container w3-green">
<h1>BeagleBone GPIO Control</h1>
<p>Acesso remoto a GPIO's em rede local</p>
</div>
<div class="w3-row-padding">
<div class="w3-third">
<h2>GPIO x</h2>
<p>Led blue</p>
<form method="POST" action="/cgi-bin/led.cgi">
<input type="submit" name="led" value="ON">
<input type="submit" name="led" value="OFF">
</form>
</div>
</body>
</html>
file led.gci
#!/bin/bash
LED_FILE="/home/gpcosta/Desktop/data.txt"
read CONTENT
if [ "$CONTENT" == "led=ON" ]; then
echo "Apertou botao ON" >> $LED_FILE
elif [ "$CONTENT" == "led=OFF" ]; then
echo "Apertou botao OFF" >> $LED_FILE
fi
echo "Content-type: text/html"
echo ""
echo '<html>'
echo '<meta http-equiv="refresh" CONTENT="0;url=http://192.168.15.20/index.html">'
echo '</html>'
The cgi permissions below
enter image description here

It's because the web server don't have permissions on the directory.
To solve this, run the following script on your cgi server:
echo “content-type: text/html”
echo “”
echo “<html>
<head>
<meta charset='utf-8'/>
<title>What permission?</title>
</head>
<body>
<p>Run this on your server terminal:</p>
<pre>chown $(whoami) ${PWD}
chmod 755 ${PWD}</pre>
</body>
</html>”
Then simply copy the script your web browser will display and paste it on the CGI Server terminal, remember to run it with a priviledged user.

Related

Convert all french accents into HTML character format

I have for example a bunch of HTML pages like this :
<!DOCTYPE html>
<html>
<head><title>Table des matières</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<!-- 3,html,xhtml,charset="utf-8" -->
<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />
<script type="text/javascript" src="./jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
$('div.caption span.id').each(function() { var result = $(this).text().replace(':','');
result=capitalizeFirstLetter(result);
$(this).text(result);
});
});
</script>
</head><body
>
<!--l. 125--><div class="crosslinks"><p class="noindent">[<a
href="chapter1.html" >next</a>] [tail] [<a
href="/sciences/index.html" >up</a>] </p></div>
<h2 class="likechapterHead"><a
id="x2-1000"></a>Table des matières</h2>
<div class="tableofcontents">
But impossible to convert all french accents in these HTML pages like above the accent in
"Table des matières" with "è" appearing instead of "è".
I tried 2 things :
for i in $(ls *.html); do iconv -f iso-8859-1 -t utf8 $i > $i"_new"; mv -f $i"_new" $i; done
=> the accents are not converted
for i in $(ls *.html); do recode ..html $i; done
=> I have the following errors :
recode: section5.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section6.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section7.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section8.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: section9.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
recode: table_of_contents.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
...
I don't know what to do to convert all these french accents ?
Has anyone got an idea or suggestion to convert all possible french accents ? I would like to use iconv, recode or sed commands.
UPDATE 1: taking a basic example, here is the message I get for a single file :
$ recode ..html table_of_contents.html
recode: table_of_contents.html failed: Invalid input in step `CHAR..ISO-10646-UCS-2'
What's wrong ?
UPDATE 2: here is the output of my original HTML pages :
$file -i index.html
$ index.html: text/x-tex; charset=iso-8859-1
and the head of the index.html :
<!DOCTYPE html>
<html>
<head><title>Table des matières</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<!-- 3,html,xhtml,charset="utf-8" -->
<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />
<script type="text/javascript" src="./jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
$('div.caption span.id').each(function() { var result = $(this).text().replace(':','');
result=capitalizeFirstLetter(result);
$(this).text(result);
If I apply the command :
$ recode -vfd u8..html index.html
Request: UTF-8..:libiconv:..ISO-10646-UCS-2..HTML_4.0
Shrunk to: UTF-8..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
and
<!DOCTYPE html>
<html>
<head><title>Table des matires</title>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<meta name="generator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<meta name="originator" content="TeX4ht (http://www.tug.org/tex4ht/)" />
<!-- 3,html,xhtml,charset="utf-8" -->
<meta name="src" content="content_final.tex" />
<link rel="stylesheet" type="text/css" href="content_final.css" />
<script type="text/javascript" src="./jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
$('div.caption span.id').each(function() { var result = $(this).text().replace(':','');
result=capitalizeFirstLetter(result);
$(this).text(result);
});
});
</script>
as you can see, the "è" has disappeared.
What can I do ?
Assuming the source file encoding is UTF-8. Following command worked in my environment:
$ recode -vfd u8..html index.html
Output:
$ locale charmap
UTF-8
$ file -i index.html
index.html: text/html; charset=utf-8
$ recode -vfd u8..html index.html
Request: UTF-8..:iconv:..ISO-10646-UCS-2..HTML_4.0
Shrunk to: UTF-8..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
You can use the command options to debug the error in this way:
-v Verbose output. Useful to find in which step the error occurred.
-f Forces the completion even if error occurred. You can compare the output file with original to figure out which character/location is giving trouble.
-d For HTML, recode doesn't convert ASCII characters. Avoids conversion of < > " & etc. html characters.
Update If the encoding/charset is iso-8859-1 then you need to use:
$ recode -vfd iso-8859-1..html index.html
Request: ISO-8859-1..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
#Or use following.
$ recode -vfd lat1..html index.html
Request: ISO-8859-1..ISO-10646-UCS-2..HTML_4.0
Recoding index.html... done
The ISO-8859-1 has following aliases in recode:
l1
lat1
latin1
Latin-1
819/CR-LF
CP819/CR-LF
CSISOLATIN1
IBM819/CR-LF
ISO8859-1
iso-ir-100
ISO_8859-1
ISO_8859-1:1987
You can use anyone of the above in the command.

Real time html editor for download

I like solution in this post Real-Time Html editor with Javascript or editor on this site. Just simple solution without extra functionalities.
How to edit the code to add SAVE/LOAD option? Is there somethin like "downloadable little CMS" to play with HTML/CSS? I want upload it to my hosting, easy access from home/phone/work, I do not want use online services like codepen or Liveweave.
thanks!
EDIT: Due to comments, I will clarify my question. I have some hosting, mySite.com. There is folder with this magic editor, mySite.com/xxx where i have some sample images and some basic css etc.. Im learning html/css, so I developing some basic html temapltes. HTML editor I linked is just fine. Only I need add 3 buttons, NEW/OPEN/SAVE which make new html file/can open it in live editor/and save it. AND I WANT HAVE THIS EASY SOLUTION ON MY OWN HOSTING.
<?php
$fileName = "page.html";
$fileContent = fopen($fileName, "r") or die("Unable to open file!");
if (isset($_POST['text'])) {
file_put_contents($fileName, $_POST["text"]);
}
?>
<!DOCTYPE html><html lang="cs"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.error {background-color: red; color: white;}
</style>
</head><body>
<form method="POST">
<textarea name="text" class="form-control" rows="20" id="pure">
<?php echo fread($fileContent,filesize($fileName)); ?>
</textarea><br>
<input type="submit" value="submit" />
</form>
<hr>
<div id="compiled"></div>
</body>
</html>
<?php
fclose($fileContent);
?>
<script type="text/javascript">
var h = document.getElementById("pure");
var compiled = document.getElementById("compiled");
h.onkeyup = function() {
compiled.innerHTML = h.value;
pure.classList.toggle("error",
compiled.innerHTML !== h.value);
};
h.onkeyup();
</script>
Its my actual work, real-time html editor from link in my question. File "page.html" must exist.
Added func. to load content from "page.html" file into textarea when page loads..
Added button to save textarea content to "page.html" when done..
Probably not perfect code, and for multiple projects must copy into diferent folders and load one by one :( no popup or form to choose diferent filename easily.. but for now it fits my requirements. I can learn/try/work on html template from home/work/mobile on my own hosting without login into third party service.
Ok, I'm done. Here is my final solution.
real-time html editor
Load/save buttons
automatically load files from /projects/ folder into dropdown list
you can upload files to make new project
no need to modify anything, you can just use it.
Index.php
<?php
$fileName = $_POST['project']?? 'index.html';
$fileContent = fopen("./projects/" . $fileName, "r") or die("Unable to open file!");
if (isset($_POST['text'])) {
file_put_contents("./projects/" . $fileName, $_POST["text"]);
}
?>
<!DOCTYPE html><html lang="cs"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.error {background-color:red; color:white;}
.dib {display:inline-block;}
</style>
</head><body>
<?php
echo "<form class='dib' method='POST'><select name='project'>";
$path = './projects/';
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));
foreach($files as $file){
echo "<option" . (($fileName == $file)?' selected':'') . ">" . $file . "</option>";
}
echo "</select> <input type='submit' value='Load!'></form>";
?>
<input type='submit' form='content' value='Save!'>
<form class="dib" style="float:right;" action="fileUploadScript.php" method="post" enctype="multipart/form-data">
Upload a File:
<input type="file" name="the_file" id="fileToUpload">
<input type="submit" name="submit" value="Start Upload">
</form>
<p style='margin:auto; text-align:center; width:20%; text-transform:uppercase; font-weight: bold;'><?php echo $fileName?></p>
<br>
<form id="content" method="POST">
<textarea name="text" rows="40" id="pure" style="width:100%;margin-top:8px;" wrap="off">
<?php echo fread($fileContent,filesize("./projects/" . $fileName)); ?>
</textarea><br>
<input type="hidden" name="project" value="<?php echo $fileName; ?>">
</form>
<hr>
<div id="compiled"></div>
</body>
</html>
<?php
fclose($fileContent);
?>
<script type="text/javascript">
var h = document.getElementById("pure");
var compiled = document.getElementById("compiled");
h.onkeyup = function() {
compiled.innerHTML = h.value;
pure.classList.toggle("error",
compiled.innerHTML !== h.value);
};
h.onkeyup();
</script>
fileUploadScript.php
<?php
$currentDirectory = getcwd();
$uploadDirectory = "/projects/";
$errors = []; // Store errors here
$fileExtensionsAllowed = ['jpeg','jpg','txt','bmp','html','htm','rar','zip','7z','doc','docx','xls','xlsx','ppt','pptx','pdf','pptm','png','gif']; // These will be the only file extensions allowed
$fileNamee = $_FILES['the_file']['name'];
$fileSize = $_FILES['the_file']['size'];
$fileTmpName = $_FILES['the_file']['tmp_name'];
$fileType = $_FILES['the_file']['type'];
$tmp = explode('.',$fileNamee);
$fileExtension = strtolower(end($tmp));
$uploadPath = $currentDirectory . $uploadDirectory . basename($fileNamee);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensionsAllowed)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 4000000) {
$errors[] = "File exceeds maximum size (4MB)";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo "The file " . basename($fileNamee) . " has been uploaded";
} else {
echo "An error occurred. Please contact the administrator.";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
After you save these two files, dont forget make new folder named "projects" and default file called "index.html" in this folder..

i want my shell script to generate a file with the output in it

so basically, instead of writing over and over again the html code for a website i am building (install page so i need one for each app i offer to download)so i made this script. i want the output to be in a file generated so, on the console it asks what should i name the file (e.g: hi.html) and the output will be in that file in an specific directory on my mac.
# prompt for input.
APP=$1
if [ -z "${APP}" ]
then
read -p "App: " APP
fi
REPORT=$2
if [ -z "${REPORT}" ]
then
read -p "Report App: " REPORT
fi
APPICON=$3
if [ -z "${APPICON}" ]
then
read -p "AppIcon: " APPICON
fi
PLISTURL=$4
if [ -z "${PLISTURL}" ]
then
read -p "plist URL: " PLISTURL
fi
DESCRIPTION=$5
if [ -z "${DESCRIPTION}" ]
then
read -p "Description: " DESCRIPTION
fi
VERSION=$6
if [ -z "${VERSION}" ]
then
read -p "Version: " VERSION
fi
DEV=$7
if [ -z "${DEV}" ]
then
read -p "Developer: " DEV
fi
# Generate the P-List
read -r -d '' HTML << EndOfHTML
================================================================================
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- Your app title -->
<title>My App</title>
<!-- Path to Framework7 iOS CSS theme styles-->
<link rel="stylesheet" href="css/framework7.ios.min.css">
<!-- Path to Framework7 iOS related color styles -->
<link rel="stylesheet" href="css/framework7.ios.colors.min.css">
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/my-app.css">
</head>
<body>
<!-- Status bar overlay for full screen mode (PhoneGap) -->
<div class="statusbar-overlay"></div>
<!-- Views -->
<div class="views">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main">
<!-- Top Navbar-->
<div class="navbar">
<div class="navbar-inner">
<div class="left"> <i class="icon icon-back"></i><span>Back</span></div>
<div class="center sliding">$APP</div>
<div class="right">Report App</div>
</div>
</div>
<!-- Pages container, because we use fixed-through navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-through toolbar-through">
<!-- Page, "data-page" contains page name -->
<div data-page="index" class="page">
<!-- Scrollable page content -->
<div class="page-content">
<!-- Content Here-->
<img src="appicons/$APPICON" class="appinstallicon"/>
<a class="button button-big button-round active installbutton link external" href="itms-services://?action=download-manifest&url=$PLISTURL"><b>1. Install App!</b></a>
<a class="button button-big button-round active installbutton link external" href="prefs:root=General&path=DATE_AND_TIME"><b>2. Change Date!</b></a>
<div class="content-block-title">Description</div>
<div class="content-block tablet-inset">
<div class="content-block-inner">
<p>$DESCRIPTION</p>
<ul>
<li>Name: $APP</li>
<li>Version: $VERSION</li>
<li>Developer: $DEV</li>
</ul>
</div>
</div>
<!-- Content Here-->
</div>
</div>
</div>
<!-- Bottom Toolbar-->
<!-- Toolbar links -->
<!-- Path to Framework7 Library JS-->
<script type="text/javascript" src="js/framework7.min.js"></script>
<!-- Path to your app js-->
<script type="text/javascript" src="js/my-app.js"></script>
</body>
</html>
================================================================================
EndOfHTML
# WHAT TO DO WITH THE OUTPUT.
OUTPUT=$8
if [ -z "${OUTPUT}" ]
then
echo "$HTML"
else
echo "$HTML" >> $OUTPUT
fi
So i dont know how to write in bash to create a file( which i want to name) in an specific directory with the output in it
Given you want to shovel a string into a file. You can do so in two different ways.
The first way to do this would be with a string:
# Here we put the filename which is a string into the variable $FILENAME.
$FILENAME = "foo.html"
# Given that you have built your HTML string and
# put it into a variable called $HTML.
# We can then redirect the output of echoing
# our $HTML variable to our $FILENAME variable.
echo $HTML >> $FILENAME
The second way would be using an argument you pass to the script:
# Here $1 contains the first argument you can pass when running a bash script.
# For example if you ran `bash myscript.sh foo.html` $1 would then contain
# a string "foo.html".
# This will allow you to dynamically generate the file name without having
# to edit your script.
$FILENAME = $1
echo $HTML >> $FILENAME
ie. bash myscript.sh foo.html
Are you passing the filename as the 8th argument. As 0th argument is your script filename containing the script. As #Fazlin pointed out showing the entire commandline you are using would tell if you are missing something.
if the above script is contained in a file called GenerateHtml.sh your commandline should look like:
GenerateHtml.sh "app" "report" "appicon" "plisturl" "description" "version" "dev" "[output].htm"
Here [output] is the name of the html file.

Generating an HTML page using a bash script, but image tags are broken

#!/bin/bash
echo "Content-type: text/html"
echo
echo "<h1>You Rolled 9 dice</h1>"
dice=( /images/die1.png /images/die2.png /images/die3.png /images/die4.png /images/die5.png /images/die6.png)
index=$RANDOM
let "index = index % 6"
href="${dice[$index]}"
echo "<a href=$href><img src=$href></a>"
This is what I have so far. I want the page to stay text/html because I'm going to be writing more on it. It keeps telling me that the requested URL /images/die5.png was not found on this server.
You simply need to remove the leading / character from your image file names:
#!/bin/bash
dice=(images/die1.png images/die2.png images/die3.png images/die4.png images/die5.png images/die6.png)
index=$RANDOM
let "index = index % 6"
href="${dice[$index]}"
echo '<!DOCTYPE html>'
echo '<html>'
echo ' <head>'
echo ' <meta charset="utf-8">'
echo ' <title>Example</title>'
echo ' </head>'
echo ' <body>'
echo ' <h1>You Rolled 9 dice</h1>'
echo " <a href='$href'><img src='$href' alt='image'></a>"
echo ' </body>'
echo '</html>'
After running the script like so:
thomas#yozu-thomas:~/Programming/bashbrowser$ ./makehtm.sh > out.htm
The output I get is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<h1>You Rolled 9 dice</h1>
<a href='images/die3.png'><img src='images/die3.png' alt='image'></a>
</body>
</html>
...which looks like this:
Note: I'm assuming that the file structure is something like this:
makehtm.sh
out.htm
images/
die1.png
die2.png
die3.png
die4.png
die5.png
die6.png
Additionally, you don't need to echo "Content-type: text/html" within the HTML page itself; this is an HTTP header field, and will be handled by the web server that hosts the HTML file.

HTML Upload on iPhone (iOS): filename is always same (image.jpg, image.png, ...)

I am using very simple code to upload files in my responsive website. But when I upload image using iPhone, the image name is always image.jpg irrespective of actual image name.
Any workaround for this problem?
I created this sample page with small code for debugging purpose:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
print "<pre>";
echo 'post object info:';
print_r($_FILES);
print "</pre>";
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload Test for iphone</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
<input name="userfile" type="file" /> <br />
<input type="submit" value="Send File" />
</form>
</body>
</html>
Demo: http://codepad.viper-7.com/VnTfb3/55dev?
I ran into the same problem but I was using 3 images in my upload script. The quickest, easiest solution for me was to add the current date and time in any format (epoch is probably the best for this) as well as a letter or combination of letters to the filename to distinguish the filename.
$date = date('U');
$filename1 = str_replace(' ', '%20', $_FILES['image1']['name']);
$target1 = 'images/';
$file1 = $_FILES['image1'];
$target1 .= $date.'A'.$file1['name'];
$fileName1 = $date.'A'.$file1['name'];
The above is some of the code I used for my script but my script is obviously much different than yours. I just pasted it to show how you can modify the name of a file when it is being processed and uploaded.