Showing posts with label snippet. Show all posts
Showing posts with label snippet. Show all posts

How to Protect from double posting insert MySQL

Submit once even the visitor is refresh the page from browser.
Here is the way to protect.
Use a SESSION.
1. Set a session in the form page

session_start();
$_SESSION[post_only_once] = 1;
echo "
< form method=\"post\">
Name < input type=\"text\" name=\"name\">
< input type=\"submit\" value=\"submit\" name=\"submit\">
< /form>
";


2. Check the session before doing INSERT into MySQL.
session_start();
if($_SESSION[post_only_once] == 1) {
// here doing insert to mysql
}
unset($_SESSION[post_only_once]); // remove the session after insert

How to connect MySQL from PHP

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

PHP Cut string from MySQL

Shorting or cutting the text string from long char into new max lenght.
Here is the code.
PHP CODE

function short_string ($var, $len){    
if (strlen ($var) < $len) {
return $var;
}
if (preg_match ("/(.{1,$len})\s/", $var, $match)) {
return $match [1] . "..";
} else {
return substr ($var, 0, $len) . "..";
}
}


How to use?
PHPCODE
short_string ("Very very long text is here blablabla", 14);


The Result is:
Very very long..

Insert and Select doing in MySQL from SQL Injection

Here is the save way from RSS Attack SQL Injection.
Get all variable $_POST or $_GET or $_REQUEST or $_SESSION convert into mysql_real_escape string filter, you do not need one by one for all type variable.
here is code.
PHP CODE

$_POST  = array_map('mysql_real_escape_string', $_POST);
$_SESSION = array_map('mysql_real_escape_string', $_SESSION);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);


And here is to view back or mysql_unescape_string or mysql_real_unescpae_string or whatever you want to.
PHP CODE
function mysql_real_unescape_string($string){
$string=trim($string);
$string=str_replace("\\","",str_replace("\$","",$string));
return $string;
}

Convert TEXT2HEX

Here is a php script snippet to convert string text to hex decimal code.
PHP CODE

function text2hex($string) {
$hex = '';
$len =
strlen($string) ;
for ($i = 0; $i < $len; $i++) {
$hex .=
str_pad(dechex(ord($string[$i])), 2, 0, STR_PAD_LEFT);
}
return $hex;
}