I am writing a web application in php where users can upload their own files or images, but how can I protect these files from being accessed by others other than the owner
If you are storing images and files as binary blobs in your database, then it is simply a matter of checking permissions against the logged in user before retrieving and displaying them from the database.
If you are storing them as regular files, what you need to do is store them above the document root of your website, where they are not publicly accessible on the web. Then to retrieve an image, after checking the correct ownership from your database (we don't know your architecture, so substitute however you have stored what belongs to whom), PHP can retrieve the file and send it to the browser with the correct headers.
For example, to display an image:
// Check permissions...
// If permissions OK:
$img = file_get_contents("/path/to/image.jpg");
// Send jpeg headers
header("Content-type: image/jpeg");
// Dump out the image data.
echo $img;
exit();
You can, for example, keep a database table of filenames matched with user IDs to keep track of who owns what.