how to upload image code and save path into mysql db - php

how to write code to upload image and save path into mysql db?
i have tried but none are working.

One way is to upload image and store it in a folder on server, and save name to mysql database. Here's an example ::
First we'll create a form to upload ::
//file.html
Upload your file to the database...
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture" type="file" id="picture" size="50">
<input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>
Then we create upload.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title> Upload Image </title>
<?php
// if something was posted, start the process...
if(isset($_POST['upload']))
{
// define the posted file into variables
$name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
$type = $_FILES['picture']['type'];
$size = $_FILES['picture']['size'];
// if your server has magic quotes turned off, add slashes manually
if(!get_magic_quotes_gpc()){
$name = addslashes($name);
}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, $size);
$content = addslashes($content);
fclose($extract);
// connect to the database
include "connect.php";
// the query that will add this to the database
$addfile = "INSERT INTO files (name, size, type, content ) VALUES ('$name', '$size', '$type', '$content')";
mysql_query($addfile) or die(mysql_error());
if(!empty($_FILES))
{
$target = "upload/";
$target = $target . basename( $_FILES['picture']['name']) ;
$ok=1;
$picture_size = $_FILES['picture']['size'];
$picture_type=$_FILES['picture']['type'];
//This is our size condition
if ($picture_size > 5000000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($picture_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['picture']['name']). " has been uploaded <br/>";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
}
mysql_close();
echo "Successfully uploaded your picture!";
}else{die("No uploaded file present");
}
?>
</head>
<body>
<div align="center">
<img src="upload/<?php echo $name; ?>"
<br />
upload more images
</div>
</body>
</html>
//getpicture.php
**//Finally the connect.php**

Related

Renaming a form-selected file before submitting upload

I am attempting to create a form which allows the renaming of a selected file within the form, before submitting the upload.
I created the form with a 'text' field named "new_fileName" in addition to the file-picker.
On the upload.php side, I changed the variable to $newname, and tried a few ways to use that to change the name of the uploaded file. Including using it to replace the ['name'] part of the $filename variable. But so far, no success with anything.
FORM
<!DOCTYPE html>
<html>
<head>
<title> Rename and Upload Form </title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="file" id="file" />
<br><br>
<input type="text" name="new_fileName" placeholder="Rename File"/>
<br><br>
<input type="submit" value="Rename and Upload" />
</form>
</body>
</html>
upload.php
<?php
$newname = $_POST['new_fileName'];
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
if( move_uploaded_file($_FILES['file']['tmp_name'], $location)){
echo 'File uploaded successfully';
}else{
echo 'Error uploading file';
}
?>
After a bit of tinkering with the 'upload.php' page, this is what ended up working to change the name of the file before submitting the upload form.
This code also adds the file-type extension to the new file name.
(New) upload.php
<?php
$filename = $_POST['new_fileName'];
$name = $_FILES["file"]["name"];
$ext = end((explode(".", $name)));
if($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_FILES['file']['error'] > 0) { echo 'Error: ' . $_FILES['file']
['error']; }
if (file_exists('upload/' . $_FILES['file']['name'])) { unlink
('upload/' . $_FILES['file']['name']); }
move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $_POST =
$filename . "." . $ext);
echo 'File uploaded successfully' ; }
else { echo 'Error uploading file'; }
?>

Failed to show the result

For my project i am using PHP and MySql. In that i was tried to upload an image to the mysql database. In that i faced one terrible error. My html code was like this
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Learing new things</title>
<style>
body
{
margin:4%;
}
</style>
</head>
<body>
<form enctype="multipart/form-data" method=post name=imaging action="upload.php">
<input type="file" name=file><input type="submit" name=upload value=Upload>
</form>
</body>
</html>
"file" was the name of my file upload field. PHP code like this
<?php
$file=$_FILES['file'];
var_dump($file);
if(isset($_FILES['file']['name']))
{
echo "Image Uploaded";
echo $file['name'];
}
else
echo "Image not Uploaded";
?>
Whatever happen whether the file is uploaded or not uploaded, in my PHP page it is always executing the echo "image upload". i tried without selecting a file and clicked the upload still i am getting the same. How do i find whether a file is selected and uploaded in the html page. why i am getting the same message. it is not executing the else block.
Format html code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Learing new things</title>
<style>
body
{
margin:4%;
}
</style>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="imaging" action="upload.php">
<input type="file" name="file" /><input type="submit" name="upload" value="Upload" />
</form>"
</body>
</html>
Php check if file was selected
if (empty($_FILES['file']['name'])) {
// No file was selected for upload
}
Modify your Php script to this.
<?php
$target_dir = "(your target directory)/";
$target_file = $target_dir .basename($_FILES["uploadfile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["upload"])) {
$check = getimagesize($_FILES["uploadfile"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

uploading zip files with PHP, undefined index

I'm having issues uploading zip files and can't seem to find an answer.
Index.php
<form id="convertFile" action="convert.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input name="upload" type="file" id="inputFile">
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
convert.php:
if(isset($_FILES)){
echo $_FILES['upload']['name'];
}else{
echo json_encode(array('status'=>'error'));
}
When I upload a zip file, I get: Notice: Undefined index: upload in C:\wamp\www\xmlconverter\convert.php on line 3
This is what chrome shows in the post header:
------WebKitFormBoundaryuFNy5dZtFj7olmD5
Content-Disposition: form-data; name="zip_file"; filename="123.zip"
Content-Type: application/x-zip-compressed
------WebKitFormBoundaryuFNy5dZtFj7olmD5--
This works on any other major file format, but can't get it to read the zip file. If I var_dump $_FILES or $_POST they are empty.
What am I missing? Why does all other files work but zip does not.
Thank you
using wamp and php 5.5.12
Where is your zip file type definition?
Anyways, let say this was the html form to upload zip files you'd have the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
On the server-side script which handles the post you'd have:
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
//if you also wanted to extract the file after upload
//you can do the following
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
I used a script very similar to one posted by #unixmiah without issue on my cPanel based server. Worked great (and has for year now) but ran into issue of error "PHP, undefined index" when using locally with wamp.
Here is the mod that worked for me:
<?php
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if(!empty($_FILES)){
//added above to script and closing } at bottom
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "<b>The file you are trying to upload is not a .zip file! Please try again...</b>";
}
$target_path = "somedir/somesubdir/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("somedir/somesubdir/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "<h2>ZIP file was uploaded and content was replaced!</h2>";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>QikSoft ZIP Upper</title>
</head>
<body>
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label><h3>Upload Your ZIP:</h3> <input type="file" name="zip_file" /></label>
<br /><br />
<input type="submit" name="submit" value="START UPLOAD" />
</form>
</body>
</html>
Also note that the echo message has been changed:
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
One thing that does not work is file restriction. Currently allows other types besides ZIP. Anyone with fix, be greatly appreciated.
It's echo $_FILES['upload']['tmp_name'];
Try checking and adjusting the post_max_size value in your php.ini file, this worked for me as the default is 3M, raised the value to 128M and everything was peachy

Failing to upload file

I'm trying to test a simple file upload script but it fails. Here is the html portion.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title="testing"></title>
</head>
<body>
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input type="file" name="uploaded"/>
<input type="submit" value="Upload File"/>
</form>
</body>
And below this is the php portion.
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>
It fails at this line:
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
And execute the else portion: "Sorry, there was a problem uploading your file." How can I get it to work without failing. Thank you for you help.
The most likely reason is lack of write access to the target directory.
Also, I'd check if $target resolves correctly, as there could be artifacts in the filename that seem to be passed directly to the script and are not filtered.
You could test the permissions with
is_writable( PATH_OF_FOLDER )
I also tend to test the existance of the file with
is_file( PATH_OF_NEW_FILE )
before confirming the upload is successful!

on upload get all file names in array in php

What i want to know is how can I get a list [specifically array] of all the files name in a directory when I select it through upload button, after which I would upload that array of files to the database. As one file as a single entry. So how do I do that?
No to forget that I just need files names and I have to upload these names only not the actual files.
are the files on the server? if you hopping to have a button you click on browser and open a folder on the end user this will not work. most browsers only allow single file selection
If you are using ftp, this function will return all of the filenames of a directory in an array.
function ftp_searchdir($conn_id, $dir) {
if(!#ftp_is_dir($conn_id, $dir)) {
die('No such directory on the ftp-server');
}
if(strrchr($dir, '/') != '/') {
$dir = $dir.'/';
}
$dirlist[0] = $dir;
$list = ftp_nlist($conn_id, $dir);
foreach($list as $path) {
$path = './'.$path;
if($path != $dir.'.' && $path != $dir.'..') {
if(ftp_is_dir($conn_id, $path)) {
$temp = ftp_searchdir($conn_id, ($path), 1);
$dirlist = array_merge($dirlist, $temp);
}
else {
$dirlist[] = $path;
}
}
}
ftp_chdir($conn_id, '/../');
return $dirlist;
}
<?
if (isset($_POST[submit])) {
$uploadArray= array();
$uploadArray[] = $_POST['uploadedfile'];
$uploadArray[] = $_POST['uploadedfile2'];
$uploadArray[] = $_POST['uploadedfile3'];
foreach($uploadArray as $file) {
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['$file']['name']);
if(move_uploaded_file($_FILES['$file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['$file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload-simple.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload:
<input name="uploadedfile" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile2" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile3" type="file" />
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
</html>
This Might be Solve your Problems
If the files already exist on the server you can use glob
$files = glob('*.ext'); // or *.* for all files
foreach($files AS $file){
// $file is the name of the file
}

Categories