php upload file and move to server - php

I want to upload files from my server. I had written this piece of code months ago when it worked fine, but now I have no idea what's going wrong.
I basically want to move the file to a folder "uploads" in my server and then store the path in the database.
The uploaded file doesn't get reflected in the database.
if(isset($_POST['submit']))
{
require("dbconn.php");
$filename = $_POST['filename'];
$name = $filename . "." . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION);
//$name = $_FILES['ufile']['name'];
//$size = $_FILES['file']['size']
//$type = $_FILES['file']['type']
$tmp_name = $_FILES['ufile']['name']; //was tmp_name
$error = $_FILES['ufile']['error'];
if(isset($name))
{
if(!empty($name))
{
$location = 'uploads/';
if(move_uploaded_file($tmp_name, $location.$name))
{
echo "hi";
$filename = $_POST['filename'];
$filepath = $location.$name;
$advname = $_POST['advname'];
$year = $_POST['year'];
$cname = $_POST['cname'];
$ctype = $_POST['ctype'];
$sqlq = "INSERT INTO file(filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');";
$result = mysql_query($sqlq);
if(!$result)
{
die("Error in connecting to database!");
}
}
}
}
}
There seems to be a problem in the
if(move_uploaded_file($tmp_name, $location.$name))
statement. This condition is evaluated as false.

If $_FILES['ufile']['error'] gives you a value of 1 then the upload_max_filesize in your config is set to a smaller value that the file you are trying to upload.
You cannot change the upload_max_filesize from within your code.
If you have access to your php.ini, .htaccess, httpd.conf or .user.ini you can change this value in any of those files.
So you would need to add or modify the parameter from its default of 2M (2meg)
upload_max_filesize = 20M
Its also a good idea to check the post_max_size at the same time as this may also have an effect on the max size of the file uploaded, make sure post_max_size is larger than upload_max_filesize as this should allow extra space for the other fields that you will be uploading as part of the post

Related

Print/debug cause of upload error in PHP

I'm a PHP newbie and have written a script to process form uploads. It works for small files(less than 1Mb). However when I try to upload an ~4Mb pdf file it returns an error message. What am I doing wrong?
PS: I ran php_info, got the value of "upload_tmp_dir" and set it to a directory owned by the apache process(www-data)
My client-side code is
<form action="upper.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile"><br>
<input type="submit" value="Upload">
</form>
Upper.php contains
define("UPLOAD_DIR", "/var/www/html/upload/");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "Error is " . $myFile["error"];
//echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
Most probably you have wrong config in you php.ini file.
You need to set
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
its already described here: PHP change the maximum upload file size
You ned to set values in php.in file.
Open the file,
Find upload_max_filesize and post_max_size lines.
Change this two value. (M= MB)
; Maximum allowed size for uploaded files.
upload_max_filesize = 20M
; Must be greater than or equal to upload_max_filesize
post_max_size = 20M
Restart the sever for effect.
Note:
You can set any number. But not use any decimal value.
Open the php.ini file in NOTEPAD. Don't user wordpad or any word processor.

How To Import Large Excel File To MySql Database Using PHP

I have to upload excel file's data to MySQL database using php. I have found the code for that but I am unable to upload large files.
Can anyone please tell me that how can I increase the max file size limit for the code mentioned in below link:
http://www.9code.in/how-to-import-excel-file-to-mysql-database-using-php/
<!DOCTYPE html>
<?php
include 'db.php';
include 'Excel/reader.php';
function uploadFile($fieldName, $fileType, $folderName, $name = "")
{
$flg = 0;
$MaxID = "";
$ext = "";
$uploadfile = "";
if (isset($fieldName) AND $fieldName['name'] != '')
{
$flg = 1;
$allowed_filetypes = $fileType;
// I Need to increase this..... I tried changing values but nothing happened
$max_filesize = 1048576;
$filename = $fieldName['name'];
if ($name == "")
$MaxID = time() . time() . rand(1, 100);
else
$MaxID = $name;
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if($ext==".xlsx")
$ext=".xls";
if (!in_array($ext, $allowed_filetypes))
echo "<h1>The file you attempted to upload is not allowed...</h1>";
else if (filesize($fieldName['tmp_name']) > $max_filesize)
echo "<h1>The file you attempted to upload is too large...</h1>";
else
{
$uploadfile = $folderName . "/" . $MaxID . $ext;
if (move_uploaded_file($fieldName['tmp_name'], $uploadfile) == FALSE)
{
echo "<h1>Error in Uploading File...</h1>";
$MaxID = "";
}
else
$MaxID = $MaxID . $ext;
}
}
return $MaxID;
}
if(isset($_POST['submit']))
{
if($_FILES['csvFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".csv"),"excel_file");
$row=0;
if(($handle = fopen("excel/".$fileName , "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
//print_r($data);
$query="INSERT INTO StudentData(FirstName,LastName,MobileNo,City)VALUES('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
mysql_query($query);
}
fclose($handle);
}
}
else if($_FILES['excelFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".xls",".xlsx"),"excel_file");
$data = new Spreadsheet_Excel_Reader();
$data->read('excel_file/'.$fileName);
for($i=1;$i<=$data->sheets[0]['numRows'];$i++)
{
$firstname=$data->sheets[0]['cells'][$i][1];
$lastname=$data->sheets[0]['cells'][$i][2];
$mobile=$data->sheets[0]['cells'][$i][3];
$city=$data->sheets[0]['cells'][$i][4];
$query="INSERT INTO StudentData(FirstName,LastName,MobileNo,City)VALUES('".$firstname."','".$lastname."','".$mobile."','".$city."')";
mysql_query($query);
}
}
}
if(isset($_POST['delete']))
{
mysql_query("DELETE FROM StudentData");
}
?>
You can use LOAD DATA command in MySQL : Read More
you have to used load data in mysql statement. This can load your large file in database.
mysqli_query($dblink, '
LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE transactions
FIELDS TERMINATED by ","
OPTIONALLY ENCLOSED BY "\'"
LINES TERMINATED BY "\n"
');
Look at these values in your php.ini
upload_max_filesize = 10M
post_max_size = 10M
You need to set the value of upload_max_filesize and post_max_size in your php.ini :
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
I have to add that you have to restart the server
According to ASNAOUI Ayoub I made the following changes:
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
But Stil the Problem was same then I tried to change the
$max_filesize = 41943040
Now It perfectly works.....
Thanks Everyone for the help

Change name of uploaded file

I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.

File not uploading and moving to folder

$image = $_FILES['picture']['name'];
$id=$_SESSION['id'];
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['picture']['name']) ;
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "mainimage/";
//This combines the directory, the random file name, and the extension
$target = $target . $id.".".$ext;
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
{
echo ("This is your new profile picture!");
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
for some reason the "else" keeps showing up (there was a problem uploading the file). I put comments in everything that I am trying to do. please help! thanks!
To close the question as per OP's request.
The issue is that you need to increase the maximum size for uploads. PHP's default is usually 2M and you are most probably trying to upload a file larger than what the maximum setting is set to.
This can be achieved in two ways.
By editing your php.ini file with the following settings:
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
or via an .htaccess file placed in the root of your server:
php_value upload_max_filesize 20M
php_value post_max_size 30M

Is there a predefined upload limit to $_FILES in PHP?

Hi I'm fairly new to HTML, PHP, MySQL etc.. I am wondering if there is a predefined upload limit using $_FILES. I ask because when I try to upload 8 images of around 1.5 megabytes the code does not work but when I upload 10 images of around 60 kilobytes the code works fine.
Here is my code and feel free to make any criticisms/comments about it:
</head>
<body>
<form action="test.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
<?php
include 'connect.php';
if(!empty($_FILES['image']['tmp_name'])){
$allowed = array('jpg', 'gif', 'png', 'jpeg');
$count = 0;
foreach($_FILES['image']['name'] as $key => $name){
$image_name = $name;
$tmp = explode('.', $image_name);
$image_extn = strtolower(end($tmp)); //can only reference file
$image_temp = $_FILES['image']['tmp_name'][$count];
$count = $count +1;
if(in_array($image_extn, $allowed) === true){
$image_path = 'images/' . md5($image_name) . '.' . $image_extn;
move_uploaded_file($image_temp, $image_path);
mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image_path')") or die(mysql_error());
$lastid = mysql_insert_id();
$image_link = mysql_query("SELECT * FROM store WHERE id = $lastid");
$image_link = mysql_fetch_assoc($image_link);
$image_link = $image_link['image'];
$uploaded[] = $image_link;
}
else{
echo 'Incorrect file type. Allowed: ';
echo implode(', ', $allowed);
}
}
}
if(!empty($uploaded)){
foreach($uploaded as $new){
echo "<a href = $new>$new</a><p></p>";
}
}
else{
echo "Please select an image.";
}
?>
</body>
</html>
You are trying to upload an array of files, you will not be able to upload more than 20 files due to max_file_uploads limit in php.ini which is by default set to 20.
So you have to increase this limit to upload more than 20 files.
Note: max_file_uploads can NOT be changed outside php.ini. See PHP "Bug" #50684
Here are the settings you want to change in php.ini:
post_max_size
This setting controls the size of an HTTP post, and it needs to be set larger than the upload_max_filesize setting.
upload_max_filesize
This value sets the maximum size of an upload file.
Remember to restart your web server after making these changes.
Ref:
http://www.php.net/manual/en/ini.core.php#ini.post-max-size
http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize
A few settings in your php.ini could be causing this. Look into memory_limit, post_max_size, upload_max_filesize. You could also be timing out. The best way to find out specifically is error_reporting(E_ALL);ini_set('display_errors','1');
In php.ini, there will be a post_max_size and upload_max_filesize directive.
You should also define a MAX_FILE_SIZE hidden input within your form, as per
http://www.php.net/manual/en/features.file-upload.post-method.php

Categories