i need to edit in this code, i need to submit the form even if there is no images selected. when i submit the form without selecting images i got this error "Unknown extension!", as i want to submit the rest of the data without images
<?php
$session_id='1'; //$session id
define ("MAX_SIZE","9000");
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");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' width='50px' height='50px' class='imgList'>";
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
$ad_id=$_POST['ad_id'];
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created,ad_id) VALUES('$image_name','$session_id','$time','$ad_id')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
}
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
?>
Your code is looking for a file extension on something that doesn't exist. That's the error. If you don't want to require images, make the check only run if there is an image submitted.
You can do this by wrapping your image code in this:
if(isset($_FILES['photos']) && $_FILES['photos']['size'] > 0){
}
This code checks to see if there was a file uploaded to the temp directory and if it has a size greater than 0. PHP by default returns a size of 0 if there is no file uploaded.
As noted in the comments by Alexis_user, your query needs to be moved outside of this if statement to make sure it continues to run. However, your insert may be wrong if you are expecting an image in the query.
You could keep the query where it is and simply add a second query:
if(isset($_FILES['photos']) && $_FILES['photos']['size'] > 0){
//Do image stuff and query
}else{
//Do query without image.
}