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..
Related
I created a google sign in using Google OAuth 2.0, I configure it using Xamp and php to build the database, I built it outside my project, now I want to include the google sign in button in my project but I kept getting errors. From my localhost, I want to add it to my file first and see how it would look in my page before uploading it. Below is my index.php file
<?php
require_once('config.php');
require_once('core/controller.Class.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="uft-8">
<meta name="viewport" content="width=device-width, inital-scale=1">
<title>Login with Google</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px">
<?php
if(isset($_COOKIE["id"]) && isset($_COOKIE["sess"])){
$Controller = new Controller;
if($Controller -> checkUserStatus($_COOKIE["id"], $_COOKIE["sess"])){
echo $Controller -> printData(intval($_COOKIE["id"]));
echo 'Logout';
}else{
echo "Error!";
}
}else{
?>
<img src="img/20210908_214559.jpg" alt="Logo"
style="display: table; margin: 0 auto; max-width: 150px;">
<form action="" method=:POST>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="email" class="form-control" id="exampleInputEmail1"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1"
placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
<button onClick="window.location = '<?php echo $login_url;?>'" type="button" class="btn btn-danger">Login with Google</button>
</div>
</form>
<?php } ?>
</body>
</html>
It looks like you're expecting to collect the google username and password and then pass that to the google auth engine? That's not the way I've implemented the solution.
Google provide instructions for integrating their sign-in service.
I recommend following those instructions. This will require the following files:
A login page which contains the google sign-in button. You could conceivably add this to any of your existing pages. The relevant code is:
<div class="g-signin2" data-longtitle="true" data-onsuccess="onSignIn"></div>
A javascript file which contains the onSignIn function and a signOut function if you want one. This file handles the redirect to a successful logged in page and also passes the attributes you want to collect from the user's Google account. I'm using XMLHttpRequest, but you could use POST if you wish. This page contains the page that the user will be directed to upon successful login, set in xhr.onreadystatechange = function() {}:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
// console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/oauth.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
window.location = "../loggedin.php"; //Redirect to loggedin page on completion of oauth.php. Determine if new user or existing user and process accordingly
}
xhr.send('idtoken=' + id_token + '&googleId=' + profile.getId() + '&name=' + profile.getName() + '&imageURL=' + profile.getImageUrl() + '&email=' + profile.getEmail());
}
function signOut() {
gapi.load('auth2', function() {
gapi.auth2.init().then(function(){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
document.location.href = 'includes/logout.php';
});
});
});
}
A file to handle the authentication (referred to as includes/oauth.php in my javascript file above). Note the settings for $leeway - this caused me a lot of grief figuring out that the clock on my server was slower than the Google auth server's clock!):
require_once '../vendor/autoload.php';
$jwt = new \Firebase\JWT\JWT; //Allow for discrepancies between server and auth times
$jwt::$leeway = 60;
$CLIENT_ID = "ENTER_YOUR_CLIENT_ID_HERE";
$client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend
$client->setRedirectUri("http://localhost/includes/oauth.php");
$client->addScope("email");
$client->addScope("profile");
if (isset($_POST['idtoken'])){
$id_token = $_POST['idtoken'];
$attempt = 0;
do {
try {
$payload = $client->verifyIdToken($id_token);
$retry = false;
} catch (Firebase\JWT\BeforeValidException $e) {
error_log("JWT server time mismatch. Retry attempt: " . strval($attempt) . "Error: " . $e, 0);
$attempt++;
$retry = $attempt < 3;
}
} while ($retry);
if ($payload) {
$userid = $payload['sub'];
...
YOUR VALIDATION, SESSION SETTING, ETC. CODE HERE
...
} else {
// Invalid ID token
print("Invalid ID token");
}
} else { //Attempt to access this page directly, redirect to Google login page
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
The page that will displayed upon successful login. I used an interstitial page here because the authenticated user could be new to my site and need to create a profile, or could be an existing user and want to go about their activities. I look to verify whether a SESSION has been started and whether this includes a successful authentication.
I'm trying to make some php message sender and receiver Pages.
From the "Admin.php" page, administrator can send messages to the website visitors. And the "receiver.php" page is the visitor's inbox.
Here is the codes:
Admin.php:
<form method="post" action="sender.php">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
Sender.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$message = $POST["message"];
echo "data: {$message}\n\n";
flush();
?>
Receiver.php:
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sender.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
why doesn't this work?
The problem is that you are trying to use "sender.php" to do two things.
From the admin form you need to submit to one php script that will store the messages, in a database of some kind.
Then in "receiver.php" you need to connect to a different PHP script, whose job is to keep polling that database for new entries, and when it sees one it should send it to the client. This latter PHP script will run in an infinite loop.
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.
I think the problem is in the "aif.php" file"
I am trying to fetch and display an array using PHP but the HTML element <br> is showing up in my result from the following scrip. I know I have to escape the HTML tags but I'm just not sure how! Also, any other advice on this code would be greatly appreciated (i.e. is there any redundancy or areas to improve? Thanks.
HTML
<DOCTYPE! html>
<html>
<head>
<title>The Auditors' Report: Data Entry</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header><h1>Work Station<h1></header>
<div = id="leftnav">
<h2>Select Action</h2>
Name: <input type="text" id="name">
<input type="submit" id="grab" Value="Grab">
</div>
<div id="content"></div>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="aif.js"></script>
</body>
</html>
PHP - config (filename: "config.php")
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$dsn = "mysql:host=$dbhost;dbname=$dbname";
$dbh = NULL
?>
PHP - query / resulting content (filename: "aif.php")
<?php
require "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM table1 LIMIT 0,10";
$sth = $dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'],"<br>";
echo $row['field2'],"<br>";
echo $row['field3'],"<br>";
}
?>
Javascript
$('input#grab').on('click', function() {
var name = $('input#name').val();
if ($.trim(name) !='') {
$.post('aif.php', {name: name}, function(data) {
$('div#content').text(data);
});
}
});
If you want to html encode a line like this:
this is <br /> a test
into a line like this:
this is <br /> a test
Use the nifty little function described here: HTML-encoding lost when attribute read from input field
I made a simple error in the Javascript. I wanted to pass back HTML and not TEXT.
With the following change, the PHP is rendered properly:
$('div#content').text(data);
to
$('div#content').html(data);
I just created a simple facebook app. I would like to add a simple html form that posts values to the same file. I wrote the code below, but it doesn't work.
When I type something into the text box of the form and hit submit, the page reloads but it doesn't get any values.
I can't figure out how to post data to the fb app on a canvas page. I would be grateful if you could help me to fix my code. Thanks.
<?php
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => '229924173724291',
'secret' => '79e2bdaaa52bb3b80ea2f5e4c0f20d3e',
));
$user = $facebook->getUser();
if ($user) {
$me = $facebook->api('/me');
} else {
$loginUrl = "https://www.facebook.com/dialog/oauth?client_id=229924173724291&redirect_uri=https://apps.facebook.com/tnxkapp/&scope=publish_stream";
echo "<script>top.location.href=\"{$loginUrl}\"</script>";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<? print($_POST[name]); ?>
<form action="https://apps.facebook.com/tnxkapp/" method="post">
<input type="text" name="name" value="<?php print($name); ?>" />
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>
Post to your actual app URL http://yourdomain.com/appfolder not the apps.facebook.com. You're essentially trying to post info to facebook not your app with what your doing now.