$org_file_name = $_FILES['file1']['name'];
$file_size = $_FILES['file1']['size'];
$ext = strtolower(pathinfo($org_file_name, PATHINFO_EXTENSION));
$file_path = 'docs/';
$rand = rand(111,999);
if($ext == 'csv')
{
if(file_exists($file_path))
{
$file_path = 'docs/'.$org_file_name;
}
if(!move_uploaded_file($_FILES['file1']['tmp_name'],$file_path))
{
die ('<script> alert("file not uploaded successfully."); </script>');
}
}
else
{
die ('<script> alert("Uploaded only CSV files."); </script>');
How Do I rename CSV file when uploading and insert into database with renam and after insert show csv column headings in buttons
CSV headers (if present) are located right on the first line. So you can simply do:
$delimiter = ',';
$headers = fgetcsv(fopen($file_path, 'r'), $delimiter);
if (is_array($headers)) {
foreach($headers as $header) {
echo "<input type=\"button\" name=\"$header\"
value=\"$header\"/>'";
}
}
}
And to rename the file while moving, you should change the second parameter of move_uploaded_file() to the desired name. If you like, you can get a unique ID using sha1_file($_FILES['file1']['tmp_name']). It will also avoid duplicated storage of identical files.
Related
I am making a javascript XMLHttpRequest() request to execute some php in the background. Now I know the callback will only receive the first response from php. How can I get output to send back what php is echoing as it is happening to show it on the main page as php is running in the background?
javascript
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var phpResponse = this.responseText
// i know this will only be the first thing echoed by php
}
};
xhttp.open("GET", "scan.php?scanRoot=yes", true);
xhttp.send();
php run in the back ground
function rootDirFileSort($scanDir,$getID3){
//Sort stray files in root directory. Put them in a dir named by artist
$printFix = str_repeat(" ", 8157);
$files = array_diff(scandir($scanDir), array('.', '..'));
//Get files in dir. Only get flac and mp3 files
$FilesArray = array_diff(scandir($scanDir), array('.', '..'));
$FilesArray = preg_grep('~\.(flac|mp3)$~', $FilesArray);
$files = array_values($FilesArray);
foreach ($files as $file){
$file_Basename = basename($file);
// Get the metadata from file. Returns as an array
$metaDataArray = $getID3->analyze($scanDir.$file);
//Check for ID3v1 metadata container
if (isset($metaDataArray['tags']['id3v1']['artist'][0])){
$artist = $metaDataArray['tags']['id3v1']['artist'][0];
$artist = str_replace(array('.',',','?','/','\\','$'), array('','','','','',''), ucwords($artist));
}else{
$artist = '';
}
//Check for vorbis comment metadata container
if(isset($metaDataArray['tags']['vorbiscomment']['artist'][0])){
$artist = $metaDataArray['tags']['vorbiscomment']['artist'][0]; echo $artist;
$artist = str_replace(array('.',',','?','/','\\','$'), array('','','','','',''), ucwords($artist));
}else{
$artist = '';
}
//If the artist meta tag is present move the file
if(!empty($artist)){
//Check if diretory exists before making one
if(!is_dir($scanDir.$artist)){
//If file DOES NOT exist
mkdir($scanDir.$artist, 0755, true);
rename($scanDir.$file, $scanDir.$artist.'\\'.$file);
echo $file.'<br>'.$artist.'<br>Moved To: '.$scanDir.$artist.'\\'.$file.'<br><br>'.$printFix;
}else{
//If file exists
rename($scanDir.$file, $scanDir.$artist.'\\'.$file);
echo $file.'<br>'.$artist.'<br>Moved To: '.$scanDir.$artist.'\\'.$file.'<br><br>'.$printFix;
}
}else{
//Put failures in an array to show which failed when done
$notProcessed[] = array('musicFile'=>$file_Basename);
}
}
//Show all the failures if they exist
if(count($notProcessed) >= 1){
echo '<strong>***** These items failed as they don\'t contain ID3v1, ID3v2 or Vorbis Comment meta container. Manually process directories. *****</strong><br><br>';
foreach($notProcessed as $value){
echo '<strong>File:</strong> '.$value['musicFile'].'<br><br>'.$printFix;
}
}
echo '<br><br>------------------------- Root File Scan Finished! -------------------------'.$printFix;
}
I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.
I'm having difficulting on what problem my code is facing. instead of just updating the record that i am supposed to code for example i am just going to update the image for my "Google tour package" instead of just updating the image of it, it updates all the record , so what happened is all the image in my db is all the same. i think the problem is on the where clause.
This is windows server running sql and apache in xammp v3.2.2
$targetDir = "../../../../../../img/itinerary/";
$fileName = basename($_FILES["itinerary_img"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
$itinerary_id = $_GET['id'];
if(!empty($_FILES["itinerary_img"]["name"]))
{
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes))
{
if(move_uploaded_file($_FILES["itinerary_img"]["tmp_name"],
$targetFilePath))
{
// Insert image file name into database
$insert ="UPDATE 'tms_itinerary' SET itinerary_img = ".$fileName."' WHERE itinerary_id = '".$itinerary_id."' ";
$result2 = mysqli_query($mysqli, $insert);
if($result2){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
i expect the output to only change the image of the one i am updating and not all of the itinerary_image
public function ExportCSV()
{
// THIS PART IS WORKING
$this->load->dbutil();
$this->load->helper('file');
$delimiter = ',';
$newline = "\n";
$enclosure = '"';
$filename = "tamp.csv";
$query = "SELECT politician.id, politician.ident, party.abbr, politician.id_image, politician.name, politician.surname, politician.personal_birth, politician.home_city, politician.political_function
FROM politician
INNER JOIN party
WHERE party.id = politician.id_party
LIMIT 10000";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline, $enclosure);
// data IS CORRECT
// THIS PART NOT WORKING: write_file() returns false
if ( ! write_file(APPPATH."/assets/media/upload/tamp.csv", $data, 'r+'))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
}
The variable $data contains the correct output but the write_file() returns false.
The directory /assets/ is in the main directory of the codeigniter project.
My questions are:
Is this function returning false because I don't have the permission to write in this directory?
If yes, what should I do?
In which directory should I write this file as I would like it public?
When creating a file with write_file make sure your folder/directory is there where you would like to create file
Then I would recommend using FCPATH
$data = "Some file data";
if (write_file(FCPATH . '/document/text.txt', $data) == FALSE)
{
echo 'Unable to write the file';
} else {
echo 'File written!';
}
My directory
application
document
system
index.php
Hello I have a view file and controller, what makes multiple inputs where I can upload files in to folder, but its uploading only one file in to folder. I know what is problem, but I dont know how to fix this or how to do this.
My Controller:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
//print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
My View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
And this script what Im using in View :
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I think that, the problem is in input names. If Im doing more inputs, then the inputs names are same, and thanks to this its uploading only one file in to webroot/files folder, but I want these all.
Can anybody help me or give me some tips.
Thanks !
Here is someone with almost exactly the same issue as you have:
Create multiple Upload File dynamically
Try doing the same. I haven't programmed PHP for quite some time, but I guess you should replace data[files] to just data[], so it creates a new array item for each field. Now you are giving each field the same name.
Then you can loop over them in your controller by using:
foreach($_FILES['data'] as $file){
//do stuff with $file
}
EDIT 2:
As you are saying, you want to upload the files (not to a db). So I guess this should work:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $file)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
}
Try this function:
function multi_upload($file_id, $folder="", $types="") {
$all_types = explode(",",strtolower($types));
foreach($_FILES[$file_id]['tmp_name'] as $key => $tmp_name ){
if(!$_FILES[$file_id]['name'][$key]){
$return[$key]= array('','No file specified');
continue;
}
$file_title = $_FILES[$file_id]['name'][$key];
$ext_arr = pathinfo($file_title, PATHINFO_EXTENSION);
$ext = strtolower($ext_arr); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,5);
$file_name = $uniqer . '_' . $file_title;//Get Unique Name
if($types!=''){
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name'][$key]."' is not a valid file."; //Show error if any.
$return[$key]= array('',$result);
continue;
}
}
//Where the file must be uploaded to
if($folder) $folder .= '/';//Add a '/' at the end of the folder
$uploadfile = $folder . $file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'][$key], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name'][$key]."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
}
else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
}
else {
#chmod($uploadfile,0777);//Make it universally writable.
}
}
$return[$key]=array($file_name,$result);
}
return $return;
}
html: <input type="file" name="data_file[]" id="uploadFilefiles">
Call by multi_upload("data_file","upload_to_folder","pdf,jpg,txt,bmp")