Php Upload a File and Dynamically Create a Link for It
[printfriendly]
File Upload and Download with PHP
In This Tutorial We learn How to procedure Upload and Download organization using PHP and MySQL
Some observations<
- Always-fix grade method to Postal service
- Always-set form encodedtype to multipart/form-data
- Cheque files type on client side and server side likewise.
- Increase the script time limit and memory limit to upload large file.
- Don't use web method (this method) to upload larger than 500mb, instead utilise ftp upload interface.
More often than not the default maximum upload file size less than 8mb.
Increase file size upload limit using php.ini or htaccess
Any php web application or server configured with default values set in php.ini and .htacess. Generally almost web hosting providers, particularly popular ones, configures the web application to optimum settings, which effects server bandwidth, server memory limit, server disk space, and height security measures. For file uploading and PHP script execution there is default configuration in PHP.ini. However almost hosting providers give chance to developer to customize this default configuration by override php.ini or .htaccess . some settings can be configured by ini_set() method at run time of script. Bank check Infographic: Get Your Advice System Out of the Stone Age with Business VoIP, where you volition find the best networking skills.
Default PHP.ini
;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; ; Whether to permit HTTP file uploads. file_uploads = On ; Temporary directory for HTTP uploaded files (volition use system default if non ; specified). upload_tmp_dir = "${path}\tmp\" ; Maximum allowed size for uploaded files. upload_max_filesize = 2M ;;;;;;;;;;;;;;;;;;; ; Resource Limits; ;;;;;;;;;;;;;;;;;;; max_execution_time = 30 ; Maximum execution fourth dimension of each script, in seconds max_input_time = threescore ; Maximum corporeality of time each script may spend parsing request data ;max_input_nesting_level = 64 ; Maximum input variable nesting level memory_limit = 128M ; Maximum amount of retentiveness a script may consume (128MB)Increasing file upload size by php.ini
File upload size affected by mainly below PHP settings.
file_uploads = OnThis setting must be on. Information technology allows running uploads through HTTP.
Ensure this value is on the value tin can be On/Off or 1/0 or true/faux.upload_max_filesize = 20MThis value limits the size of uploaded single file. Requite it value any your requirements.
post_max_size = 40MThis value limits the size of all the uploaded content. For example upload_max_filesize is for single file, if we upload 3 files simultaneously each 15mb total 45mb so it exceeds post_max_size.
Recollect post_max_size must be larger about 40% of upload_max_filesize.max_execution_time = thirtyGenerally image uploading and manipulating with GD or Imagemagic consumes much time. And so information technology may exceeds 30 seconds. You can alter any your requirements. When a script execution time exceeded by this limit the server stops the scripts or gives fatal error.
memory_limit = 128MBy and large image uploading and manipulation with GD or Imagemagic consumes much server memory. When it exceeds this memory the server stops executing the script, then we run across empty page or no response from server or we get a fatal error.
Completed example, to increment 10Mb
upload_max_filesize = 10M ; post_max_size = 20M ; memory_limit = 128MCopy the above settings into your php.ini and put it in your web root directory.
Increasing file upload size by .htaccess
php_value upload_max_filesize 10M php_value post_max_size 20M php_value memory_limit 128MCopy the above settings into your .htaccess file and put it in your web root directory.
Almost all web host providers give to override the .htacces ,so you tin can use to a higher place method.Now Let's Beginning PHP Elementary File Upload Script:
&lt;?php // display file upload course if (!isset($_POST['submit'])) { ?&gt; &lt;grade enctype="multipart/form-data" action="&lt;?php echo $_SERVER['PHP_SELF']?&gt;" method="post"&gt; &lt;input type="hidden" proper name="MAX_FILE_SIZE" value="8000000" /&gt; Select file: &lt;input type="file" name="data" /&gt; &lt;input type="submit" proper name="submit" value="Upload File" /&gt;&lt;/form&gt; &lt;?php } else { // bank check uploaded file size if ($_FILES['information']['size'] == 0) { die("ERROR: Zero byte file upload"); } // cheque if file blazon is allowed (optional) $allowedFileTypes = assortment("image/gif", "image/jpeg", "paradigm/pjpeg"); if (!in_array($_FILES['data']['type'], $allowedFileTypes)) { dice("Mistake: File type not permitted"); } // check if this is a valid upload if (!is_uploaded_file($_FILES['information']['tmp_name'])) { dice("Error: Non a valid file upload"); } // ready the proper name of the target directory $uploadDir = "./uploads/"; // copy the uploaded file to the directory move_uploaded_file($_FILES['data']['tmp_name'], $uploadDir . $_FILES['information']['name']) or die("Cannot re-create uploaded file"); // display success message echo "File successfully uploaded to " . $uploadDir .$_FILES['data']['name']; } ?&gt;PHP significantly simplifies the task of uploading files through a Web form, by exposing a special $_FILES assortment which contains data on files sent through the POST method.
At that place are two components to this listing, the file upload form and the business organization logic that processes the submitted form.
- The form must exist submitted using Post, and must comprise the enctype="multipart/form-data" attribute, to ensure that the file is correctly uploaded. The hidden form variable MAX_FILE_SIZE specifies the maximum allowed upload size, in bytes; files larger than this will exist rejected.
- Once a file has been uploaded, it is stored in a temporary directory and information on its size, blazon, and original and temporary names is saved to the $_FILES array. The temporary file name is then provided to the move_uploaded_file() function, which is used to copy the file from the temporary directory to a new location.
It's mostly considered a good idea to verify the integrity of the upload before accepting it. Typical checks include ensuring the file is non a cypher-byte file with the
'size' key of the $_FILES array, and verifying that the file was indeed uploaded through a Postal service performance (and not "injected" into the script artificially by a
malicious user) with the is_uploaded_file() office. You may also choose to test the file blazon if your application only allows particular types of files to be
uploaded.TIP
Don't use the file extension to decide the file type, every bit it's easy to rename an executable file with a "safety" extension. Instead, apply the 'type' key of the $_FILES array to cheque the Multipurpose Net Postal service Extensions (MIME) type of the file, and simply allow those types you deem to exist safe.
Agreement PHP's File Upload Variables
In that location are six important PHP configuration variables influencing POST file uploads:
- "file_uploads" This variable, a Boolean, indicates whether or non file uploads should be permitted. Gear up this to true if your application supports file uploads.
- "max_execution_time" This variable determines the number of seconds a PHP script can run before it is forcibly terminated by the engine. If your application expects large file uploads, or if a wearisome network link is used for the file transfer, increase this value to avert your script automatically terminating in the center of a long upload.
- "max_input_time" This variable controls the maximum corporeality of fourth dimension a script has to receive input data, including Postal service-ed files. Equally with the max_
execution_time variable, increase this value if yous conceptualize big files or deadening transfers. - "upload_max_filesize" This variable determines the maximum size of an uploaded file, and it gets higher priority than the subconscious MAX_FILE_SIZE
form field. - "post_max_size" This variable determines the maximum size of data PHP can take in a single POST request, including file uploads. This should be at to the lowest degree equal to the value defined in "upload_max_filesize"; in well-nigh cases, it is larger.
- "upload_tmp_dir" This variable determines the temporary directory used for uploaded files. It defaults to the system's temporary directory.
In case you're confused by the interaction between these variables, think of it this style: "upload_max_filesize" applies to each of the files being uploaded to the server and "post_max_size" defines how many of them (or how much of them) can come through in a single Mail service request. This is why you'd typically want
"post_max_size" to exist larger than "upload_max_filesize".
Our Upload Form Expect Similar:
Afterwards Submit Our Upload Form:
Now Nosotros Create another File Upload Form with MySQL Database that besides supports multiple extensions Files:
Create a database chosen upload
CREATEDATABASE`upload`;Create tabular array called gravator
CREATE TABLE IF NOT EXISTS `gravator` ( `id` int(xi) NOT Goose egg AUTO_INCREMENT, `path` varchar(200) NOT Zilch, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=one ;Now create uploader.php file for uploading the file
&lt;?php if(isset($_FILES['filefield'])){ $file=$_FILES['filefield']; $upload_directory='uploads/'; $ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,md,docx,ppt,pptx,txt,pdf"; $allowed_extensions=explode(',',$ext_str); $max_file_size = 10485760;//10 mb retrieve 1024bytes =1kbytes /* check immune extensions hither */ $ext = substr($file['name'], strrpos($file['name'], '.') + 1); //get file extension from last sub string from terminal . graphic symbol if (!in_array($ext, $allowed_extensions) ) { echo "merely".$ext_str." files immune to upload"; // get out the script by warning } /* bank check file size of the file if it exceeds the specified size warn user */ if($file['size']&gt;=$max_file_size){ repeat "but the file less than ".$max_file_size."mb immune to upload"; // get out the script by alert } //if(!move_uploaded_file($file['tmp_name'],$upload_directory.$file['name'])){ $path=md5(microtime()).'.'.$ext; if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){ mysql_connect("localhost","root",""); mysql_select_db("upload"); echo"Your File Successfully Uploaded"; mysql_query("INSERT INTO gravator VALUES ('', '$path')"); } else{ echo "The file cant moved to target directory."; //file can't moved with unknown reasons likr cleaning of server temperory files cleaning } } /* Hurrey we uploaded a file to server successfully. */ ?&gt; &lt;grade activeness="" method="post" enctype="multipart/grade-data"&gt; &lt;label&gt;Upload File &lt;input id="filefield" type="file" name="filefield" /&gt; &lt;/label&gt; &lt;label&gt; &lt;input id="Upload" type="submit" name="Upload" value="Upload" /&gt; &lt;!-- This hidden input volition forcefulness the PHP max upload size. information technology may piece of work on all servers. --&gt; &lt;input blazon="subconscious" name="MAX_FILE_SIZE" value="100000" /&gt; &lt;/characterization&gt;&lt;/form&gt;Download file with PHP
To kickoff with create two new files and call them download.php and index.php.
Open the download_test.php and type the post-obit:&lt;a href="download.php?file=picture.jpg"&gt;Download file&lt;/a&gt;Now Open up the download.php file and remove the entire content which your editor added to it, and then first typing the following:
&lt;?php // block any attempt to the filesystem if (isset($_GET['file']) &amp;&amp; basename($_GET['file']) == $_GET['file']) { $filename = $_GET['file']; } else { $filename = NULL; } ?&gt;First we are checking if the the url contains the parameter file and whether basename($_GET['file']) and $_GET['file'] have the same value – this is to preclude whatsoever attackers from downloading files we don´t desire them to download.
If the condition is true then we are assigning the value of the file to the variable called $filename, still if the condition is false then we are assigning Null to the variable.
On the adjacent line type:
First we are checking if the the url contains the parameter file and whether basename($_GET['file']) and $_GET['file'] have the same value – this is to forestall any attackers from downloading files we don´t desire them to download.
If the condition is true then we are assigning the value of the file to the variable called $filename, however if the condition is fake then we are assigning NULL to the variable.
On the next line type:
// define error message $err = 'Sorry, the file you are requesting is unavailable.';This line of code creates a new variable called $err and assigns the default message which volition be displayed to the user when the file is unavailable or any other problem occurs.
&lt;?php if (!$filename) { // if variable $filename is NULL or false display the bulletin repeat $err; } else { // ascertain the path to your download folder plus assign the file proper name $path = 'downloads/'.$filename; // cheque that file exists and is readable if (file_exists($path) &amp;&amp; is_readable($path)) { // get the file size and send the http headers $size = filesize($path); header('Content-Type: application/octet-stream'); header('Content-Length: '.$size); header('Content-Disposition: attachment; filename='.$filename); header('Content-Transfer-Encoding: binary'); // open the file in binary read-simply mode // display the error messages if the file can´t exist opened $file = @ fopen($path, 'rb'); if ($file) { // stream the file and exit the script when complete fpassthru($file); go out; } else { echo $err; } } else { echo $err; } } ?&gt;What´s happening here is – first we cheque whether the $filename is Zilch and if so we are displaying our message $err message. If it isn´t Nil and so nosotros are creating the variable called $path which stores the path to the file and assigns the populated name of the file to the end of it.
Next we are checking whether the file exists and is readable, if so then we are sending the appropriate http headers with file size and opening the file in binary read-merely mode (rb). Then, if the file has been opened successfully, we are using the fpassthru() function to write the effect to the output buffer.
If any of the status was unsuccessful we are displaying our $err bulletin.Our File Download Output..
![]()
Uploading and Downloading Files To MySQL Database
Using PHP to upload files into MySQL database sometimes needed by some spider web application. For case for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).
For the first step, permit'due south brand the table for the upload files.
&lt;/pre&gt; CREATE Table IF Non EXISTS `files` ( `id` int(11) Not Aught AUTO_INCREMENT, `proper name` varchar(200) NOT NULL, `blazon` varchar(thirty) Non NULL, `size` int(xi) NOT Nix, `content` mediumblob Not NULL, PRIMARY Key (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=two ; &lt;pre&gt;Uploading a file to MySQL is a two footstep procedure. Start you demand to upload the file to the server so read the file and insert information technology to MySQL.
For uploading a file we need a class for the user to enter the file name or browse their computer and select a file. The inputtype="file"is used for that purpose.
Instance : upload.php
&lt;?php if(isset($_POST['upload']) &amp;&amp; $_FILES['userfile']['size'] &gt; 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } mysql_connect("localhost","root",""); mysql_select_db("upload"); $query = "INSERT INTO files (name, size, type, content ) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); echo " File $fileName uploaded "; } ?&gt; &lt;form method="post" enctype="multipart/grade-data"&gt; &lt;table width="350" border="0" cellspacing="1" cellpadding="1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td width="246"&gt; &lt;input blazon="hidden" name="MAX_FILE_SIZE" value="2000000" /&gt; &lt;input id="userfile" blazon="file" name="userfile" /&gt;&lt;/td&gt; &lt;td width="80"&gt;&lt;input id="upload" type="submit" proper noun="upload" value=" Upload " /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/grade&gt;Earlier you do anything with the uploaded file. Youshould notassume that the file was uploaded successfully to the server. Always cheque to see if the file was successfully uploaded by looking at the file size. If it'due south larger than zero byte and so we tin assume that the file is uploaded successfully.
PHP saves the uploaded file with a temporary name and salve the proper name in$_FILES['userfile']['tmp_name']. Our next chore is to read the content of this file and insert the content to database. E'er make sure that you useaddslashes()to escape the content. Usingaddslashes()to the file proper noun is also recommended considering you never know what the file proper noun would be.
That'south it now you lot can upload your files to MySQL.
Now it's time to write the script to download those files.
Downloading Files From MySQL Database
When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.
The download page list the file names stored in database. The names are printed equally a url. The url would look similar download.php?id=3.
Let's Create download.php file:
Download File From MySQL &lt;?php mysql_connect("localhost","root",""); mysql_select_db("upload"); $query = "SELECT id, name FROM files"; $issue = mysql_query($query) or dice('Mistake, query failed'); if(mysql_num_rows($issue) == 0) { echo "Database is empty "; } else { while(list($id, $proper name) = mysql_fetch_array($result)) { ?&gt; &lt;?php } } ?&gt;When you click the download link, the $_GET['id'] will be set. Nosotros can use this id to identify which files to get from the database. Below is the code for downloading files from MySQL Database.
&lt;?php mysql_connect("localhost","root",""); mysql_select_db("upload"); if(isset($_GET['id'])) { // if id is set then get the file with the id from database $id = $_GET['id']; $query = "SELECT name, blazon, size, content " . "FROM files WHERE id = '$id'"; $result = mysql_query($query) or die('Error, query failed'); list($name, $type, $size, $content) = mysql_fetch_array($event); header("Content-length: $size"); header("Content-type: $type"); header("Content-Disposition: zipper; filename=$name"); echo $content; exit; } ?&gt;Putting It All Together
&lt;/pre&gt; &lt;?php mysql_connect("localhost","root",""); mysql_select_db("upload"); if(isset($_GET['id'])) { // if id is prepare then get the file with the id from database $id = $_GET['id']; $query = "SELECT name, type, size, content FROM files WHERE id = $id"; $result = mysql_query($query) or die('Error, query failed'); list($name, $type, $size, $content) = mysql_fetch_array($result); header("Content-length: $size"); header("Content-type: $blazon"); header("Content-Disposition: attachment; filename=$proper noun"); repeat $content; exit; } ?&gt; Download File From MySQL &lt;?php $query = "SELECT id, name FROM files"; $outcome = mysql_query($query) or dice('Fault, query failed'); if(mysql_num_rows($consequence) == 0) { echo "Database is empty"; } else { while(list($id, $name) = mysql_fetch_array($result)) { ?&gt; &lt;a href="download2.php?id=&lt;?php echo $id;?&gt;"&gt;&lt;?php echo $name; ?&gt;&lt;/a&gt; &lt;?php } } ?&gt; &lt;pre&gt;Our Output Look like:
![]()
![]()
Hi, My name is Masud Alam, beloved to piece of work with Open Source Technologies, living in Dhaka, Bangladesh. I'm a Certified Engineer on ZEND PHP 5.iii, I served my start five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, The states AID and MAX Group where I worked on ERP software and spider web evolution., but at present i'yard a founder and CEO of TechBeeo Software Visitor Ltd. I'grand also a Class Instructor of ZCPE PHP 7 Certification and professional person web evolution class at w3programmers Preparation Establish – a leading Grooming Institute in the state.
Source: https://www.w3programmers.com/file-upload-and-download-with-php/
0 Response to "Php Upload a File and Dynamically Create a Link for It"
Post a Comment