$apply_id=25;
if(isset($_COOKIE['apply'])){$apply_cookie=$_COOKIE['apply'];}
else{$apply_cookie=serialize(array());}
$apply_cookie=unserialize($apply_cookie);
//HAVE COOKIE
if(in_array($apply_id, $apply_cookie)==TRUE){echo "COOKIE=TRUE<BR>"; print_r($apply_cookie);}
else{
//NO COOKIE,DB HAVE RECORDED
$db=FALSE;//I don't want to query, so just set TRUE FALSE
if($db==TRUE){
echo "COOKIE=FALSE; DB=TRUE";
$apply_cookie[]=$apply_id;
$apply_cookie=serialize($apply_cookie);
setcookie("apply", $apply_cookie);
}
else{
//NO COOKIE,NO RECORDED
echo "COOKIE=FALSE, DB=FALSE";
$apply_cookie[]=$apply_id;
$apply_cookie=serialize($apply_cookie);
setcookie("apply", $apply_cookie);
//process the apply query...
}
}
I have set up a cookie for my apply button, if user have been apply, it will pop message instate to query again, if no cookie, it will check db and update cookie.
I store array(unserialize) into cookie and I use in_array to check.
However if user try to change my cookie, unserialize will get error.
Is any way to set up like- if unserialize=FALSE apply_cookie=array();
something like that
unserialize returns false if it fails.
$apply_cookie = #unserialize($apply_cookie);
if ($apply_cookie === false) {
$apply_cookie = array();
}
use #unserialize, the "#" infront of a function will silence errors
<?php
$apply_id = 25;
if ( isset( $_COOKIE["apply"] ) ) {
$apply_cookie = $_COOKIE["apply"];
}
$apply_cookie = ( isset( $apply_cookie ) ) ? #unserialize( $apply_cookie ) : array();
$apply_cookie = ( is_array( $apply_cookie ) ) ? $apply_cookie : array();
//HAVE COOKIE
if ( in_array( $apply_id, $apply_cookie ) ) {
echo "COOKIE=TRUE<BR>";
print_r( $apply_cookie );
}
else {
//NO COOKIE,DB HAVE RECORDED
$db = false;
if ( $db === true ) {
echo "COOKIE=FALSE; DB=TRUE";
$apply_cookie[] = $apply_id;
$apply_cookie = serialize( $apply_cookie );
setcookie( "apply", $apply_cookie );
}
else {
//NO COOKIE,NO RECORDED
echo "COOKIE=FALSE, DB=FALSE";
$apply_cookie[] = $apply_id;
$apply_cookie = serialize( $apply_cookie );
setcookie( "apply", $apply_cookie );
//process the apply query...
}
}
?>
You should use $_SESSION instead of $_COOKIE.
To unserialzie user inputs is VERY DANGEROUS.
unserialize
http://www.php.net/manual/en/function.unserialize.php
Warning
Do not pass untrusted user input to unserialize().
Unserialization can result in code being loaded and executed due to
object instantiation and autoloading, and a malicious user may be able
to exploit this. Use a safe, standard data interchange format such as
JSON (via json_decode() and json_encode()) if you need to pass
serialized data to the user.
If you defined like the following class:
<?php
class TestClass {
public function __destruct() {
echo '__destruct() called';
}
}
And if you get serialized data:
O:9:"TestClass":0:{}
It will be displayed, __destruct() called.
Related
I am having array of for fields and saving data to the database without issue if I submit without validation.
The trouble I am having is to check for errors existence in foreach iteration before saving any single field data using update_setting( $optionname, $optionvalue );
Current code is saving data for all fields but the error one. So is there any way to first validate all fields and only store to database if there is no single error. Otherwise shoot error message on the page.
$errors = [];
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
// check the field if not set
if ( get_post_field( 'test' ) == '' ) {
$errors['test'] = 'Test field is required';
}
/**
* all loop items only should be add/update if there is not single error
* If any single error occure than it shold not save any single field data
*/
// add/update settings
elseif ( empty( $errors ) ) {
update_setting( $optionname, $optionvalue );
}
}
trivial but may work :)
$errors = [];
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
// check the field if not set
if ( get_post_field( 'test' ) == '' ) {
$errors['test'] = 'Test field is required';
}
/**
* loop all variables
*/
}
if ( count( $errors ) == 0) {
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
update_setting( $optionname, $optionvalue );
}
} else {
//routine or whatever you want to fire errors on the page
}
Rather than hitting the database with an UPDATE query every iteration, why not just run one query? Regardless, you can achieve your goal if you break your code up into two foreach loops, as so:
// first loop validates each option
$errors = [];
foreach($optionNames as $optionName){
$optionValue = get_post_field($optionName);
if( strlen(trim($optionValue)) == 0 ){
$errors[] = sprintf("%s field is required!", $optionName);
// you could break here if you do not want to accumulate error messages
}
}
// if any errors were found, halt execution and output error messages
if( count($errors) > 0){
$errorMessages = implode(",", $errors);
die("Cannot save due to the following errors: " . $errorMessages);
}
// this will only execute if no errors were found
foreach($optionNames as $optionName){
$optionValue = get_post_field($optionName);
update_setting( $optionName, $optionValue );
}
This is not how I would go about doing this, but I chose to answer your question using the code you provided rather than providing something entirely different.
Try to avoid using "else" in situations where returning early (or in my example, halting execution) is an option. It helps clean up your code by providing a clear path to the desired outcome.
I would like to dedicate this page to handling sessions using procedural php.
I'll begin with how I start most of my projects:
session_name('Easy_App');
session_start();
if (!isset( $_SESSION['ip'] )){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}
if (!isset( $_SESSION['created'] )){
$_SESSION['created'] = time();
}
if (!isset( $_SESSION['overall_views'] )){
$_SESSION['overall_views'] = 1;
}
else {
$_SESSION['overall_views']++;
}
if (!isset( $_SESSION['username'] )){
$_SESSION['username'] = "";
}
if (!isset( $_SESSION['logged_in'] )){
$_SESSION['logged_in'] = 0;
}
/*A quick method to keep pageviews to < 5 pages per 1 second per session*/
if (!isset($_SESSION['first_action'])){
$_SESSION['first_action'] = time();
}
$first_action = $_SESSION['first_action'];
if (!isset( $_SESSION['action'] )){
$_SESSION['action'] = 1;
}
else{
$_SESSION['action']++;
}
$action=$_SESSION['action'];
if ($action>=5){
unset($_SESSION['action']);
unset($_SESSION['first_action']);
if((time() - $first_action) <=1){
exit("Please Don't Hammer My Site ");
}
}
So We have a starting point:
The Start of a session with a few regularly used parameters
In the last few lines, prevention of hammering by casual users.
My question is this:
Where would you go from here? Improvements of the above code or a brief snippet of how you handle sessions using procedural php would be greatly appreciated.
Your code would not work If you are trying to STOP Hammer or FLOODING if the user doesn't keep cookies your Sessions are useless and the script is a waste ... you should try better approach using storage systems like memcache , mongoDB or redis
See : https://stackoverflow.com/a/10155437/1226894 .... this has been answered before
EDIT 1
Am not sure what you want by procedural PHP but i hope this helps
Objectives
Remove duplicate isset
Remove duplicate if Statement
Create single function to get and set $_SESSION
Trying to make everything a function and hide all variables
Final Code
session_start ();
include("procedural.function.php");
__SESSION ( 'ip', $_SERVER ['REMOTE_ADDR'] );
__SESSION ( 'created', time () );
__SESSION ( 'overall_views', 1 );
__SESSION ( 'overall_views', "++" );
__SESSION ( 'username', "" );
__SESSION ( 'logged_in', 0 );
__SESSION ( 'first_action', time () );
__SESSION ( 'action', "++" );
if (__SESSION ( 'action' ) >= 5) {
__UNSET ( 'action' );
__UNSET ( 'first_action' );
if ((time () - __SESSION ( 'first_action' )) <= 1) {
exit ( "Please Don't Hammer My Site " );
}
}
procedural.function.php
function __SESSION($var, $value = null) {
if ($value === null) {
return isset ( $_SESSION [$var] ) ? $_SESSION [$var] : null;
} else if ($value === "++") {
isset ( $_SESSION [$var] ) ? $_SESSION [$var] ++ : $_SESSION [$var] = 0;
return $_SESSION [$var];
} else {
isset ( $_SESSION [$var] ) ? $_SESSION [$var] = $value : null;
return $value;
}
}
function __UNSET($var) {
unset ( $_SESSION [$var] );
}
After a user signs in and his password is verified, I need to store his username in a cookie. I tried to simply add setcookie() when the password is successfully verified in the section that looks like if ( $password_match == $user_login_password ) {... but for some reason it doesn't seem to be working. I can't set cookies when a user successfully logins with correct password/username. Is there some reason you can't setcookies from inside a function?
public function write($p) {
if ( $_POST['user_login_username'] )
$user_login_username = mysql_real_escape_string($_POST['user_login_username']);
if ( $_POST['user_login_password'] )
$password = mysql_real_escape_string($_POST['user_login_password']);
$password .= 'some_Salt';
$user_login_password = hash('sha256', $password);
} elseif ( $user_login_username && $user_login_password ) {
$q = "SELECT * FROM users WHERE username = '$user_login_username'";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$password_match = stripslashes($a['password']);
}
if ( $password_match == $user_login_password ) {
echo $this ->display_login('Correct!');
setcookie('user','some_username');
} else {
echo $this ->display_login('Wrong Password!');
}
} else {
echo $this ->display_login('That username does not exist.');
}
return;
} else {
return false;
}
}
I'd do this that way:
function mysetcookie($name, $value, $timestamp=null, $directory='/') {
return setcookie($name, $value, time()+$timestamp, $directory);
}
And I'd be using mysetcookie() instead of setcookie() :) And I'd consider reading this:
http://php.net/manual/en/function.setcookie.php
Ahh I got it. Protocol restriction with setcookie, I was trying to set it after the tags. Thanks to everyone who looked, I should have read the documentation better. Sorry!
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.
function procLogin( $user, $pass, $remember, $hostname, $domainame )
{
global $session, $form;
$retval = $session->login( $user, $pass, $remember );
if ( $retval )
{
if ( $session->userlevel == 9 )
if ( $session->isAdmin() )
return ( array(
$session->userlevel, $session->userid
) );
} else {
$process = new process( );
//process->s_Host('domain.com');
//$process->s_Domain('domain.com');
$process->s_Host( $hostname );
$process->s_Domain( $domainname );
$process->s_processSecure( false );
$process->s_User( $user );
$process->s_Pass( $pass );
// First check we actually have a username and password set inside the process object.
if ( $process->g_User() && $process->g_Pass() )
{
if ( $process->processConn() )
{
if ( $process->processBind() )
{
return 'google';
}
}
}
}
}
My problem is if the login is false, why does it not turn towards else condition....
if i remove the code inside else part and put return 'no' it does work.... i just want to know why the code inside the else part does not execute
$session->login(... must somehow always evaluate to true. You would probably be better off posting the code of the login method.
Maybe login is returning "false" as a string? It is evaluating to true because it is not null.
Without a specific error or details of the implementation, or a hint that the PHP runtime or builtin or library is broken ...
This looks like a case of go back, check, debug.