Hi ubaid,
Try the following php code:[php]<?php
mysql_connect(“localhost”,“root”,"");
mysql_select_db(“student”);
$rollno=$_POST[“txtroll”];
$target_path = ‘upload/’;
$filename = $_FILES[‘file’][‘name’];
$destPathFile = $target_path.basename($filename);
$fileExt = substr($filename,-4);
$extentions = array(’.pdf’,’.doc’);
$filetypes = array(‘application/pdf’,‘application/msword’);
$maxSize = 2048000; // 2kb
if(empty($_FILES)) // Most likely the user didn’t choose a file, or php did not allow the upload (check your php.ini file)
{
$errors[] = ‘No file was submitted, or file upload was blocked by php configuration’;
}
if($_FILES[‘file’][‘error’] > 0) // A php error was returned
{
$errors[] = 'File upload lead to the following error: '.$_FILES[‘file’][‘error’];
}
if($_FILES[‘file’][‘size’] > $maxSize) // The file was too large
{
$errors[] = ‘File too large’;
}
if(!empty($filetypes) && !in_array($_FILES[‘file’][‘type’],$filetypes)) // The filetype was not acceptable. DO NOT TRUST THIS TECHNIQUE IF FILE TYPE IS TRULY CRITICAL
{
$errors[] = ‘Wrong file type’;
}
if(!empty($extentions) && !in_array(substr($filename,-4),$extentions)) // The file extention was not acceptable.
{
$errors[] = ‘Wrong file extention’;
}
if(!isset($errors) && file_exists($destPathFile)) // No other errors, but file already exists
{
$errors[] = “Could not save file, $filename already exists.”;
}
else
{
move_uploaded_file($_FILES[‘file’][‘tmp_name’],$destPathFile);
if(!file_exists($destPathFile))
{
$errors[] = “Failed to save file as $destPathFile”;
}
else
{
// NOTE THIS NEEDS TO BE SANITIZED!
$query=“INSERT INTO upload(roll,file) VALUES($rollno,’$target_path’)”;
mysql_query($query);
echo ‘Information is Updated
’;
echo mysql_error();
}
}
if(isset($error)) echo “The following errors were encountered:
”.implode(’
’,$errors);
?>[/php]
You can will want to adjust the $extentions and $filetypes to match what you wish to allow. You can also remove them if you don’t want to limit them. If the filetype is critical, do not trust this method. It can easily be spoofed and you will need to look into better options!
You should also make sure that your php.ini file is not causing a problem. You can add the following to your php code to display the relevant configuration info:[php]phpinfo(INFO_CONFIGURATION);[/php]Among other possibilities, check the upload_max_filesize and post_max_size. Make sure that post_max_size is larger than upload_max_filesize and the upload_max_filesize is at least as large as the largest file you would like to allow.
IMPORTANT: You need to sanitize your query! There are many articles online about this. I was going to link one; however, the forum is not allowing the including of links within posts at this time.
You will obviously want to adjust the above code to work with your application. Let me know if it doesn’t work or if you need help adjusting it.