HTML form data to PHP script - php

What small background I have is in Python. I've never used PHP before, so I'm somewhat lost. What I'm trying to do is upload files through an HTML form and then parse the files with a PHP script and display the results back to the user.
This is my HTML:
<html>
<form enctype='multipart/form-data' action='read.php'
method='POST'>
<input type='hidden'/>
Choose a file to upload: <input name='uploadedfile' type='file' multiple /><br />
<input type='submit' value='Upload File' />
</form>
</html>
it seems to work, but I could be missing something obvious.
My PHP script is
<?php
if ($_FILES['uploadedfile']['name'] !==false)
file_get_contents($_FILES);
foreach (glob($_FILES["uploadedfile"]["name"]) as $file) {
if (is_uploaded_file($file['temp_name']))
$file_handle = fopen(file, "r");
while (feof($file_handle)) {
$e = array("code", "money", "notes", "date2");
$n = 0;
$line = fgets($file_handle);}
foreach($line as $value) {
if ($n=0);
if (strpos($line, 'Sent:') !==false);{
array_push($e, $line);}
if (strpos($line, 'REFERENCE NUMBER:') !==false) ;{
$n = 1;
array_push($e, $line);}
if ($n<40);{
array_push($e, $line);
$n = $n+1;}
echo $e;}}
?>
It doesn't do anything, and I'm not even sure whether the files are going through or if I just don't know how to access them. Any help would be appreciated.

If you would like to upload multiple files, you need to set name of input as array:
<input name='uploadedfile[]' type='file' multiple />
And then you can read all uploaded files in cycle:
<?php
foreach ($_FILES['uploadedfile']['error'] as $i => $error) {
if ($error === UPLOAD_ERR_OK) {
$file_handle = fopen($_FILES['uploadedfile']['tmp_name'][$i], 'r');
// your code here
} else {
// check error number: http://php.net/manual/en/features.file-upload.errors.php
}
}

Related

File not being created in PHP?

I've made this code in PHP because I want to practice file handling.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form action = "index.php" method = "get">
Do you want to make a new file (NF), edit a file (EF), or delete a file (DF)?
<input type = "text" name = "FileHandling">
<input type = "submit">
<br/>
</form>
<?php
$FileCommand = $_GET['FileHandling'];
if($FileCommand == 'NF') {
echo "<form action = 'index.php' method = 'get'><br/>";
echo "What is the new file's name?<br/>";
echo "<input type = 'text' name = 'CreateFile' method = 'get'><br/>";
echo "<input type = 'submit'><br/>";
$FileName = $_GET['CreateFile'];
echo $FileName;
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
}
?>
</body>
</html>
However, there is a problem after you choose 'NF' and type in the file name. The file does not get created:
echo $FileName;
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
}
You have a bug in the way you're handling inputs and forms. Currently, you're checking $FileCommand == 'NF', which is true on the first form submission. But then the page reloads and you get a second form with a new input. So when you fill in the second form and resubmit it, now <input name='FileHandling' /> wasn't submitted because it wasn't part of this form (it's part of the first form).
So if you change your PHP to the following, the file will be attempted to be created if $FileName !== null (regardless of the value of $FileCommand) rather than your previous logic which also required $FileCommand == 'NF'. This moves the logic for creating the file outside of the first if.
<?php
$FileCommand = $_GET['FileHandling'];
if ($FileCommand == 'NF') {
echo "<form action='index.php' method='get'><br/>";
echo "What is the new file's name?<br/>";
echo "<input type='text' name = 'CreateFile'><br/>";
echo "<input type='submit'><br/>";
echo "</form>";
}
$FileName = $_GET['CreateFile'];
if (null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
?>
Another way to handle this would be to create only a separate field instead of a completely separate form.
<html>
<body>
<form action="index.php" method="get">
Do you want to make a new file (NF), edit a file (EF), or delete a file (DF)?
<br>
<input type="text" name="FileHandling" />
<br>
<?php
$FileCommand = #$_GET['FileHandling'];
if($FileCommand == 'NF') {
echo "What is the new file's name?<br/>";
echo "<input type='text' name = 'CreateFile' /><br/>";
}
?>
<input type="submit">
</form>
<?php
$FileName = $_GET['CreateFile'];
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
?>
</body>
</html>
When you create new form get request blocked because of page reload.
This is working code to solve your problem.
<form method="get" action="index.php">
<input type="text" name="filehandling">
<input type="submit" name="createfile">
</form>
<?php
if ( isset($_GET['createfile']) ) {
$fh = $_GET['filehandling'];
if ($fh == 'NF') {
echo '
<form method="get">
<input type="text" name="filename">
<input type="submit" name="createnewfile">
</form>
';
}
}
if ( isset($_GET['createnewfile']) ) {
$filename = $_GET['filename'];
$f = fopen($filename, "w");
fclose($f);
}
?>
Try to use is_null() PHP function to get the desired result
Change your code to
if(!is_null($FileName)) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
}

php count variable outside loop being reset

I've set $count as counter outside foreach loop, but it seemed to be reset everytime. This php is used to upload multiple files.
$count = 0;
foreach ($_FILES["my_file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$count++;
echo "<script>alert(".$count.");</script>";
$tmp_name = $_FILES["my_file"]["tmp_name"][$key];
$name = basename($_FILES["my_file"]["name"][$key]);
move_uploaded_file($tmp_name, "upload/". $SN."/".$name .$count);
echo json_encode(array('id' => 'message', 'data' => 'successful'));
}
}
echo "<script>alert(".$count.");</script>"; to observe the counter , and if upload three files it will alert '1' three times. Also, I added $count to upload filename, for example , filename 1.jpg,2.jpg , after uploading ,the filename will become 1.jpg1, 2.jpg1, it supposed to be 1.jpg1,2.jpg2. what is wrong with my loop?
html code:
<form method="post" action="ImagesUpload.php" id="myForm1" enctype="multipart/form-data">
<input name="my_file[]" id="file-fr" type="file" class="file" data-preview-file-type="text" multiple>
</form>
Are you using AJAX to upload?
I added a submit button to your code and it worked.
Also, are you sure you are selecting more than one file?
See modified code:
HTML
<form method="post" action="upload.php" id="myForm1" enctype="multipart/form-data">
<input name="my_file[]" id="file-fr" type="file" class="file" data-preview-file-type="text" multiple>
<input type="submit" >
</form>
PHP
$count = 0;
if(isset($_FILES["my_file"])){
print_r($_FILES["my_file"]);
foreach ($_FILES["my_file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$count++;
echo "<script>alert(".$count.");</script>";
$tmp_name = $_FILES["my_file"]["tmp_name"][$key];
$name = basename($_FILES["my_file"]["name"][$key]);
move_uploaded_file($tmp_name, "upload/". $SN."/".$name .$count);
echo json_encode(array('id' => 'message', 'data' => 'successful'));
}
}
}
Both blocks of code are in the same file.

PHP Upload and process a CSV file

I have an upload form which takes a csv file. Then I process it with PHP.
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Ladda upp!" class="upload_sub"/>
<br />
<br />
</form>
<?php
if(isset($_POST['submit'])) {
if($_FILES["csv"]["error"] > 0) {
echo 'Ett fel inträffade vid uppladdning av filen. Var god försök igen.';
} else {
$tmp = $_FILES['csv']['tmp_name'];
$import = new Importer();
$import->importTariff($tmp);
}
}
?>
lib.php class Importer ( I only submit the relevant function )
public function importTariff($tmp) {
if(($handle = fopen($tmp, 'r')) !== FALSE) {
while(($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
echo 'foo';
}
}
}
For testing purposes I would like to print 'foo' for each line in the csv. However I get no errors or anything like it so any ideas?
print_r($_FILES);
Check out your NAME from file-input:
<input type="file" name="file" id="file" />
Rename it to name="csv" or change $_FILES["csv"] to $_FILES["file"]
The issue was not PHP related. I've looked into the table design and I noticed that the id column was unsigned and not checked for incredement.

PHP get names of multiple uploaded files

Hi im trying to create a script to upload multiple files.
everythings works so far and all files are being uploaded.
My problem now is that i need to grap each file name of the uploaded files, so i can insert them in to a datebase.
Here is my html:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image[]" multiple />
<input type="submit" value="upload" />
And here is the php:
if (!empty($_FILES['image'])) {
$files = $_FILES['image'];
for($x = 0; $x < count($files['name']); $x++) {
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
$size = $files['size'][$x];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
}
Really hope someone can help me with this.
/JL
You have your indexes backwards. $_FILES is an array, with an element for each uploaded file. Each of these elements is an associative array with the info for that file. So count($files['name']) should be count($files), and $files['name'][$x] should be $files[$x]['name'] (and similarly for the other attributes. You can also use a foreach loop:
foreach ($_FILES as $file) {
$name = basename($file['name']);
$tmp_name = $file['tmp_name'];
$size = $file['size'];
if (move_uploaded_file($tmp_name, "../folder/" .$name)) {
echo $name, ' <progress id="bar" value="100" max="100"> </progress> done <br />';
}
}
I think the glob() function can help:
<?php
foreach(glob("*.jpg") as $picture)
{
echo $picture.'<br />';
}
?>
demo result:
pic1.jpg
pic2.jpg
pic3.jpg
pic4.jpg
...
be sure to change the file path and extension(s) where necessary.
Thanks for the help, i got it to work by simply creating variables:
$image_1 = (print_r($files['name'][0], true));
$image_2 = (print_r($files['name'][1], true));
$image_3 = (print_r($files['name'][2], true));

Uploading files with PHP

I am using a form for users to upload files to my website. I want to allow them to upload multiple photos at once, so I am using the HTML5 "multiple" attribute.
My HTML:
<form method="post" action="save.php">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
But, for some reason when I run the script, I get an error saying undefined index: uploads. And an error saying that I have an invalid argument supplied for foreach(). What could I be dong wrong?
Thanks
UPDATE
Okay, setting the enctype="mulitpart/form-data" worked. Now, I am having trouble with moving the file. I am getting the error move_uploaded_file() expects parameter 1 to be string, array given. What am I doing wrong here?
Thanks again
You need the proper enctype to be able to upload files.
<form method="post" enctype="multipart/form-data" action="save.php">
try this html code: <form method="post" action="save.php" enctype="multipart/form-data">
Then in PHP:
if(isset($_FILES['uploads'])){
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
} else {
echo 'some error message!';
}
In order to upload files in the first place, you need enctype="multipart/form-data" on your <form> tag.
But, when you upload multiple files, every key in $_FILES['uploads'] is an array (just like $_FILES['uploads']['name']).
You need to get the array key when looping, so you can process each file. See the docs for move_uploaded_file for more deatils.
<?php
foreach ($_FILES['uploads']['name'] as $key=>$file) {
echo $file."<br/>";
$file = time().$file;
$target = UPLOADPATH.$file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with query 2');
}
index.html
<form method="post" action="save.php" enctype="multipart/form-data">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="Upload Image"/>
</form>
save.php
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) {
$file_name = time() . $_FILES['uploads']['name'][$x];
$file_tmp = $_FILES['uploads']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name;
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>

Categories