I cannot upload the images while using angular and php using this code.
please assist..
I got an error undefined index error on line 2 from php
angular side
const formData = new FormData();
formData.append('date', this.uploadRequest.date.toString());
formData.append('description', this.uploadRequest.description);
formData.append('title', this.uploadRequest.title);
this.imageDetails.forEach((image, i) => {
formData.append('images[' + i + ']', image.file);
});
const params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', '/api/upload', formData, options);
return this.http.request(req).subscribe();
php side
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if (!empty($_FILES['image'])) {
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
$uploadOk = 1;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = time() . '.' . $ext;
move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' .
$image);
echo "Image uploaded successfully as " . $image;
} else {
echo "Image Is too Large";
}
} else {
echo "Image Is Empty";
}
You need to put your code inside the if statement. You are trying to execute a code before the if statement is ran and that code is crucial for the if statement to function properly.
if (!empty($_FILES['image'])) {
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
$uploadOk = 1;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = time() . '.' . $ext;
move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' .
$image);
echo "Image uploaded successfully as " . $image;
} else {
echo "Image Is too Large";
}
} else {
echo "Image Is Empty";
}
Related
I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?
this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.
I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.
I have googled this question but did not find an answer. I am using the ng-file-upload Angular directive to upload images to my back-end. At the back-end I am using php to retrieve the image. It works fine if I select an image which contains no white space. But if I select an image which contains white space it throws an error. This is what I did
//app.js
Upload.upload({
url: "api/index.php/postNewFeedsWithPicture",
file: $scope.file,
method: "post"
}).then(function (response) {
$scope.isShowing = false;
if (response.data.error) {
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.error(response.data.message, {timeOut: 5000});
}
else {
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.success(response.data.message, {timeOut: 5000});
$scope.file = null;
}
}, function (reason) {
$scope.isShowing = false;
toastr.options = {positionClass: 'toast-bottom-full-width'};
toastr.error('Message not posted! Network error', {timeOut: 5000});
});
in my html file i did this
<div role="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB">Upload</div>
in my php file I wrote a function that saves the image
function savePictureToDb($fileName, $dirName) {
$target_dir = "../image/" . $dirName . "/";
$target_file = $target_dir . basename($_FILES[$fileName]["name"]);
$uploadOk = 1;
$errorMsg = null;
$report = array();
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size. //20mb
if ($_FILES[$fileName]["size"] > 20000000) {
$uploadOk = 0;
$errorMsg = "File size is greater than 20 mega bytes";
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
$uploadOk = 0;
$errorMsg = "The file selected is not an image";
}
if ($uploadOk == 0) {
$report[ERROR] = TRUE;
$report[MESSAGE] = $errorMsg;
return $report;
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES[$fileName]["tmp_name"], $target_file)) {
rename($target_file, $target_dir . generateRandStr_md5(500) . "." . $imageFileType);
$response['path'] = basename($_FILES[$fileName]["name"]);
$report[ERROR] = FALSE;
$report[PATH] = $response['path'];
return $report;
} else {
$errorMsg = "Unexpected error";
$report[ERROR] = TRUE;
$report[MESSAGE] = $errorMsg;
return $report;
}
}
}
It works fine, but if the image contains white space this is the error i get when debugging
array (
'file' =>
array (
'name' => 'Age Declaration.jpg',
'type' => '',
'tmp_name' => '',
'error' => 1,
'size' => 0,
),
)
Rename the file name with random value
$filename1=explode(".", $file);
$extension=end($filename1);
$file=rand().time().".".$extension;
Or Use pathinfo() for extention
$ext = pathinfo($filename, PATHINFO_EXTENSION);
My script is not working properly. If i upload a php file instead of jpg file then it should not upload php files to upload folder, i want to allow only image files. Please correct my script.
Here is my code Thanks !
<?php
include "inc.php";
ob_start();
if(!isset($_SESSION['ocer']) && trim($_SESSION['ocer'])!=''){
header("Location: admin.php?l=1");
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$title=addslashes(mysql_real_escape_string($_REQUEST['title']));
$des=addslashes(mysql_real_escape_string($_REQUEST['des']));
$location=addslashes(mysql_real_escape_string($_REQUEST['location']));
$state=addslashes(mysql_real_escape_string($_REQUEST['state']));
$status=mysql_real_escape_string($_REQUEST['status']);
$userid=mysql_real_escape_string($_REQUEST['userid']);
$date1=mysql_real_escape_string($_REQUEST['date1']);
chmod('upload', 0777);
if($_FILES['file_name1']['name']!="")
{
$file_name1=$_FILES['file_name1']['name'];
$ext=getExtension($file_name1);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name1=mktime().'thumb1'.'.'.$ext;
copy($_FILES['file_name1']['tmp_name'],"upload/".$file_name1);
}
}
if($_FILES['file_name2']['name']!="")
{
$file_name2=$_FILES['file_name2']['name'];
$ext=getExtension($file_name2);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name2=mktime().'thumb2'.'.'.$ext;
copy($_FILES['file_name2']['tmp_name'],"upload/".$file_name2);
}
}
if($_FILES['file_name3']['name']!="")
{
$file_name3=$_FILES['file_name3']['name'];
$ext=getExtension($file_name3);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name3=mktime().'thumb3'.'.'.$ext;
copy($_FILES['file_name3']['tmp_name'],"upload/".$file_name3);
}
}
if($_FILES['file_name4']['name']!="")
{
$file_name4=$_FILES['file_name4']['name'];
$ext=getExtension($file_name4);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name4=mktime().'thumb4'.'.'.$ext;
copy($_FILES['file_name4']['tmp_name'],"upload/".$file_name4);
}
}
if(trim($title)!="" && trim($des)!=""){
$sql_ins="insert into `jobs` set title='$title',des='$des',location='$location',state='$state',date1='$date1',userid='$userid',status='$status',newsimg='$file_name1',newsimg2='$file_name2',newsimg3='$file_name3',newsimg4='$file_name4'";
$rs=mysql_query($sql_ins) or die(mysql_error());
$lid=mysql_insert_id();
$notice="job";
}
header("location: admin.php?done=1");
?>
try the following lines
$ext = pathinfo($_FILES["file_name3"]["name"], PATHINFO_EXTENSION);
if($ext...)// your if else condition
{}
else
{}
Part 1 :
$valid_mime_types = array(
"image/gif",
"image/png",
"image/jpeg",
"image/pjpeg",
);
if (in_array($_FILES["file"]["type"], $valid_mime_types)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 2 :
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
$file_extension = strrchr($_FILES["file"]["name"], ".");
// Check that the uploaded file is actually an image
// and move it to the right folder if is.
if (in_array($file_extension, $valid_file_extensions)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 3 :
if (#getimagesize($_FILES["file"]["tmp_name"]) !== false) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
I am uploading multiple images from a single input and rename all uploaded files. My problem is; I need to display all uploaded images with separate variables
For example:
If user upload 3 images, i need to echo as
$upload1 = 1st file name
$upload2 = 2nd file name
$upload3 = 3rd file anme
No of images uploaded (upload number of file)
Here is my current code:
<?php
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
print_r($errors);
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key+1) . " = $row[0];";
eval ($codestr);
} else {
$codestr = '$file' . ($key+1) . " = NULL;";
eval ($codestr);
}
}
}
echo $file1;
echo $file2;
echo $file3;
echo $file4;
echo $file5;
?>
I tried this and I get the error
Parse error: syntax error, unexpected 'png' (T_STRING) in C:\Users\logon\Documents\NetBeansProjects\upload file rename single and multiple\multiple file rename\method 2\process.php(43) : eval()'d code on line 1
What am I doing wrong? can some one help me
I think the " = $row[0];" on line 42 might not do what you want it to do. Because of the double quotes, the value of the variable $row[0] will be printed in the code.
The code running through the eval will look something like this:
$file0 = FILENAME.png;
Instead of this:
$file0 = $row[0];
To solve the problem you could simply turn line 42 into the following:
$codestr = '$file' . ($key+1) . ' = $row[0];';
More information about the difference between single and double quotes: http://php.net/manual/en/language.types.string.php
Edit: For the correct names of the files you could change $_FILES['files']['name'][$key] to $file_name . $sExt. Hope it helps!