I found an interesting and useful class file in phpclasses.org, that helps to detect image nudity based on skin pixel score developed by Bakr Alsharif from Egypt. I had integrated this with my previous tutorial Ajax image upload with Jquery and PHP, sure this code helps you to block adult or nudity images.
Download Script Live Demo
Sample database design for Users.
Users
Contains user details username, password and email etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
Sample values.
INSERT INTO `users`
(`uid`, `username`, `password`, `email`)
VALUES
('1', '9lessons', MD5('password'), '[email protected]');
(`uid`, `username`, `password`, `email`)
VALUES
('1', '9lessons', MD5('password'), '[email protected]');
Javascript Code
$("#photoimg").on('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will <i>prepend</i> inside <i>#preview</i> tag.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status. ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
ajaximage.php
Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
//---Image Filter Code
require_once('class.ImageFilter.php');
$filter = new ImageFilter;
$score = $filter->GetScore($_FILES['photoimg']['tmp_name']);
if(isset($score))
{
if($score >= 60) // Score value If more than 60%, it consider as adult image.
{
echo "Image scored ".$score."%, It seems that you have uploaded a nude picture :-(";
}
else
{
//---Image Filter Code
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($connection,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
//---Image Filter Code
}
}
//---Image Filter Code
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
//---Image Filter Code
require_once('class.ImageFilter.php');
$filter = new ImageFilter;
$score = $filter->GetScore($_FILES['photoimg']['tmp_name']);
if(isset($score))
{
if($score >= 60) // Score value If more than 60%, it consider as adult image.
{
echo "Image scored ".$score."%, It seems that you have uploaded a nude picture :-(";
}
else
{
//---Image Filter Code
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($connection,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
//---Image Filter Code
}
}
//---Image Filter Code
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
db.php
Database configuration file, just modify database credentials.
<?php
error_reporting(0);
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
error_reporting(0);
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
nice ,very nice...
ReplyDeleteNice integration. I am sad though. This has blocked a small baby's photo. :(
ReplyDeleteInteresting script here, from the image filter class it seems you can use it for much more than just nude picture. Cool.
ReplyDeleteBlocks only color images, tested it with some black and white and passed all.
ReplyDeleteIt dosnt allow faces eighter.
ReplyDeleteNice but not enough! Based on skin color. It seems we can change the score value. How about BW pictures? Or portrait photos?
ReplyDeleteUseful link and documents
An Algorithm for Nudity Detection
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.96.9872&rep=rep1&type=pdf
Nude.JS
https://github.com/pa7/nude.js/blob/master/nude.js
good article as always :)
ReplyDeleteIt's working pretty good but not perfectly..some nude pics r getting uploaded with out showing any error message..but still impressive...
ReplyDeleteThis is very good script while image uploading to validate nudity basically for images.
ReplyDeletevery nice blur image.. :)
ReplyDeleteVery nice...
ReplyDeletenice tutorial :) i tried it
ReplyDeletevery nice. liked it. ty.
ReplyDeletePlease change the score value 40 to 60 in download script.
ReplyDeleteif($score >= 40)
to
if($score >= 60)
Being able to blur unwanted images is cool idea!
ReplyDeleteI've tested the online demo and the code allowed my upload attempt of one nude image they wasn't blocked or blured or anything in the image, the script is working(online)?
ReplyDeletei've used color image.
i will try it locally, looks good script
i will try it localy.
do you have any idea about securing image?
ReplyDeletewhat if user upload some malicious php script and they changed its extensions before upload.
do you have any idea about securing image?
ReplyDeletewhat if user upload some malicious php script and they changed its extensions before upload.
That is an execellent tutorial but i just want to know that if there is such a class which can detect the nudity of the video file instead of image file.
ReplyDeleteworking! well i'm taking back my last comment!
ReplyDeleteyup.. useful share.Its a common problem in a family who use internet in home.
ReplyDeleteNice sharing
The code works perfectly fine at localhost. However the same code at the server seems like stuck into an infinite for loop and I just see the loading image.
ReplyDeleteAny quick help Srinivas Tamada?
That Great Way and very nice Sri
ReplyDeleteGreat info thank you !
nice..but with some minor glitches. (mostly) gray pictures were considered as nude.
ReplyDeletereally a great post. thanks for sharing this great post
ReplyDeleteGreat script! I like the concept but before reading others' comments. I feared it would have issues with portraits, but together with other validation checks, or even administrator intervention, it would be excellent.
ReplyDeleteAs for user being able to upload malicious script by changing file extension, use file mime type for validation. Eg.
if ($sourceFile_type == 'application/octet-stream'){ -- File is executed, deny upload -- }
if ($sourceFile_type == 'image/jpeg'){ -- File is GENUINE JPEG, Allow upload -- }
User would not be able to fool php to upload any format other than what you accept.
Can this be made into a WordPress plugin ?
ReplyDeleteThank you for this code..im creating social network application...its very useful..
ReplyDeleteDoes anyone have a script which can block Malware, Virus and corrupt jpeg image from uploading on your server.?
ReplyDeleteFor corrupt image, u may check for file size like if ($imgfileSize == "0"){ ...Uploaded file corrupted or missing } though this wouldn't detect an image that is partially corrupted or whose data string is truncated. A partially corrupted file may b complicated at times coz it may b fine apart from having a potion of img replaced by plain color (uniform pixels) which to software cld b the same as the sky, or a plain wall so this may require human discretion to verify.
ReplyDeleteGreat info thank you !
ReplyDeleteI tested this with photos of different skin tone, and the darker the person the more it made it through. I also tested this with a photo of an Egyptian desert and it was blocked.
ReplyDeletereally great man
ReplyDeletei have many erros like this ......
ReplyDeleteNotice: imagecolorat(): 605,539 is out of bound .......
did'nt find the getscore function and image filter class :(
ReplyDelete