PHP and Python for absolute beginers

Explicitly explained codes, and well written articles , a better place to learn programming

Securing image upload box using PHP

How to make Image upload box secure using PHP

Now day , it is common to see image upload boxes in several sites - forums,social networks,blogs... upload boxes are fun and good way to interact with users ,But,at the same time,  they could be a way for any attacks made up on a site if they are not cleverly utilized.



Bad guys can use security holes on upload boxes for their own advantage.This bad guys ,for instance, upload malicious shell (executable code)  which could have a power to unveil all information we kept secret for several years,or which  may also used as backdoor, a way get in to the site later after the security hole is patched.




The common and usual way to check if the uploaded file is image using $_FILES['upload']['type']. However this is will be increasingly great risk if ahacker happens to find that you are using this method to secure your upload box.Because,any thing under $_FILES other than 'tmp_name' can be manipulated by just making simple tampering before the data is sent to the server. This is would be a great risk if a bad guy upload rotten script using this for advantage.



in the description to come I will show you some excellent ways to make super secure Image Upload box.
1.  check to see if the uploaded file is image
The above function is basically used for creating image handlers from pre-existing images, you can think of image handlers as file handlers.  The parameters for this function should only be location of an png image. if any other file location is given as argument ,then,it throws exception.since I used error control operator in front of the function call createimagefrompng()  no error message is going to be printed.


The condition in the if statement can only be executed if and only if the function,
createimagefrompng(), runs with out any mess or error. if this happens to be false or the function,createimagefrompng(),fails at some time of execution and throws exception, the code in side in the else statement get executed. The only case the function throws exception is when file other than Image is given as argument.

Thus,checking whether exception is throwed can be a best way to check if it is image. This works for png images only, but if you want to check the file type of jpg images uses imagecreatefromjpeg()

getimagesize() is another PHP function which gives us much more information about images. this function returns associate array.

To make a brief overview of the above function, it calls the getimagesize() function and using the if else statement the code checks if any exception is thrown.then it enlist the mime information using the mime key ,and checks if it is png.

Like that of imagecreatefrompng () or imagecreatefromjpeg(), this function also throws exception if image is not given as parameter.

2. Checking the name of the image

So far, we have seen how to check the file type,But hackers also can mess up a website using the name of images. for example,they may make the name of image '../../../../../../../../../etc/passwd' or something which directs to a certain file.
When Your browser tries to display this image,it ,the browser, will be redirected to the given directory,which may cause local file inclusion,another type of attack.

Furthermore, images with the same name may replace already stored image.
so,The best way to rectify this problem is renaming the image-giving a unique name for each image.

The above code shows a way to rename the uploaded image to unique name. this is done by concatinating the current time stamp and and md5 hashed imagename. click here to find more about generating unique name.

Even if the above methods are good enough way to secure image upload box,still it is not the safest way.Because there are also other methods or way to trick the functions imagecreatefrompng() and getimagesize().

Soon,I will discuss how to tackle this problem,But for now this is more than enought. Dont forget to leave a comment. Your comments encourage to post more intersting articles


Recursion

In python it is possible a function to call it self, this is called recursion .It is mostly used to solve complex problems, that can be broken down into smaller, identical problems. it seems a bit weird concept to understand,But it is not as it sounds. let me show you one clever example which could be easy way to get used to recursion.

Factorial notation would be best example for recursion. what does factorial notation even mean ?
If we say, 6!, which is read as 6 factorial, it shows the product of numbers from 1 to 6. if you take any number, lets say n, and if you say I want to calculate the n! (n factorial) , in other word you are saying  that I want to calculate 1x2x3x4...(n-2)x(n-1)xn . it is pretty straight forward, eh ?
 Note : the factorial of 0 ( 0!) is 1. 

You can write a python code which calculate the factorial of any number. there may be several ways to tackle this problem,but the best and clever way would be recursion. with out further ado lets see what the code looks like.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
 
How it works
 
The above code shows a function which calculates factorial.  it takes n as a a parameter. n is the number that we want to calculate its factorial.
the first condition is called the base case. it checks if the value of n is 0 and if the condition happens to be True, then it returns 1. In recursion you need a base case in order to prevent infinite loop. otherwise, your code will continue executing forever. But in my factorial  function I check if the value of n is 0, which happens at some time of the loop.

factorial image


As you see in the figure , I calculate the factorial of 3. first I check if 3==0, since 3 is different from 0, it execute the code in the else statement. once it  gets in to the else statement. it will get the line return n * factorial(n - 1),this line return product of 3,the current value of n, and factorial(2). here, I call the function factorial, but in this time value of n is  one less from the previous this means n is 2 now.  then the function factorial(2) begin to execute, it checks if 2==0 is True, since it is false , it gets in to the else statement then it returns 2*factorial(1,)then the function call factorial(1) go through  the same stapes,but this time it returns 1*factorial(0). now the value of n is 0 , so the base case become True, then the code in the if statement will run for the first time and it returns one.
Finally when everything get evaluated , the function returns 6, which is the product of 3*2*1

As you saw in the previous example , recursion is not as difficult as it sounds. once you get used to the concept ,you could use it to solve several problems. In short, it is clever way to approach problems.

However, most likely whatever solved with recursion can be done with loop - either while or for loop. and loops are more efficient than recursive. recursive uses more memory than for loop. so why you bother learning recursion ? when we come to complex problems,however, recursion become more handy ,easier and simpler.
 
 

Prime Factorization

Prime numbers are numbers  in which their factors are one and the number it self. for example, 5 is a prime number because factors of 5 are 1 and 5 itself. However , 6 is not prime number because its factors are not only one and six but also 2 and 3. Prime numbers  have wide range application in the science of cryptography,  the art of creating secret code, or unraveling secret code.

Prime Factorization is a a process of expressing a number using a multiple of prime numbers. for example, we can express 30 as 2x3x5. Here, we are able to express 30 as a multiple of prime numbers: 2,3,5. every number can be expressed as a product of prime numbers.

Here is the python code.

def factor(n):
    m = []
    x = 2
    while x <= n:

        while n%x==0:
            m.append(x)
            n = n/x

        x +=1
    print m
    m = [1]
    x = 2

                                            How it works

I created a function called factor, which accepts n as a parameter. you can change the name of the
function and the name of the variable to whatever you want, but it is advicable if you make it some thing pertaining to its purpose. Naming a function about factoriazation as protein sound weird,even if it is
possible.

Then I create to local variable m and x and define their value. 'm' is used to store all prime factors and x is used to store each number which ranges in [2,n] turn by turn.

following the variable declaration, we get in to while loop. what this loop basically does is, it checks
if the value of x is not greater than the number you want to calculate its prime factors.  the while loop
breaks (stops) if the value of x is greater than n. I did this because I know in my elementary school mathematics class that the prime factors of a number couldn't exceed the number. you can't have a prime factor 7 for the number 6.

the second while loops is used here in order to check if the remainder of n divided by x is 0.
I did this using the module (%) operators. This operator is an operator like that of addition(+),
multiplication (*) , division(/) and subtraction (-), But it is used to calculate the remainder
when two numbers are divided. for example,4%2 = 0 Because the remainder we get when we divide 4 by 2 is 0.
 Note: if you divide any number by its factor, then its remainder is 0.

 if the condition, n%x == 0, goes True, then the code \ in the while loop get executed.
 the first line in the while loop used to append x in the list m, which we defined earler. then the next line
 changes the value of n to n/x. this while loops break when n%x is different from 0. this means when
 x is no longer factor of n.This loop get exectued untill the value of x exceeds the value of n.
 
in the end, when all thing get its accomplishment, we print the value of m, which contains all prime factors, in a list.

Don't Forget to leave a comment.
 
  .