I am trying to do a file check in an MVC framework, and even if I put the file with a jpg format, I am getting error
This is the function that checks the format
public function addAction()
{
$upload = new Upload();
if($this->request->isPost())
{
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed))
{
echo 'error';
}
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
if($upload->save())
{
Router::redirect('upload');
}
}
$this->view->uploas = $upload ;
$this->view->displayErrors = $upload->getErrorMessages();
$this->view->postAction = PROOT . 'upload' . DS . 'add';
$this->view->render('upload/add');
}
And this is the HTML code:
<div class="col-lg-6 upload-position center" >
<input type="file" id="file" name="file" >
</div>
The isPost method checks if the form method is post
For the next one looking for it :)
To upload a file you will need enctype="multipart/form-data":
<form enctype="multipart/form-data">
<input type="file" name="file"/>
</form>
Related
Hi I'm new to php and keep getting this error: "Warning: Invalid argument supplied for foreach() in /home/site/folder/upload.php on line 61."
I'm trying to build a form in which users can upload one or more photos automatically to a directory to then be displayed else where.
Whenever I use this form I created it functions properly on my website but unfortunately it keeps printing that error out and would like it to go away. Here is my code I'm working with:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
// check if uploads directory exists
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
?>
</div>
Try
if (count($_FILES)) {
foreach($_FILES["images"]["name"] as $k=>$name) {
....
}
}
I tested your script, it works fine. The error message appears because you are not checking that a file got uploaded before starting the foreach. If I land on the page, the PHP code will still be triggered. To fix this, you may use the below:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
if( $_POST['submit'] ) {
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
}
?>
</div>
if( $_POST['submit'] ) will ensure that the form is submitted prior to running the rest of the PHP code.
try multiple file upload in Laravel so my code for view is
<input type="file" name="photos">
but i facing this problem to cant exact type .. ?
$img = $request->file('photos');
$fileExtension=$img->getClientOriginalExtension();
If you are posting single image. You try this code :-
if($request->hasFile('photos')){
if (Input::file('photos')->isValid()) {
$file = Input::file('photos');
$destination = 'images/Foldername'.'/';
$ext= $file->getClientOriginalExtension();
$mainFilename = str_random(6).date('h-i-s');
$file->move($destination, $mainFilename.".".$ext);
echo "uploaded successfully";
}
}
Make sure You have added the enctype in form:-
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="photos">
</form>
If you are uploading multiple images. Try this code:-
if ($request->hasFile('photos')) {
$files = $request->file('photos');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$destinationPath = 'images/Foldername'.'/';
$file->move($destinationPath, $fileName);
}
}
And form must look like this :-
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="photos[]" multiple>
</form>
Hope it helps!
In $img you got an array. And you shoud use loop like foreach to operate with $img
I'm new in PHP area. This is my try to upload a file:
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
if($file['error'] === 0) {
$distination = 'uploads/';
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = $distination . uniqid('', true) . '.' . $file_ext;
if(!move_uploaded_file($file['name'], $filename)) {
echo "File upload failed!";
}
}
}
?>
<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
the return value from the move_uploaded_file always false. I create the uploads folder in the same directory as the upload script file.
Your main problem is fact that you use name instead of tmp_name value from $_FILES array.
name is original name of uploaded file, tmp_name is location of file after upload. Manual Page
Fixed version below. I also added check for destination directory and automatic creation of it if not available.
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
if($file['error'] === 0) {
$distination = 'uploads/';
if(!file_exists($distination)){
mkdir($distination, 0777, true);
}
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = $distination . uniqid('', true) . '.' . $file_ext;
print_r($file);
if(!move_uploaded_file($file['tmp_name'], $filename)) {
echo "File upload failed!";
}
}
}
?>
<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
I have a single file named test.php. In this file, I written below codes to upload a picture (.PNG and .JPG). I also add some code to make a preview of pictures before being uploaded...
Nothing seems to be wrong but when I press the SUBMIT button, nothing happens...
Why? Where is my problem?
Update: I make changes and now I get this warning:
Warning: Invalid argument supplied for foreach() in...
test.php:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<body>
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
define ("UPLOAD_DIR" , "uploaded/pic/");
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
$info = getimagesize($_FILES["images"]["tmp_name"][$key]);
$image_type = $info[2];
$type = $_FILES['images']['type'][$key];
// if the image is .JPG or .PNG
if ( ($image_type == 3) || ($image_type == 2) ){
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $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($_FILES["images"]["tmp_name"][$key], 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);
echo "<h2>Successfully Uploaded Images</h2>";
}
else{
echo "<h2>format not supported... </h2>";
}
}
}
}
?>
<div id="upload_form">
<form id="frm1" name="frm1" method="post" action="test.php" enctype="multipart/form-data">
<p>
<label for="images">insert your image</label>
<input type="file" name="images" id="images" tabindex="80"/>
</p>
<img id="pic" name="pic" src="#" />
<button type="submit" id="submit" name="submit">Upload Files!</button>
</form>
<script type="text/javascript" language="javascript">
// Preview the picture before Uploading on the server!
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#images").change(function(){
readURL(this);
});
</script>
</div>
You need to put your name="images as an array using []
Like this:
<input type="file" name="images[]" id="images" tabindex="80"/>
I try to upload pictures from a form in PHP.
I've got a strange problem regarding my images upload:
My form:
<form id="booking-step" method="post" action="add.php" class="booking" autocomplete="off" enctype="multipart/form-data">
<input type="file" id="AddPhotos1" name="AddPhotos[]" />
<input type="file" id="AddPhotos2" name="AddPhotos[]" />
<input type="file" id="AddPhotos3" name="AddPhotos[]" />
<input type="file" id="AddPhotos4" name="AddPhotos[]" />
<input type="file" id="AddPhotos5" name="AddPhotos[]" />
</form>
My PHP:
if($_FILES['AddPhotos']){
$errorAddPhotos = "";
$validAddPhotos = "";
for($x=0;$x<sizeof($_FILES["AddPhotos"]["name"]);$x++){
$fichier = basename($_FILES['AddPhotos']['name'][$x]);
$taille_maxi = 3000;
$taille = filesize($_FILES['AddPhotos']['tmp_name'][$x]);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['AddPhotos']['name'][$x], '.');
if(!in_array($extension, $extensions))
{
$errorAddPhotos .= "Wrong extension.<br />";
}
if($taille>$taille_maxi)
{
$errorAddPhotos .= "Wrong size.<br />";
}
if((in_array($extension, $extensions)) && ($taille<$taille_maxi))
{
$fichier = strtr($fichier,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
if(move_uploaded_file($_FILES['AddPhotos']['tmp_name'][$x], $destin . $fichier))
{
$validAddPhotos = 'Success!';
}
else
{
$errorAddPhotos = 'Wrong';
}
}
}
}
echo $validAddPhotos;
echo $errorAddPhotos
My code looks good, but I cant upload my files...
Error: my files stay in condition "if(!in_array($extension, $extensions))".
Could you please help ?
Thanks.
I think you should use this logic is more perform than yours with testing image type and file size. Also, you can custom it with what you want like you did name of the file :)
multiple upload image function php?