php file upload php upload file to database
How does PHP upload files to the database? Here are a few examples. Master the method of PHP to save files to the MySQL database, and how to let PHP upload files and save them into the database.
php upload files to database It is nothing more than creating a longblob field in the database to save this file However, if you upload a file of 4-5m, there will be some problems that you need to pay attention to at this time 1, modify php.ini post_max_size upload_max_filesizeThe value of the 2 parameters, make them larger than the size of the file you need to upload 2, modify my.cnf Modify the value of the max_allowed_packet parameter of the mysql database The meaning of this parameter: max_allowed_packet The maximum size of a bag. The message buffer is initialized to net_buffer_length bytes, but can be increased to max_allowed_packet bytes if needed. By default, this value is too small to capture large (possibly erroneous) packets. If you are using large blob columns, you must increase this value. It should be as large as the largest blob you want to use. 1. PHP uploads pictures to the database Create 3 php files: readdir.php - code that puts images into the database image.php - code that displays the actual image view.php - code that shows how you call an image from the database 1. Create a database create table `images` ( `imgid` int not null auto_increment, `sixfourdata` longtext not null , primary key (`imgid`) );readdir.php Specific content: $dbcnx = mysql_connect("localhost", "username", "password"); mysql_select_db("base64imgdb"); ?> 'Need to open a directory "./" The 'readdir.php file is located in this directory: $path = "./"; $dir_handle = opendir($path) or die("unable to open directory $path");Category images and read out some of the data being used fopen 'Convert base64_encode 'Insert into table while ($file = readdir($dir_handle)) { $filetyp = substr($file, -3); if ($filetyp == 'gif' or $filetyp == 'jpg') { $handle = fopen($path . "/" . $file,'r'); $file_content = fread($handle,filesize($path . "/" . $file)); fclose($handle); $encoded = chunk_split(base64_encode($file_content)); $sql = "insert into images set sixfourdata='$encoded'"; mysql_query($sql); } } ?>Close the set directory and process: closedir($dir_handle); echo("complete"); mysql_close($dbcnx); ?>Code to read the image: image.php $dbcnx = mysql_connect("localhost", "username", "password"); mysql_select_db("base64imgdb"); ?>The code used to read out the image image.php?img=x: $img = $_request["img"]; ?>After that, you need to connect to the database and read out: $result = mysql_query("select * from images where imgid=" . $img . ""); if (!$result) { echo("Request error: " . mysql_error() . ""); exit(); } while ($row = mysql_fetch_array($result)) { $imgid = $row["imgid"]; $encodeddata = $row["sixfourdata"]; } ?> mysql_close($dbcnx); echo base64_decode($encodeddata); ?> Understand base64-encoded image data format.
"Let's take a look at the specific pictures!" view.php
image.php?img=1
image.php?img=357
readdir.php: ############################### # db connection # change these values ############################### $dbcnx = mysql_connect("localhost", "username", "password"); mysql_select_db("base64imgdb"); ############################### # db connection # change these values ############################### $dbcnx = mysql_connect("localhost", "username", "password"); mysql_select_db("base64imgdb"); $path = "./"; $dir_handle = opendir($path) or die("unable to open directory $path"); while ($file = readdir($dir_handle)) { $filetyp = substr($file, -3); if ($filetyp == 'gif' or $filetyp == 'jpg') { $handle = fopen($file,'r'); $file_content = fread($handle,filesize($file)); fclose($handle); $encoded = chunk_split(base64_encode($file_content)); $sql = "insert into images set sixfourdata='$encoded'"; mysql_query($sql); } } closedir($dir_handle); echo("complete"); mysql_close($dbcnx); ?> image.php: $dbcnx = mysql_connect("localhost", "username", "password"); $dbcnx = mysql_connect("localhost", "username", "password"); mysql_select_db("base64imgdb"); $img = $_request["img"]; $result = mysql_query("select * from images where imgid=" . $img . ""); if (!$result) { echo("error performing query: " . mysql_error() . ""); exit(); } while ($row = mysql_fetch_array($result) ) { $imgid = $row["imgid"]; $encodeddata = $row["sixfourdata"]; } mysql_close($dbcnx); echo base64_decode($encodeddata); ?> view.php (i shouldn’t need to post this..) ..2. How to let php upload files and save them into the database 1.show_info.php
$num=mysql_num_rows($result); if($num $data = mysql_result($result,0,"file_data"); $type = mysql_result($result,0,"file_type"); $name = mysql_result($result,0,"file_name"); mysql_close($conn); //First output the corresponding file header and restore the original file name header("content-type:$type"); header("content-disposition: attachment; filename=$name"); echo $data; ?> 2.show_info.php
$sql = "select file_name ,file_size from receive where id=$id"; $result = mysql_query($sql,$conn); if(!$result) die(" error: mysql query"); //If there is no specified record, an error will be reported $num=mysql_num_rows($result); if($num //The following two sentences of program can also be written like this //$row=mysql_fetch_object($result); //$name=$row->name; //$size=$row->size; $name = mysql_result($result,0,"file_name"); $size = mysql_result($result,0,"file_size"); mysql_close($conn); echo " Uploaded file information:"; echo " the file's name - $name"; echo " the file's size - $size"; echo " attachment"; ?> 3.submit.php
$myfile=$_files["myfile"]; //Set the timeout limit time. The default time is 30 seconds. When set to 0, there is no time limit. $time_limit=60; set_time_limit($time_limit); // //Read the file content into a string $fp=fopen($myfile['tmp_name'], "rb"); if(!$fp) die("file open error"); $file_data = addslashes(fread($fp, filesize($myfile['tmp_name']))); fclose($fp); unlink($myfile['tmp_name']); //File format, name, size $file_type=$myfile["type"]; $file_name=$myfile["name"]; $file_size=$myfile["size"]; die($file_type); //Connect to the database and save the file to the database $conn=mysql_connect("localhost","root","admin"); if(!$conn) die("error : mysql connect failed"); mysql_select_db("nokiapaymentplat",$conn); $sql="insert into receive (file_data,file_type,file_name,file_size) values ('$file_data','$file_type','$file_name',$file_size)"; $result=mysql_query($sql,$conn); //The following sentence takes out the id of the insert statement just now $id=mysql_insert_id(); mysql_close($conn); set_time_limit(30); //Restore the default timeout setting echo "Upload successful--- "; echo "Show uploaded file information"; } else { echo "You did not upload any files"; } ?> 4.upload.php |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
