Upload files without using php but no php form - php

I have a C program running on the localhost server which generates some files( writes its output to these file). Then I zip all these files together using php. Now I want to upload the zip file produced to mysql server using some php script but i dont want the user to upload these files using a form by clicking choose file button but i would like to upload these automatically as soon as they are generated to mysql using php script.
<?php
//get content of json file
require_once("zip.php");
$str = file_get_contents("program/heatmap_parameters.json");
//decode the JSON
$json = json_decode($str,true);
//echo '<pre>' . print_r($json, true) . '</pre>';
foreach ($json['parameters'] as $params) {
echo $params[3]."<br>";
$files_to_zip = array("program/".$params[3]);
var_dump($files_to_zip)."<br>";
//$files_to_zip = array("program/cctv2.mp4.json");
//if true, good; if false, zip creation failed
$zip_name = "program/".$params[3].".zip";
//zip the files
$result = create_zip($files_to_zip,$zip_name);
}
//connect to database
require_once("database/conn.php");
//upload zip file to database without displaying any form.
?>
I need a way to upload my generated file to saved to mysql without choosing it from the form.
<form action="" method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
include '../database/conn.php';
$sql = "INSERT INTO upload (name, content ) ".
"VALUES ('$fileName', '$content')";
$query = mysqli_query($conn,$sql);
if(!$query){
die("Cannot Insert".mysql_error());
}
}
How can i make this code such that it does not need the form

To answer your question in oneline,
You can not upload a file without form/input type file element, because that will a big security hole to web.
To upload any file to server, server need files object which has all the info of file. that info will be given by client from where you are uploading a file. It will also has the tmp location of file form where server will take that file.
You can copy file from one server to another, using curl or you can
write a bash script which will copy file from one place to another and
you can run that bash script using PHP.
Hope this helps to you!

Related

PHP: Editing a file using a dynamic filename

I have a PHP script that I am trying to edit some text files that have a dynamic file name. I think I am about 90% there, but am having an issue where the resulting output filename is incorrect.
The files in question I am trying to edit are for VoIP phones nad have a ormat of MAC.cfg, where MAC is the MAC address of the phone in question.
I have an HTML page that is just a very simple form where the MAC address is entered, and the form calls a PHP script that using that MAC address and brings up the contents of the appropriate MAC.cfg file. When I edit what I want to edit, however, the resulting filename becomes MAC.cfg.cfg (i.e., it adds an extra ".cfg" to it), and I do not know why.
The code for the page where the MAC address of the phone gets entered is:
<form method="post" action="edit-imaccfg.php">
<input type="text" name="macaddress" value="">
<input type="submit">
</form>
and the contents of 'edit-imaccfg.php' is this:
<?php
// set file to read
$filename = $_POST['macaddress'].=".cfg";
$newdata = $_POST['newd'];
if ($newdata != '') {
// open file
$fw = fopen($filename, 'w') or die('Could not open file!');
// write to file
// added stripslashes to $newdata
$fb = fwrite($fw,stripslashes($newdata)) or die('Could not write to file');
// close file
fclose($fw);
}
// open file
$fh = fopen($filename, "r") or die("Could not open file!");
// read file contents
$data = fread($fh, filesize($filename)) or die("Could not read file!");
// close file
fclose($fh);
// print file contents
?>
<html>
<body>
<form action="<?= $_SERVER[php_self] ?>" method="POST" >
<textarea name="newd" cols="100%" rows="100"> <?= $data ?> </textarea>
<input type="hidden" name="macaddress" value="<?= $_POST['macaddress'] ?>" />
<input type="submit" value="Change">
</form>
</body>
</html>
I don't know what, in the above code, is adding the extra '.cfg' to the outputted filename, rather than overwriting the intended MAC.CFG file.
Your insight is greatly appreciated Thanks! :-)

php - Upload .dat file to be stored in json

I am trying to upload .dat file, I want to get the content inside the file and have it in json.
I have this code:
HTML:
<from action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>
PHP:
If(isset($_POST["btnSubmit"])) {
$file = file_get_contents($_FILES["fileUpload"]["name"], true);
$r = json_encode($file);
}
The error I get is file_get_contents("fileName.dat"): failed to open stream
I am not trying to upload the file to my server or a folder, I am trying to get the data inside it and store it into json.
A file upload will save the file in the php's defined temporary directory. From there you can either move the file to a desired location, or get the content from it. In your case you can simply get the content by using "tmp_name" instead of "name".
Future more, you have to make sure you have the enctype set in your form.
<?php
// check if file is given
if(!empty($_FILES)) {
// get file from temporary upload dir
$file = file_get_contents($_FILES["fileUpload"]["tmp_name"], true);
$r = json_encode($file);
// show restult
var_dump($r);
}
?>
<!-- add multipart -->
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>

Using PHP code and rename an image file before uploading to XAMPP database?

I am new to php and is it possible to rename an image file before uploading to the database?
EDIT: would be using a form to upload the file to a database.
<input type="file" name="image">
<input type="submit" name="upload" value="Add" action="viewpage.php">
EDIT: IMAGE OF DATABASE:
The second image above still shows the original image file name in the database while the image name in the directory already changed.
Yor can try this..
<?php
if(isset($_POST['submit_btn']))
{
$tmp_file = $_FILES['uploadedfile']['tmp_name'];
$ext = pathinfo($_FILES["uploadedfile"]["name"], PATHINFO_EXTENSION);
$rand = md5(uniqid().rand());
$post_image = $rand.".".$ext;
move_uploaded_file($tmp_file,"../post_imgs/".$post_image);
}
?>

PHP: Encode image Base64 local

I want to convert a image to Base64 and put in into my database.
I know how to encode a image to Base64, but I dont know how to use a file from a user.
So the user can "upload" a file with <input type="file" />
But how can I approach that file without download the file and store it at my server?
So i encode the file actually localy on the user his/her computer
Thanks
The BLOB datatype is best for storing files.
This PHP sample goes over it pretty well
Also see: How to store .pdf files into MySQL as BLOBs using PHP?
The MySQL BLOB reference manual has some interesting comments
if you do not want to save the file to the database, but just read it, use:
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 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);
$content here has the file content
To encode an image to base64 you can use file_get_contents to read the image file:
$imageBinaryString = file_get_contents('/image/file/path.png');
http://us1.php.net/file_get_contents
Then base64 encode:
$base64_imageString = base64_encode($imageBinaryString);
You can then store in database in a column with type text or varchar.
<input type="file" name="icon" />
Now try with below code.
$base = $_REQUEST['icon'];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('upload/imagename.png', 'wb');
$imagename = 'path_to_image_/images.png';
fwrite($file, $binary);
fclose($file);

file upload method in php?

i don't know why file is not uploaded in database.
i am tried to check this method why file is not uploaded.
this method is used a lots of time. and worked successfully at every time.
if any mistake please correct it.
<?php
//database connection successfully worked.
$manu = $_POST['manu'];
if(isset($_POST['img_submit']))
{if($_FILES['file']['name']<>"")
{$file =time().'_'.$_FILES['file']['name'];
if (!copy($_FILES['file']['tmp_name'],"file/".$manu))
{$message = "Invalid File type.Upload only JPEG and GIF files";}
if(move_uploaded_file($_FILES['file']['tmp_name'], $manu)) {$msg2 = "The file ". basename( $_FILES['file']['name']). " has been uploaded";}
else{$msg3 = "There was an error uploading the file, please try again!";} }
echo $query = "insert into upload_image (upload_img) values('".$manu."')";
mysql_query($query) or die (mysql_error());
}?>
<form name="form" action="" method="post" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="4" cellpadding="5">
<tr><td align="center" colspan="2"> <b>Upload Image</b></td></tr>
<tr>
<th width="50%"> Image Url :</th>
<td width="50%"> <input type="file" name="manu" value="" /></td>
</tr>
<tr><td align="center" colspan="2"><input type="submit" name="img_submit" value="Upload Image" /></td></tr></table></form>
You so don't want to have this code on your server.
<?php
//database connection successfully worked.
$manu = $_POST['manu'];
...
if(move_uploaded_file($_FILES['file']['tmp_name'], $manu)
This basically means that if I have control of my browser (I have), I can send along a file with a fake MIME type and a full path of my choice in $_POST['manu'], and your server will save this file in any folder I want where it has write access to, without checking.
Just suppose I were to upload evil_haxxor_skr1pt.php with a MIME type of image/jpeg somewhere where your server code might find it, and execute it on my behalf...
Fr starters, you use the copy() function and move_uploaded_file(). Don't use the copy()! That's a big security breach!
If you want to save in the DB you need to use something like the file_get_contents() to get all the contents of the file, then you just use that data directly into the DB like you did with the $manu variable.
Don't forget to filter the input.
By the way, don't use the mysql_* functions, use mysqli_* functions. mysql_* are already too old and outdated.

Categories