Okay, so basically i need a little helpt with some validation code.
I need to see if the user has actually selected an image, if not, $error = 1;.

I tried this:

if($_FILES['image']['name'] == "") {
echo 'Error: Select an image!';
$error = 1;
}

I tried several times to put the code in with the rest of the validation code (image size, extension etc.), but it wont work. Once i try to upload with empty image field it says: Error: Select an image!File uploaded successfully!. And there are errors at line 119.

If anyone has time to help me, i will be pleased, it also would be good with a little explanation why this does not work.

Whole code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Puffys Net - Funny Shit</title>
	<link rel="stylesheet" type="text/css" href="../resources/home.css"  />
	<link rel="shortcut icon" type="image/png" href="../#" />
</head>

<body bgcolor="#232323" link="transparent" vlink="transparent" alink="transparent">
<table width="100%" border="0">
	
	<tr>
		<td></td>
		<td width="650px;">
			<div id="top" align="center">
			<div id="logo"><a href="http://www.puffys.net"><img src="../resources/logo.png"  height="312" widht="502" /></a></div>
        
			<div id="navigation">
			<ul>
            <li><a href="../page_funnyshit/funnyshit">-Funny shit</a></li>
			<li><a href="../page_funnyshit/photoshop">--Photoshop</a></li>
			<li><a href="../page_funnyshit/bloag">---Bloag</a></li>
			</ul>
			</div>
			</div>
		</td>
		<td></td>
	</tr>
			
            
            
	<tr>
		<td></td>
		<td width="650px;">
    		<div id="uploader" align="center">            
				<?php
	
					//Database connect
					include 'dbconnect_images_pc.php';
					
					define ("MAX_SIZE","3000"); 
					$passkey = 'random_password_here';
					
					//Checks the file extensions
					function getExtension($str){
						$i = strrpos($str,".");
						if (!$i) { return ""; }
						$I = strlen($str) - $i;
						$ext = substr($str,$i+1,$I);
						return $ext;
					}
	
					//If error, value change to 1, file will not be uploaded
					$errors=0;
							
					if (isset($_POST['Submit']))
					{
						
						//Did the person select an image?
						if($_FILES['image']['name'] == "") {
						echo 'Error: Select an image!';
						$error = 1;
						}
						
						//Reads the image name
						$image=$_FILES['image']['name'];
						//If not empty
						if ($image)
						{
							//Get orgiginal name from client machine
							$filename = stripslashes($_FILES['image']['name']);
							//Get the extension
							$extension = getExtension($filename);
							$extension = strtolower($extension);
			
							//If file extension not known, error. If not, continue
							if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
							{
								//Error message
								echo 'Error: Only JPG, JPEG, GIF and PNG allowed!';
								$errors = 1;
							}
							else
							{
								//Get the size of the image in bytes
 								//$_FILES['image']['tmp_name'] is the temporary filename of the file
 								//in which the uploaded file was stored on the server
								$size=filesize($_FILES['image']['tmp_name']);

								//Compare the size with the maximum size we defined and print error if bigger
								if ($size > MAX_SIZE*1024)
								{
									echo '<h1>Error: Image is too big!</h1>';
									$errors=1;
								}
				
								//Giving the uploaded files new name
								$image_name = time().'.'.$extension;
								//Uploaded image will have the path as a name
								$newname = "images/".$image_name;
								//Error when copying image to storage
								$copied = move_uploaded_file($_FILES['image']['tmp_name'], $newname);
				
								if (!$copied)
								{
									echo 'Failuuuure. Try again.';
									$errors = 1;
								}}}}
								
								

								
					//If no errors do this
					if (isset($_POST['Submit']) && !$errors)
					{
					echo 'File uploaded successfully!';
					$sql = "INSERT INTO images (id, name, path) VALUES ('', '$image_name', '$newname')";
								
					$result = mysql_query($sql);
					mysql_close($conn);
					}
				?>
                
				<form name="uploader" method="post" enctype="multipart/form-data" action="">
				<input type="file" name="image"><br /><br />
                <input name="password" type="password" value="TheGame"/>
				<input name="Submit" type="submit" value="Upload">
				</form>
                
 			</div>
		</td>
        <td></td>
	</tr>
    
    
    	
	<tr>
		<td></td>
		<td width="650px;">
			<div id="footer" align="center">
			<p>Copyright &copy; 2011 by <a href="http://www.puffys.net">Kaizokupuffball</a></p>
			<p>You can contact the owner of this site by <a href="mailto:kaizokupuffball@gmail.com">mail</a></p>
            <p>I do <b>not</b> take any responsibility of what other people upload at funnyshit section.</p>
			</div>
		</td>
		<td></td>
	</tr>
    
</table>
</body>
</html>

Dani AI

Generated

Quick expert note: good catch by — echoing an error without stopping the script will still let the upload path run, and a mismatched variable name for your error flag will let the final "success" branch run even when you meant to block it. , since you fixed the typos that probably solved the immediate problem, here are a few concise, practical safeguards to prevent the same class of bug and to harden image uploads.

Always check the PHP upload error first, and bail out early if anything is wrong. Relying on $_FILES['image']['name'] == "" is brittle. Use $_FILES['image']['error'] (UPLOAD_ERR_NO_FILE, UPLOAD_ERR_OK, etc.), then inspect the uploaded temp file only when the error code is OK. Also prefer $_FILES['image']['size'] (or your own byte limit) over calling filesize() on a possibly-empty tmp file.

Example pattern (early-return style):

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['image']) || $_FILES['image']['error'] === UPLOAD_ERR_NO_FILE) {
        $errors[] = 'Select an image.';
    } elseif ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = 'Upload failed (code ' . $_FILES['image']['error'] . ').';
    }

    if ($errors) {
        foreach ($errors as $e) echo $e, '<br>';
        return; // stop further processing so you don't get conflicting messages
    }

    $info = getimagesize($_FILES['image']['tmp_name']);
    if ($info === false) { echo 'File is not a valid image.'; return; }

    // continue with size, MIME, extension checks and safe storage...
}

Additional tips: verify MIME with finfo or getimagesize, enforce a byte limit, generate safe unique filenames, store uploads outside the webroot when possible, and switch from the deprecated mysql_* API to mysqli or PDO with prepared statements for DB inserts. These measures avoid mixed up flags, false positives, and common security pitfalls.

Recommended Answers

All 3 Replies

Because on line 62 - 65 when you catch the error, you do nothing to stop the execution of your script.

I just realised i had spelling errors..
Fixed it all now.
All working :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.