Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
My HTML code is this:
<div id="videoinput" class="inputbox">
<form autocomplete="off" action="../upload/" name="textinput" method="POST" enctype="multipart/form-data">
<input type="text" id="videotitlebox" name="texttitle" required class="inputtext" placeholder="Title of video" />
<textarea type="text" id="textdescbox" name="textdesc" required class="inputtext" placeholder="Description"></textarea>
<?php
require("../common/category.php");
?>
<input type="file" name="uploadvideo" value="Upload video" id="videoupload" required />
<input type="submit" name="uploadvideo" value="Submit" class="submitbut" />
</form>
My PHP code is this:
if (isset($_POST['uploadvideo'])) {
if($_POST['category']!="" && $_POST['category']!="selectcategory") {
define("UPLOAD_DIR1", "../uploadedfiles/");
$myFile = $_FILES["myFile"];
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['file']['error']);
}
$info = getimagesize($_FILES['file']['tmp_name']);
if ($info === FALSE) {
die("File is not of an acceptable type. Only .GIF, .JPEG,.JPG and .PNG files are acceptable.");
}
if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
die("File is not an image file.");
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$temp = explode(".", $name);
$name = $_SESSION['user_id'] . '.' . end($temp);
// don't overwrite an existing file
$parts = pathinfo($name);
$id = $_SESSION['user_id'] . Date("__h.m.s__d.m.y__") . "image";
$id = md5($id);
$name = md5($id) . "." . $parts["extension"];
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR1 . $name);
chmod(UPLOAD_DIR1 . $name, 0644);
$time = date("h:i:s");
$mydate=getdate(date("U"));
$date = "$mydate[year].$mydate[mon].$mydate[mday]";
$title = $_POST['texttitle'];
$category = $_POST['category'];
$description = $_POST['textdesc'];
$sql = "INSERT INTO uploads(title, category, description, path, id, time, date, username, datetime, type)
VALUES (:title, :category, :description, :path, :id, :time, :date, :user, :datetime, :type)";
$query = $conn->prepare($sql);
$query->execute(array(':title'=>$title, ':category'=>$category, ':description'=>$description, ':path'=>$name, ':id'=>$id, ':time'=>$time, ':date'=>$date, ':user'=>$_SESSION['user_id'], ':datetime'=>$date . " " . $time, ':type'=>"image") );
echo "Success.";
header('Location: ../home/');
}
else {
}
}
Problem is that my code never even gets to the third line. As soon as the code starts, it dies because of the first if which goes "$_FILES['file']['error'] !== UPLOAD_ERR_OK".
Why is this happening? How do I upload the video?
Any other suggestions to clean up my PHP code is much appreciated.
Spot the differences:
<input type="file" name="uploadvideo" value="Upload video" id="videoupload" required />
^^^^^^^^^^^
$myFile = $_FILES["myFile"];
^^^^^^
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
^^^^^^
Related
I cant figure out how how zip a file in PHP with password. The password will be the time and filename.
This is what i have done so far.
HTML Code for upload.
<form enctype="multipart/form-data" action="http://localhost/CSS/addfile.php" method="POST">
<div id="label">
<label>Upload File</label>
</div>
<input name="doc" type="file" placeholder="Upload File Here" accept="files/topsecret/*" required>
<input type="submit" value="Upload" name="submit">
</form>
PHP code
function GetImageExtension($filetype)
{
if(empty($filetype)) return false;
switch($filetype)
{
case 'files/topsecret/bmp': return '.bmp';
case 'files/topsecret/gif': return '.gif';
case 'files/topsecret/jpeg': return '.jpg';
case 'files/topsecret/png': return '.png';
case 'files/topsecret/txt': return '.txt';
case 'files/topsecret/doc': return '.doc';
case 'files/topsecret/docx': return '.docx';
case 'files/topsecret/pdf': return '.pdf';
default: return false;
}
}
$upFile = $_FILES['doc']['name'];
$tmp_name = $_FILES['doc']['tmp_name'];
$ftype = $_FILES['doc']['type'];
$fileExt = GetImageExtension($ftype);
$filename = $upFile.$fileExt;
$target_path="files/topsecret/".$filename;
move_uploaded_file($tmp_name,$target_path);
date_default_timezone_set('Asia/Kuala_Lumpur');
$timefile = date("F j, Y g:ia");
$size = filesize($target_path);
$size = number_format($size / 1024, 2) . ' KB';
try{
$sql = "INSERT INTO file(File_path,Date,Size,Name) VALUES ('".$target_path."','".$timefile."','".$size."','".$filename."')";
if ($connection->query($sql)){
echo"<script type= 'text/javascript'>alert('Upload Successfully');</script>";
header("refresh:2;index.php");
}else{
echo "<script type= 'text/javascript'>alert('Upload Not Successfully Inserted.');</script>";
}
I have research a found a few function for php but dont know how to use it.
like. ZipArchive::setEncryptionName ... but cant use it as i am using PHP version 7.1.8, in xampp.
Please help me explain on how to do it, as simple as possible. I need to encrypt the uploaded file with password using zip or rar. Plan to use hash the file name and time together and then setting it as the password.
Thanks a lot.
First, a try block needs a catch.
Secondly, you shouldn't need the GetImageExtension function, $_FILES has the extension in the uploaded array, all you needed to do was print_r($_FILES); to be able to verify.
Sadly though, from what I read you can't encrypt a file just yet, you need to wait for php 7.2 to be released to use $zip->setEncryptionName;.
I figured this out after writing out a bit of code, I figured it might be helpful nonetheless that's why I'm posting this answer.
You can look into: http://php.net/manual/en/filters.encryption.php, that's a good option to integrate into the code below, I don't have the time right now but it's fairly easy to do following their examples.
if(isset($_POST['submit'])){
upload($_FILES);
}
class Connection {
protected $db = null;
public function db(){
if($this->db === null){
try {
$this->db = new PDO('mysql:host=localhost;dbname=name; charset=utf8', user, password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
return $this->db;
}
}
function upload($file_data){
// calling this statically, don't suggest it
$conn = Connetion::db();
$name = $file_data['doc']['name'];
$tmp_name = $file_data['doc']['tmp_name'];
$extension = explode('/', $file_data['doc']['type']); // $extension[1] returns file type.
$image_size = getimagesize($tmp_name);
$file_name = $name . '.' . $extension[1];
$target_path = "";
if($image_size !== false){
$zip = new ZipArchive();
if ($zip->open('uploaded_file.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFromString("text.txt", "#1 This is a test string added as testfilephp.txt.\n");
$zip->setEncryptionName('text.txt', ZipArchive::EM_AES_256, 'secret'); // here we'd set the password
$zip->close();
$zip_created = true;
} else {
$zip_created = false;
}
// if zip was created and uploaded the file, then we upload it to the database
if($zip_created == true){
$sth = $conn->prepare('INSERT INTO file (file_path, `date`, size, name) VALUES (:target_path, :time_file, :size, :file_name)');
$sth->bindValue(':target_path', $target_path, PDO::PARAM_STR);
$sth->bindValue(':time_file', date('m-d-Y H:i:s'), PDO::PARAM_STR);
$sth->bindValue(':target_path', $target_path, PDO::PARAM_STR);
$sth->bindValue(':file_name', $file_name, PDO::PARAM_STR);
$sth->execute();
} else {
// here we can upload the error to the database or do nothing
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="doc">
<input type="submit" value="Upload" name="submit">
</form>
My main issue is that I have two different file upload links and both are for different purposes.For ex: a) Is a license b)Is a photo so I need to upload both in different locations.So what I wanted is to be able to address file properties as a numeric array instead of an associative array.I am also open to suggestions as to how to distinguish between the two files.
Here is the input code sample:
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload">
</i>Upload License
</label>
<input id="file-upload" name="files[]" type="file">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload">
</i>Upload Photo
</label>
<input id="file-upload" name="files[]" type="file">
Here is the upload script(NOTE-I have also tried using array_values())
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$tmpname = array_values($_FILES['files']['tmp_name']);
$filename = array_values($_FILES['files']['name']);
$filesize = array_values($_FILES['files']['size']);
$filetype = array_values($_FILES['files']['type']);
$date12 = date('Y-m-d');
//for photo
$file_name2 = $filename[0];
$ext2 = pathinfo($file_name2, PATHINFO_EXTENSION);
$file_name22= $name.".".$ext2;
$file_size2 = $filesize[0];
$file_tmp2 = $tmpname[0];
$file_type2 = $filetype[0];
$extensions = array("jpg","jpeg","png","pdf","zip","rar");
$type = "photo";
$desired_dir = "user_data";
if(in_array($ext2,$extensions ) === false)
{
$errors2 = "Extension not allowed!";
}
else
{
//Added file size limit
if($file_size2 > 2097152)
{
$errors2 = 'File size must be less than 2 MB';
}
if(empty($errors2) == true)
{
// Inserting info into database for easy retrieval
$query1 = $this->pdo->prepare("
INSERT into upload_data (NAME,EMAIL,FILE_NAME,FILE_SIZE,FILE_TYPE,date1,file_ext,type)
VALUES('$name','$email','$file_name22','$file_size2','$file_type2','$date12','$ext2','$type')
");
$query1->execute();
if(is_dir($desired_dir) == false)
{
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name22) == false)
{
move_uploaded_file($file_tmp,"user_data/".$type.$file_name22);
}
else
{
//rename the file if another one exist
$new_dir = "user_data/".$file_name22.time();
rename($file_tmp2,$new_dir) ;
}
echo "
<script>
Materialize.toast('Successfully Uploaded!', 8000)
</script>";
}
else
{
echo "
<script>
Materialize.toast($errors, 8000)
</script>";
}
}
Thank you
In order to upload files in a form, your form needs enctype="multipart/form-data".
name the different inputs differently, for example license and photo. Then you can access the files in php with $_FILES['license'] and $_FILES['photo'].
I have a problem with uploading path in my sql database. Not displaying all path.
This is the php code:
$rd2 = mt_rand(1000, 9999) . "_File";
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"));
$newname = "uploads/" . $rd2 . "_" . $filename;
if (!file_exists($newname));
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)));
$query = "insert into files (file_id,floc,subid,fname,fdesc,tcid)
values ($newstd,'$newname',
'".htmlspecialchars($_REQUEST['subid'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fname'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fdesc'], ENT_QUOTES)."',
'".$_SESSION['tcid']."')";
if (!#executeQuery($query)) {
if (mysql_errno () == 1062) //duplicate value
$_GLOBALS['message'] = "Given Subject Name voilates some constraints,
please try with some other name.";
else
$_GLOBALS['message'] = mysql_error ();
}
else
$_GLOBALS['message'] = "Successfully New Subject is Created.";
}
closedb();
The code is working and shows like this in database: http://i.stack.imgur.com/Z5jmb.png
It suppose to display uploads/2654_File_filename.docx
And the file is not uploaded.
The form is in a table:
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
</tr>
I used this:http://www.w3schools.com/php/php_file_upload.asp but same no working
I'm using xampp 5.6.8 and php.ini and file_uploads directive is set to On.
EDIT - newstd is:
$result = executeQuery("select max(file_id) as fid from files");
$r = mysql_fetch_array($result);
if (is_null($r['fid']))
$newstd = 1;
else
$newstd=$r['fid'] + 1;
$result = executeQuery("select fname as fid from files where
fname='" . htmlspecialchars($_REQUEST['fname'], ENT_QUOTES) . "'
and tcid=" . $_SESSION['tcid'] . ";");
// $_GLOBALS['message']=$newstd;
if (empty($_REQUEST['fname']) || empty($_REQUEST['fdesc'])) {
$_GLOBALS['message'] = "Some of the required Fields are Empty";
} else if (mysql_num_rows($result) > 0) {
$_GLOBALS['message'] = "Sorry Subject Already Exists.";
} else {
}
$rd2 = mt_rand(1000, 9999) . "_File";
...
...
EDIT: I forgot to mention that when i dont use a path he upload it in database.
I had a "global" form and i putted enctype="multipart/form-data" in it and it worked with saving the path in table.
Before was in form below and dont recognise it.
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
But still no uploading files...
Can you check if the file is not too large and exceeds the limitations of these two configurations:
post_max_size
upload_max_filesize
You can see the values from a file with:
<?php
phpinfo();
?>
Edit:
Another suggestion is to put the body brackets of the if's because the single line execution if the statement is valid, cant be trusted. I think the problem can be the :
if (!file_exists($newname));
Also the way you insert into the DB you take the name from the $_REQUEST and not the new name and where do you store the path ?
I am PHP beginner and building my own practice project (I have thought it something like used car sale online site)
My problem is very similar to multiple file upload sql/php and Multiple file upload in php
Here are list of my problems
I want to upload image in a directory and store it's name in database. So far below code is working fine (if I upload 1 file). I am trying to add 3 more file input option so that user can upload upto 4 images.
So far trying different codes available in stackoverflow and other online sites, I have been able to atleast upload the multiple files in my directory. But the real problem is that I don't know how I would store the name of the file in database .
(In most of the tutorials and suggestions, I found I should use 1 input file type with multiple attributes or name equals array like file[] and run foreach loop. But I couldn't figure out how would go ahead and get the file name of each input and store it in database.
Below are my code for the reference.
//this is my form.addVehicle.php file to process the form
<?php
define("UPLOAD_DIR", "../uploads/");
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$name = "default.jpg";
if (is_uploaded_file($_FILES["myFile"]['tmp_name'])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$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);
}
include_once ('../class/class.Vehicle.php');
$vehicle = new Vehicle(
$_POST['make_id'],
$_POST['yearMade'],
$_POST['mileage'],
$_POST['transmission'],
$_POST['price'],
$_POST['zone_name'],
$name,
$_POST['description']
);
}
?>
//To give a try, tested is_uploaded_file condition four different times with //different file name id like myFile1,myFile2...and path variable as $name1, //$name2...and it works as I want it to be...but I'm sure that' not the correct //way to do it..
//This is my class file with name class.Vehicle.php
include_once('class.pdoDbConnnection.php');
class Vehicle{
private $make_id;
private $yearMade;
private $mileage;
private $transmission;
private $price;
private $zone_name;
private $image_path;
private $description;
public function __construct($make_id, $yearMade, $mileage, $transmission, $price, $zone_name, $image_path, $description){
$this->make_id = $make_id;
$this->yearMade = $yearMade;
$this->mileage = $mileage;
$this->transmission= $transmission;
$this->price = $price;
$this->zone_name = $zone_name;
$this->image_path = $image_path;
$this->description = $description;
try{
$sql = "INSERT INTO cars (car_id, make_id, yearmade, mileage, transmission, price, zone_name,image_path, description) VALUES (?,?,?,?,?,?,?,?,?)";
$pdo = new DBConnection();
$stmt = $pdo->prepare($sql);
$stmt->execute(array(NULL,$this->make_id,$this->yearMade,$this->mileage,$this->transmission,$this->price,$this->zone_name,$this->image_path,$this->description));
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
}
Here are my mySql table columns (I want to insert file names in the column..while displaying it in the client side, I'm using it this way: <img alt="image" class="img-responsive" src="../uploads/<?php echo $row['image_path'] ?>">
car_id , make_id , zone_id, yearmade, mileage, transmission, price, image_path, image_path1, image_path2, image_path3, description
This is my client side form to add new cars....
..................
<form class="form-horizontal" role="form" method="post" action="../includes/form.addVehicle.php" enctype="multipart/form-data">
.....................
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile" name="myFile">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile1" name="myFile2">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile3" name="myFile3">
</div>
</div>
..............
Finally I ended up with the following code.
P.S. Thanks to #Andy-Brahman insight at Multiple file upload in php
<?php
if(isset($_POST['submit'])){
$uploads_dir = '../test_uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
// I don't want to overwrite the existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists($uploads_dir . "/" . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
// Test to see if I get the uploaded file name which i want to insert into database table column.
echo "<pre>";
print_r($_FILES['pictures']['name'][0]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][1]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][2]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][3]);
echo"</br></br>";
echo "</pre>";
// test succeeds . Now I guess I can do something like $picture0 = $_FILES['pictures']['name'][0]);
// and insert $picture0,$picture1...into database..
// Am I doing everything correctly?
}
I will make example, you just adapt it for yourself.
<form action="file_reciever.php" enctype="multipart/form-data" method="post">
<input type="file" name="files[]" multiple/>
<input type="submit" name="submission" value="Upload"/>
</form>
the PHP goes (file_reciever.php):
<?php
if (isset($_POST['submission'] && $_POST['submission'] != null) {
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
}
?>
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to use a csv file to update the mysql scv table. how to code ? I have no experiece doing this job.
<p>please select a scv file to upload</p>
<form action="index.php" method="post">
<input type="file" name="scv" />
<input type="submit" value="submit" />
</form>
<?php
mysql_connect('localhost','root','admin');
mysql_select_db('linjuming');
// how to upload a scv file and insert or update the "csv" table?
?>
Your upload file:
<form action="upload_target.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
Your upload_target.php
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ($ext == "csv" && $_FILES["file"]["error"] == 0)
{
$target = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $target);
if (($handle = fopen($target, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
print_r($data);
}
fclose($handle);
}
}
Very basic and with very few checks / validations. The print_r($data) contains one line of your csv that you can now insert in your database.
However, I would recommend using PDO or MySQLi for that task, since the mysql functions of PHP will be deprecated in the future.
There's several parts of this:
First, your form MUST have the enctype set, as follows:
<form enctype="multipart/form-data" action="index.php" method="post">
Otherwise, it will not accept file uploads.
Once you've done that, then you can access the file using the $_FILES variable. After the file has been uploaded, then you can access it like so:
if (isset($_FILES["scv"])) {
$file = $_FILES["scv"];
$file_name = $file["name"];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
if ($ext!="CSV" && $ext!="TXT") {
die('The file must be csv or txt format.');
}
$saveto_path_and_name = '/path/to/file.csv'; // Where you want to save the file
move_uploaded_file($file["tmp_name"], $saveto_path_and_name);
}
Once you've saved the file, you then can open it and import it. That's not trivial to do, but here's some primer code:
// Open the file for reading
$handle = #fopen($saveto_path_and_name, "r") or die(__("Unable to open uploaded file!", "inventory"));
// Grab the first row to do some checks
$row = fgets($inv_file, 4096);
// See if it's comma or tab delimited
if (stripos($inv_row, "\t")) {
$sep = "\t";
} else {
$sep = ",";
}
while ( ! feof($handle)) {
$rowcount = 0;
// Get the individual fields
$inv_fields = explode($sep, $inv_row);
$fields = array();
// Iterate through the fields to do any sanitization, etc.
foreach ($inv_fields as $field) {
// Highly recommended to sanitize the variable $field here....
$fields[] = $field;
$rowcount++;
}
// This is where you would write your query statement to insert the data
// This is just EXAMPLE code. Use the DB access of your choice (PDO, MySQLi)
$sql = vsprintf('INSERT INTO `table` (`column`, `column2`, ...) VALUES (%s, %d, ...)', $fields);
// Get the next row of data from the file
$row = fgets($inv_file, 4096);
}