Local text file to variable in PHP - php

I'm trying to capture the text in a local .txt file to a PHP variable so I can save to database. I've been at it for hours and no luck. I've tried just about everything but this is what I currently have. Most of it is commented out for debugging.
As-is it just shows me a blank page and doesn't echo anything. What am I doing wrong? Any suggestions would be greatly appreciated.
EDIT:
Complete updated code. With errors on I'm getting a notice about an undefined index on line 12.
<?php
error_reporting(E_ALL); ini_set('display_errors','1');
?>
<html>
<head>
<title>upload file</title>
</head>
<body>
<?php
$size = $_FILES['file']['size'];
$filename = $_FILES['file']['tmp_name']; // name of the file
//$max_filesize = 100000; // Maximum filesize in BYTES
//$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// if($ext = "txt") //check for .txt
// die('Only .txt files allowed.');
// if($size > $max_filesize) //check file size
// die('File is too large');
if(file_exists($filename)){
$fp = fopen($filename, "r");
$str = fread($fp, filesize($filename));
echo $str;
fclose($fp);
}
?>
</body>
</html>
And the upload form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>

Test for $_FILES['uploadedfile']['tmp_name'] - this is the location of temporary file created on the server. $_FILES['uploadedfile']['name'] contains the original name of the uploaded file on client's side.
Update the code:
$size = $_FILES['file']['size'];
$filename = $_FILES['file']['name'];
to
$size = $_FILES['uploadedfile']['size'];
$filename = $_FILES['uploadedfile']['tmp_name'];
Documentation for the $_FILES variable can be found in PHP manual. Check out this tutorial for uploading files with PHP.
Apart from that, correct the $size($filename) to filesize($filename).

use filesize insead of $size so that it reads $str = fread($fp, filesize($filename));

Related

how to upload multiple images on a website using php

I am trying to upload multiple images on my website when user clicks on upload button. I was able to do that for one image, but I am not sure how to do for multiple images.
My code:
index.php
<html>
<head></head>
<body>
<form action="backend.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" >
<button type="submit" name="submit">button</button>
</form>
</body>
</html>
database.php
<?php
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', 'pdf');
if (in_array($fileActualExt, $allowed)) {
if($fileError === 0) {
if ($fileSize < 10000000) {
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: index.php?uploadsuccess");
} else {
echo "Your file is too big!";
}
} else {
echo "There was an error uploading your file";
}
} else {
echo "You cannot upload files of this type!";
}
}
?>
I changed a bit in my code (index.html) so I can at least select multiple images: <input type="file" name="file[]" multiple>
but when I do that and click on upload it says:
Warning: explode() expects parameter 2 to be string, array given in /opt/lampp/htdocs/testing/backend.php on line 11
Warning: end() expects parameter 1 to be array, null given in /opt/lampp/htdocs/testing/backend.php on line 12
You cannot upload files of this type!
I assume cause it expects it to be string but I have an array now. How can I make my code work in database.php for multiple files? It works for single image, but not for multiple. If someone can reckon something?
Ok, let's say you have this HTML:
<form action="backend.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file[]" multiple />
<button type="submit" name="submit">button</button>
</form>
Normally (without multiple and with name="file"), your PHP would receive something like this:
$_FILES['file']['name'] // contains the file name
However, sending multiple files, your PHP will receive these files as following:
$_FILES['file']['name'][0] // contains the first file name
$_FILES['file']['name'][1] // contains the second file name
// ...
Read more.

i think move uploaded file is not working even though he can find if the file is existed

If i choose in the same folder of my target directory it said file exist but when i choose in different folder it said success but there`s no file uploaded in that folder here is my code. i get it in google
<?php
if (($_FILES['my_file']['name']!="")){
// Where the file is going to be stored
$target_dir = "/home/cidinc1802/Pictures/";
$file = $_FILES['my_file']['name'];
$path = pathinfo($file);
$filename = $path['filename'];
$ext = $path['extension'];
$temp_name = $_FILES['my_file']['tmp_name'];
$path_filename_ext = $target_dir.$filename.".".$ext;
if (file_exists($path_filename_ext)) {
echo "Sorry, file already exists.";
}else{
move_uploaded_file($temp_name,$path_filename_ext);
echo "Congratulations! File Uploaded Successfully.";
}
}
?>
<form name="form" method="post" action="fortesting.php" enctype="multipart/form-data" >
<input type="file" name="my_file" /><br /><br />
<input type="submit" name="submit" value="Upload"/>
</form>

How to upload files and name them with file type?

hey guys so I created a website that you can upload books to and display them as a list I have a form to input the name of the book and the file type and I want them to display as the name and file type (on the same line) example (nameofabook epub) but when I try is display them it shows up like (nameofabook
new line epub) here's my code thank you
<?php
if (isset($_FILES['file']) && isset($_POST['name'])) {
$file = $_FILES['file'];
$file_name = $file['name'];
$file_type = $file['type'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array("mov", "avi", "mp4", "epub", "pdf"); //The extensions you allow
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) { //the maximum filesize
$file_destination = ''.$file_name; // If ' ', the file will be placed in this directory
if (move_uploaded_file($file_tmp, $file_destination)) {
echo $file_destination;
$fp = fopen('book_list.txt', "a");
fwrite($fp, $_POST['name']. "|||" .$file_destination."\n");
fwrite($fp, $_POST['type']. "|||" .$file_destination."\n");
fclose($fp);
} else {
echo "An error has been encountered while moving your file!";
}
} else {
echo "Your file is too big!";
}
} else {
echo "An error has been encountered while uploading your file!";
}
} else {
echo "You can't upload files of this type!";
}
}
?>
if anyones curious heres my html for the upload page
<!DOCTYPE html>
<html>
<head>
<title>Upload a Book</title>
<link href = "style2.css" type = "text/css" rel = "stylesheet" />
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" required/>
Type: <input type="text" name="type" required/>
File: <input type="file" name="file" required/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Firstly...
Don't upload files directly in your site! You should upload them with an API, outside, in a cloud storage. In this case, you can use Cloudinary . So, you don't need to think much about the files uploaded. Again, you can show them easily!
Don't store information like names and others(without the file) in a text file. Storing them in a MySQL database is the best way to do so.
Secondly...
Use different inputs for collecting book names and other information so that, you can display and modify them easily.
Thirdly...
Please give the code you are using for displaying data
I'm a Homo sapiens So I can write anything wrong. Please forgive me for that.

How to count length of csv file in when uploaded in php ?

code:
<?php
if(isset($_POST['upload']))
{
$filename = $_FILES['files']['name'];
$path = "upload_enq/";
$move = move_uploaded_file($_FILES['files']['tmp_name'],$path.$_FILES['files']['name']);
$path_file = "upload_enq/".basename($_FILES['files']['name']);
$c =0;
$fileObj = fopen( $path_file, "rt" );
if($fileObj){
while(!feof($fileObj)){
$content = fgets($fileObj);
if($content)
$c++;
}
}
fclose($fileObj);
echo $c;
}
?>
<form class="forms-sample" method="post" enctype="multipart/form-data">
<input type="file" name="files" id="files" />
<input type="submit" class="btn btn-success mr-2" name="upload" id="upload" value="Upload" />
</form>
In this code I have create a simple form where I am uploaded csv file and I want to count lenght of csv file. Now what happen when I uploaded csv file which having 295 rows but it shows wrong output it count 926 rows. So, How can I fix this issue ?Please help me.
Thank You
As you said that you need the row count of the csv file, so use file()
$fp = file( $path_file, FILE_SKIP_EMPTY_LINES);
echo count($fp);
So the code will become short now
<?php
if(isset($_POST['upload']))
{
$filename = $_FILES['files']['name'];
$path = "upload_enq/";
$move = move_uploaded_file($_FILES['files']['tmp_name'],$path.$_FILES['files']['name']);
$path_file = "upload_enq/".basename($_FILES['files']['name']);
$fp = file( $path_file);
echo count($fp);
}
?>
I have tested it on local:-
https://prnt.sc/jody8e
https://prnt.sc/jodyjl
https://prnt.sc/jodyoz
As per my comments use Count function to get total number of rows in CSV file like this
$fileObj= file('filename.csv');
echo count($fileObj);
for more details read PHP Manual

ImageMagick - writeImage output produce 8 bit depth image instead of 24 bit depth image

I am really new to this ImageMagick & GhostScript thus, I am confused what I have done wrong.
I am trying to convert the cover page of the PDF to JPG, but some of the writeImage output, produce colored once - 24bit, and most produce mono-coloured - 8bit(Which I don't want).
My code is:
<html>
<head>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" id="pdf" name="file" accept=".pdf"/>
<input type="file" id="imagePDF" style="display:none">
<input type="submit" value="upload"/>
</form>
</body>
<?php
if(isset($_FILES['file'])){
//Save file to directory
$file = $_FILES['file'];
$file_destination = "files/";
//File properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
//Work out the file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('pdf');
if(in_array($file_ext, $allowed)){
if($file_error === 0){
if($file_size <= 63000000){
//File destination relative to upload.php
$pdfWithPath = $file_destination . $file_name;
if(move_uploaded_file($file_tmp, $pdfWithPath)){
echo("File uploaded: <br>");
echo $pdfWithPath;
}
}
}
}
//Create thumbnail and save to directory
$thumb_name = $file_name . ".jpg";
$thumb_destination = "pdfThumb/";
$thumb_path = $thumb_destination . $thumb_name;
$thumb_first_page = $pdfWithPath . "[0]";
$image = new Imagick();
$image->readImage(__DIR__ . DIRECTORY_SEPARATOR . $thumb_first_page);
$image->writeImage(__DIR__ . DIRECTORY_SEPARATOR .'pdfThumb/'.$thumb_name);
$image->destroy();
echo("Done");
}
?>
<html>
<head>
<!--Display image on screen -->
<img src="<?php echo $thumb_path; ?>"/>
</head>
<body>
</body>
</html>
The idea of this code is to upload the pdf and store it into the folder 'files'
Then to create the thumbnail of the PDF file, it will retrieve the PDF from the folder 'files' and produce an image, saving the image to the folder 'pdfThumb'
I have 2 outcomes for this writeImage, colored and mono-coloured shown below
Mono-coloured image produced
Coloured image produce
I want to make all the images produced by the writeImage output to be all colored.
How should I improve my code?

Categories