- How to display simple one time messages in PHP?
- How to send a WhatsApp message in 30 seconds with PHP?
- How to handle user flash messages via session?
- Saved searches
- Use saved searches to filter your results more quickly
- License
- cmroanirgo/onetime
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- One-time secret message application using PHP-encryption library
- Simple session based “flash” messages
- The function
- Setting messages
- Displaying the messages
- Conclusion
- Related Posts
- 10 Comments + Add Comment
How to display simple one time messages in PHP?
Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.
How to send a WhatsApp message in 30 seconds with PHP?
PHP – Version 7.0 or higher. Twilio Account activated with WhatsApp Sandbox Channel. The above commands create a folder named demo-app in which the twilioWhatsAppMessaging.php and .env files are created inside it.
Which is better flash messages or session based messages?
Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better. And as usual, where there’s a will, and some code- there’s a way!
How to make JavaScript message appear in milliseconds?
Change the 5000 to the time you want the message to stay visible in milliseconds. And remember to set display: none; in CSS for your message, so that it does not appear until jQuery goes in.
Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.
Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better. And as usual, where there’s a will, and some code- there’s a way!
PHP – Version 7.0 or higher. Twilio Account activated with WhatsApp Sandbox Channel. The above commands create a folder named demo-app in which the twilioWhatsAppMessaging.php and .env files are created inside it.
How to handle user flash messages via session?
Handle user flash messages via session variables which is more professional and easy to manage, How we can display these messages in traditional way, developers know how they display messages and update users about status of user operation(s) like record save successfully record updated successfully
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A uber lightweight one time message submission system for php. Great for sending passwords securely
License
cmroanirgo/onetime
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A uber lightweight one time message submission system for php. Great for sending passwords securely. Yes, another one.
- No database required! (Flat files are used)
- This project doesn’t require composer or use autoloaders. It’s old school and small.
- Messages expire after a period of time
- All messages are deleted, the contents are never kept once they’re read.
- No records of deleted messages are stored except (optionally):
- The ID of the message
- The IP of the person who read the message (for security validation requests)
- The time the message expired or was read
- PHP (5 or 7+)
- Apache or similar
- php mail set up and configured
- php mcrypt. (Note that mcrypt itself isn’t used as it’s now considered legacy)
- A fresh subdomain. The .htaccess doesn’t play well in sub diretories.
It’s assumed you’ll want the messages stored outside the publc folder of your webserver. If you can’t do that, then this project probably isn’t for you!
- Download/clone the repo.
- Copy/rename private/includes/config.sample.php to private/includes/config.php and edit a couple of settings.
- If your private folder isn’t beside your public_html , you’ll need to edit index.php and change OT_SRC_PATH to point to the correct location.
- Profit!
About
A uber lightweight one time message submission system for php. Great for sending passwords securely
One-time secret message application using PHP-encryption library
By utilizing an existing PHP encryption library (defuse/php-encryption) and a flat file database library (jamesmoss/flywheel), my application take a secret message from a user, encrypts it using a key derived from a password, and saves it to a flat file. The message can then be decrypted by visiting a unique link and providing the same password. After the message is viewed it is automatically deleted. Encryption (encrypt.php):
$msg, 'error' => $error ); // Return a json object to the requesting page header('Content-type: application/json'); die(json_encode($response_array)); > // Validation checks if ($_SERVER['REQUEST_METHOD'] == "POST") < $continue = true; // Validation: check if it's an ajax request if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') < $continue = false; response('Hold on there. Submission must be an Ajax POST request.', true); > // Validation: check if any of the fields aren't set if((!isset($_POST['ot_secret'])) || (!isset($_POST['ot_encrypt_password'])) || (!isset($_POST['ot_encrypt_password_confirm'])) || (!isset($_POST['ot_email'])) )< $continue = false; response('Hold on there. All fields are required.', true); > else < $secret = filter_var($_POST['ot_secret'], FILTER_SANITIZE_STRING); $password = $_POST['ot_encrypt_password']; $password_confirm = $_POST['ot_encrypt_password_confirm']; $email = filter_var($_POST['ot_email'], FILTER_SANITIZE_EMAIL); >// Validation: check if any of the fields are blank if((empty($secret)) || (empty($password)) || (empty($password_confirm)) || (empty($email)))< $continue = false; response('Hold on there. All fields are required.', true); > // Validation: check if passwords is long enough if(strlen($password) < 8) < $continue = false; response('Hold on there. Your password is not long enough.', true); > // Validation: check if passwords match if($password !== $password_confirm) < $continue = false; response('Hold on there. Your passwords do not match.', true); > // Validation: check for proper email format if(!filter_var($email, FILTER_VALIDATE_EMAIL))< $continue = false; response('Hold on there. Please provide a valid email address.', true); > > // If all of the above validation checks pass, continue on if ((isset($continue)) && ($continue === true)) < // Create random encryption key $iterations = 10000; $salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM); $key = hash_pbkdf2("sha256", $password, $salt, $iterations, 16); // Encrypt secret message, reference: https://github.com/defuse/php-encryption/blob/master/example.php try < $ciphertext = Crypto::Encrypt($secret, $key); >catch (CryptoTestFailedException $ex) < response('Hold on there. Cannot safely perform encryption.', true); > catch (CannotPerformOperationException $ex) < response('Hold on there. Cannot safely perform decryption.', true); > // Save the data $secret = new \JamesMoss\Flywheel\Document(array( 'salt' => base64_encode($salt), 'secret' => base64_encode($ciphertext), 'createdAt' => time() )); $repo->store($secret); // Send email to recipient using SendGrid API $sendgrid = new SendGrid(API_KEY_SENDGRID); $sendemail = new SendGrid\Email(); $message = '
A secret message has been sent to you.
Access it at: ' . URL . '/?id=' . $secret->getId() . '
Thank you!
'; $sendemail->addTo($email) ->setFrom(EMAIL_FROM_ADDRESS) ->setSubject(EMAIL_SUBJECT) ->setHtml($message); //Provide response try < $sendgrid->send($sendemail); response('Message sent! Your secret message has been sent to ' . $email . '.', false); > catch(\SendGrid\Exception $e) < foreach($e->getErrors() as $er) < response('Hold on there. ' . $er, true); > > > else$msg, 'error' => $error ); // Return a json object to the requesting page header('Content-type: application/json'); die(json_encode($response_array)); > // Validation checks if ($_SERVER['REQUEST_METHOD'] == "POST") < $continue = true; // Validation: check if it's an ajax request if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') < $continue = false; response('Hold on there. Submission must be an Ajax POST request.', true); > // Validation: check if any of the fields aren't set if((!isset($_POST['ot_id'])) || (!isset($_POST['ot_decrypt_password'])))< $continue = false; response('Hold on there. All fields are required.', true); > else < $id = $_POST['ot_id']; $password = $_POST['ot_decrypt_password']; >// Validation: check if any of the fields are blank if((empty($id)) || (empty($password)))< $continue = false; response('Hold on there. All fields are required.', true); > // Validation: check if message ID is too long if(strlen($password) > 9) < $continue = false; response('Hold on there. Your message ID is too long.', true); > // Validation: check if message exists if($repo->findById($_POST["ot_id"]) === false) < $continue = false; response('Hold on there. The message ID you entered cannot be found.', true); > else < $secret = $repo->findById($id); > > // If all of the above validation checks pass, continue on if ((isset($continue)) && ($continue === true)) < // Decrypt encyption key using salt and password $iterations = 10000; $salt = base64_decode($secret->salt); $key = hash_pbkdf2("sha256", $password, $salt, $iterations, 16); // Decrypt message using decrypted key, reference: https://github.com/defuse/php-encryption/blob/master/example.php try < $decrypted = Crypto::Decrypt(base64_decode($secret->secret), $key); > catch (InvalidCiphertextException $ex) < // VERY IMPORTANT response('Hold on there. Something\'s wrong, please double check your password.', true); > catch (CryptoTestFailedException $ex) < response('Hold on there. Cannot safely perform encryption.', true); > catch (CannotPerformOperationException $ex) < response('Hold on there. Cannot safely perform decryption.', true); > // Delete message $repo->delete($id); // Provide response response($decrypted, false); > else
$(function() < // Connect to encrypt.php and return response $('#form_encrypt').validator().on('submit', function(e) < if (!e.isDefaultPrevented()) < var formData = $(this).serialize(); $.ajax(< type: "POST", dataType: "json", url: "encrypt.php", data: formData, success: function(data) < if (!data.error) < $("form").trigger("reset"); $("#results").removeClass().empty().addClass("alert alert-success fade in").html(data.msg); >else < $("#results").removeClass().empty().addClass("alert alert-danger fade in").html(data.msg); >>, error: function(xhr, status, error) < $("#results").removeClass().empty().addClass("alert alert-danger fade in").html('Hold on there. An internal error has occured.'); > >); e.preventDefault(); > >); // Connect to decrypt.php and return response $('#form_decrypt').validator().on('submit', function(e) < if (!e.isDefaultPrevented()) < var formData = $(this).serialize(); $.ajax(< type: "POST", dataType: "json", url: "decrypt.php", data: formData, success: function(data) < if (!data.error) < $("form").trigger("reset"); $(".nav, .tab-content").remove(); $("#results").removeClass().empty().html("
" + data.msg + "
"); > else < $("#results").removeClass().empty().addClass("alert alert-danger fade in").html(data.msg); >>, error: function(xhr, status, error) < $("#results").removeClass().empty().addClass("alert alert-danger fade in").html('Hold on there. An internal error has occured.'); > >); e.preventDefault(); > >); >);
I am hoping to get feedback on all aspects of my project — code style, proper PHP/AJAX use, validation/sanitization of user input, and any other security considerations I should be following. For the purpose of this project, I’m going to assume that the people maintaining the php-encryption library know way more about encryption than I ever will, so I’m not really looking for feedback on their library. Similarly, I know a flat file database isn’t ideal, but it was the easiest to get up and running — if I were to ever move this to a production server I would likely utilize a more traditional database.
Simple session based “flash” messages
An article by admin
10 Comments
Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.
Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better. And as usual, where there’s a will, and some code- there’s a way!
Before we get started, make sure that a session is started, otherwise a) no message will be displayed, and b) super fun headers already sent messages.
//Ensure that a session exists (just in case) if( !session_id() )
The rest is as easy as it gets!
The function
/** * Function to create and display error and success messages * @access public * @param string session name * @param string message * @param string display class * @return string message */ function flash( $name = '', $message = '', $class = 'success fadeout-message' ) < //We can only do something if the name isn't empty if( !empty( $name ) ) < //No message, create it if( !empty( $message ) && empty( $_SESSION[$name] ) ) < if( !empty( $_SESSION[$name] ) ) < unset( $_SESSION[$name] ); >if( !empty( $_SESSION[$name.'_class'] ) ) < unset( $_SESSION[$name.'_class'] ); >$_SESSION[$name] = $message; $_SESSION[$name.'_class'] = $class; > //Message exists, display it elseif( !empty( $_SESSION[$name] ) && empty( $message ) ) < $class = !empty( $_SESSION[$name.'_class'] ) ? $_SESSION[$name.'_class'] : 'success'; echo '> >
Setting messages
//Set the first flash message with default class flash( 'example_message', 'This content will show up on example2.php' ); //Set the second flash with an error class flash( 'example_class', 'This content will show up on example2.php with the error class', 'error' );
Displaying the messages
Conclusion
There’s no reason to sweat the small stuff, and hopefully this makes that possible for someone else! I’ve wrapped the messages in a div by default, however, you can obviously get creative and implement this in any way necessary.
Did you enjoy this article? Share it!
Related Posts
10 Comments + Add Comment
Don’t you think using sessions to do this a bit a waste of resources? Why not implement something similar with cookies and JS and cut the persistent server-side storage out of the equation altogether?
I personally always prefer to avoid cookies, although you could certainly replace session usage with cookies and the end result would work just as well
I really love this its esactly what i wanted, how can i make it fade out and / or have an exit button to hide this flash message?
Try adding then in your jquery scripts file (usually script.js in my case) add something such as:
if(‘.fadeout-message’) setTimeout(function() $(‘.fadeout-message’).slideUp(1200);
>, 5000);
>Pretty easily! The following code needs to be inside a $(document).ready(function()<> statement: //NOTE: Make sure you include jquery or this will not work
jQuery(document).ready(function($) if(‘.fadeout-message’) setTimeout(function() $(‘.fadeout-message’).slideUp(1200);
>, 5000);
>
>);