here is an upload code i just typed up for you. change the variables to what you need and also change the sql query to your database specifications.
Remember: always store images in a folder on the server and have the path to the file in the database.
here is the code:
<?php
//Change this to the name of the page
$thispage = 'index.php';
//Set the allowed file types
$types = array("gif","jpeg","jpg","png");
//Set max size of image (in MB)
$maxSize = '5';
//Set upload directory
$uploadDir = 'upload';
//This function get the extension of the image
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
if (isset($_POST['submit'])) {
if (empty($_FILES['image']['name'])) {
$result = 'Please choose an image';
}
else {
$imageName = $_FILES['image']['name'];
$exten = getExtension($imageName);
if (!in_array($exten,$types)) {
$result = 'Unknown extension, please choose a different image';
}
else {
$tmpFile = $_FILES['image']['tmp_name'];
$size = filesize($tmpFile);
if ($size > ($maxSize * 1024)) {
$result = 'Image exceeds size limit, choose a smaller image';
}
else {
$newName = $uploadDir . '/' . $time . '.' . $exten;
if (!copy($tmpFile,$newName)) {
$result = 'Unable to upload image, try again';
}
else {
$sql = "INSERT INTO `images` (`image_path`) VALUES ('" . $newName . "')";
$query = mysql_query($sql) or die('Error: ' . mysql_error());
$result = 'Image Uploaded Successfully';
}
}
}
}
}
$html =<<<HTML
<form action="$thispage" method="post" enctype="multipart/form-data">
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right">Image:</td>
<td align="left"><input type="file" name="image" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Upload" /></td>
</tr>
<tr>
<td colspan="2" align="center">$result</td>
</tr>
</table>
</form>
HTML;
echo $html;
?>
there might be some errors because i don't have time to test it. let me know and I will fix it.
kkeith29
Nearly a Posting Virtuoso
1,357 posts since Jun 2007
Reputation Points: 235
Solved Threads: 194