move uploaded file success but could not find file in folder - php

I have the following code
public function upload() {
if($_FILES){
$this->load->model('account/customer');
$file = $_FILES['profile'];
$file_name = $file['name'];
// $ext = end(explode('.', $file_name));
// $file_name = 'na_'.md5(time()).'.'.$ext;
echo $file_content = $file['tmp_name'];
$data = array('customer_id' => $this->customer->getId(), 'img_url' => $file['name']);
$this->model_account_customer->profileImage($data);
echo 'test/'.$file_name;
$img = move_uploaded_file($file['tmp_name'], 'test/'.$file['name']);
if($img) {
$return = json_encode(array('status' => 1));
} else {
$return = json_encode(array('status' => 0));
}
echo $return;
}
}
The above code returning status as 1 but could not see the file in folder.
I check folder permission is 0777

Try appending a / in front of the path
move_uploaded_file($file['tmp_name'], '/test/'.$file['name']);

Related

[PHP][SLIM] move_uploaded_file never ends with larger files in Hosting24

I have a question.
I'm trying to upload files to a server, this server is hosted by 'Hosting24', i don't know if that matters, anyway, if I try to move files larger than 70mb It never ends to load and never send a response, my server config is okay, it has these values: {"post_max_size":"512M","memory_limit":"1024M"}
I has tryed with $_FILES and ftp transfer and it doesnt works, it never ends of load.
I'm using Slim framework and this is the function:
public function testCode($request, $response, $args)
{
$data = $request->getParsedBody();
$uploadedFiles = $request->getUploadedFiles();
//here take files
$uploadedFile = $uploadedFiles['file_user'];
$nameC = $data['nombre_curso'];
//here set path
$path = "../../scorm/temp/" . $nameC . '/';
//Creating folders
if (!#mkdir($path, 0777, true)) {
$error = error_get_last();
echo $error['message'];
}
$file_name = $uploadedFile->getClientFilename();
$array = explode(".", $file_name);
$ext = $array[1];
//if is a zip file
if ($ext == 'zip') {
$location = $path . "/" . $file_name;
//here move the uploaded file to my selected directory
if (move_uploaded_file($uploadedFile->file, $location)) {
$obj = (object) array("response" => 'works', 'post_max_size' => ini_get('post_max_size'), 'memory_limit' => ini_get('memory_limit'));
$response->withStatus(200);
$response->getBody()->write(json_encode($obj));
return $response;
} else {
$error = error_get_last();
echo $error['message'] . " it couldn't be moved";
}
} else {
echo "no zip";
}
}

How to get parameter of ng2-file-upload with endback?

I want to get parameter with php. I try with my code but it still not work save into folder (parameter) this is post http image:
Ionic framework
this.uploader.onBeforeUploadItem = (item: any) => {
this..uploader.options.additionalParameter = {
folder : this.herb_id <---- my parameter folder name
};
endback(php)
<?php
header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'POST');
header('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Content-Description,X-Requested-With');
header('Access-Control-Allow-Credentials', true);
if (isset($_FILES['file'])) {
/------------- folder name --------------------------//
$path = 'uploads/';
$path .=$_FILES['options']['additionalParameter']['folder']; <---- folder name
$path .= '/';
$originalName = $_FILES['file']['name'];
$ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION);
$generatedName = md5($_FILES['file']['tmp_name']).$ext;
//$filePath = $path.$generatedName;
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
i can solve it as this code
for ionic
this.fileField.uploader.onBuildItemForm = (fileItem, form) => {
form.append('folder', String(this.herb_id));
return { fileItem, form };
};
for php
/------------- folder name --------------------------//
$path = 'uploads/';
$path .=$_POST['folder']; <---- folder name
$path .= '/';

file not found exception in laravel

I am facing some problem while uploading image in laravel framework of my project .I checked image is uploading to folder , but still this error is coming
Below is coding
/////////// Course Image ///////////
$tmp_name1 = $course_image['tmp_name'];
$type1 = $course_image['type'];
$name1 = $course_image['name'];
$res1 = $this->upload_file($tmp_name1, $name1);
if ($res1) {
$course_image_url = $res1;
} else {
$course_image_url = "";
}
function upload_file($source, $name) {
$list = explode(".", $name);
$ext = $list[count($list) - 1];
$ext = strtolower($ext);
if (in_array($ext, $this->file_extension)) {
$filename = md5(date("YmdHis") . microtime() . rand(100, 100000000)) . "." . $ext;
$destination = "public/uploads/" . $filename;
$res = move_uploaded_file($source, $destination);
if ($res) {
return $destination = "uploads/" . $filename;
} else {
$message = "Internal server error";
(json_encode(array("responseCode" => "500", "responseMsg" => array("status" => "error", "statusReason" => $message))));
}
} else {
$message = "Invalid file extention";
(json_encode(array("responseCode" => "500", "responseMsg" => array("status" => "error", "statusReason" => $message))));
}
}
There are lots of codes , I posted only the required one .
You should follow the Laravel Example for Uploading Files.
I.e., you can check if a file has been uploaded successfully using:
if ($request->hasFile('image')) {
//
}
And you can move / rename a file using:
$request->file('image')->move($destinationPath);
or
$request->file('image')->move($destinationPath, $fileName);
I found that issue .
Go to line number 66 of this path(D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Http\UploadedFile.php) in your project folder .or search the text instanceof static.
After it remove the "instanceof static" ,then it is working fine.
Thanx

Check if file (multiple extension possible ) exists?

I got ascript which helps me to add some data into a csv file, based on the fact if a image is inside a folder or not (exits or not). Files are images, so I need to check if the file exists, and if it is a png, jpg, jpeg, gif.
So far it only check if it a JPG but I would like it to find the file exists if it's a PNG or JPEG or even GIF.
<?php
$columns = array("row1","row2","row3","row4","row5","row6","row7","row8","row9",
"row10","row11","row12","row13","row14","row15","row16","row17","row18"
);
$rootDir = "/path/to/images/folder/files";
$file = fopen("database.csv", "r") or die('fopen database failed');
$newFile = fopen("newdata.csv", "w") or die('fopen newdata.csv failed');
while (($data = fgetcsv($file, 999999, ";")) !== FALSE) {
$row = array_combine($columns, $data);
$filename = $row['row4'].".jpg"; // could be png or jpEg, or even gif
if (file_exists("$rootDir/$filename")) {
$row['image'] = .$filename; //also needs correct extension of image which exists.
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
}
fputcsv($newFile, array_values($row), ";",'"' );
}
fclose($file);
fclose($newFile);
?>
You can do something like this:
// your code
$possible_extensions = array("jpg", "jpeg", "png", "gif");
$row = array_combine($columns, $data);
foreach($possible_extensions as $ext){
$filename = $row['row4'] . "." . $ext;
if (file_exists("$rootDir/$filename")) {
$row['image'] = .$filename;
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
break;
}
}
fputcsv($newFile, array_values($row), ";",'"' );
// your code
Edited:
If you want to perform case-insensitive file_exists() check then here's the solution,
The following fileExists() function returns the full path file if found, and false if not.
function fileExists($fileName, $caseSensitive = true) {
if(file_exists($fileName)) {
return $fileName;
}
if($caseSensitive) return false;
// Handle case insensitive requests
$directoryName = dirname($fileName);
$fileArray = glob($directoryName . '/*', GLOB_NOSORT);
$fileNameLowerCase = strtolower($fileName);
foreach($fileArray as $file) {
if(strtolower($file) == $fileNameLowerCase) {
return $file;
}
}
return false;
}
Here's the source:
PHP Case Insensitive Version of file_exists()
And now your code,
// your code
$possible_extensions = array("jpg", "jpeg", "png", "gif");
$row = array_combine($columns, $data);
foreach($possible_extensions as $ext){
$filename = $row['row4'] . "." . $ext;
if ($filename = fileExists("$rootDir/$filename", false)) {
$row['image'] = .$filename; //also needs correct extension of image which exists.
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
break;
}
}
fputcsv($newFile, array_values($row), ";",'"' );
// your code

How can I upload a file to amazon S3 with Codeigniter/PHP?

I'm trying to upload a file to my Amazon S3 bucket. My friend had this working on our site in the past but a year later its busted and I can't figure out what's wrong. We are using the S3 PHP library developed by Geoff gaudreault.
This library looks pretty straightforward to me, really it looks like there is one key function: putObject().
Unfortunately, I'm not even getting out of the gate. I'm getting the following error message:
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
Here's my codeigniter PHP for my upload form action:
function s3(){
$config['upload_path'] = $_SERVER["DOCUMENT_ROOT"].'/temp/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '1024000';
$config['max_height'] = '768000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
echo 'failure';
}
else
{
$data = array('upload_data' => $this->upload->data());
$fn = $data['file_name'];
$type = substr($fn, strrpos($fn, '.') + 1);
$this->load->library('s3');
$temp_file_path = $_SERVER["DOCUMENT_ROOT"]."/temp/" . $data['file_name'];
$contents = read_file($temp_file_path); // will this blow up or timeout for large files?!
$newFileName = uniqid().".".substr($temp_file_path, strrpos($temp_file_path, '.') + 1);
$contentPath = "mysite.com/Images";
$this->s3->putObject($newFileName, $contents, $contentPath, 'private', $type);
echo 'success';
}
}
Does anyone have any thoughts?
I switched to a different S3 PHP library, which is also referred to as S3.php, that is part of this really nice Netuts tutorial source code.
Just plugging in my AWS keys and bucket name into the demo's page.php file, I was able to upload to my bucket in like 2 minutes. So this tutorial is super easy. Very exciting!
in codeigniter
Here link to upload and delete image in s3 bucket
<?php
function profile_upload()
{
//print_r($_FILES);
if ($this->session->userdata('user_login')) {
$file = $_FILES['agent_profile_file']['tmp_name'];
if (file_exists($file)) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$typefile = explode(".", $_FILES["agent_profile_file"]["name"]);
$extension = end($typefile);
if (!in_array(strtolower($extension), $allowedExts)) {
//not image
$data['message'] = "images";
} else {
$userid = $this->session->userdata['user_login']['userid'];
$full_path = "agent_image/" . $userid . "/profileImg/";
/*if(!is_dir($full_path)){
mkdir($full_path, 0777, true);
}*/
$path = $_FILES['agent_profile_file']['tmp_name'];
$image_name = $full_path . preg_replace("/[^a-z0-9\._]+/", "-", strtolower(uniqid() . $_FILES['agent_profile_file']['name']));
//move_uploaded_file($path,$image_name);
$data['message'] = "sucess";
$s3_bucket = s3_bucket_upload($path, $image_name);
if ($s3_bucket['message'] == "sucess") {
$data['imagename'] = $s3_bucket['imagepath'];
$data['imagepath'] = $s3_bucket['imagename'];
}
//print_r($imagesizedata);
//image
//use $imagesizedata to get extra info
}
} else {
//not file
$data['message'] = "images";
}
} else {
$data['message'] = "login";
}
echo json_encode($data);
//$file_name2 = preg_replace("/ /", "-", $file_name);
}
// Helper file add code
// image compress code
function compress($source, $destination, $quality)
{
ob_start();
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
$filename = tempnam(sys_get_temp_dir(), "beyondbroker");
imagejpeg($image, $filename, $quality);
//ob_get_contents();
$imagedata = ob_end_clean();
return $filename;
}
// type for if image then it will reduce size
// site for it in web of mobile because mobile webservice image will in base 64
// $tempth will file temp path
// $image_path will file where to save path
function s3_bucket_upload($temppath, $image_path, $type = "image", $site = "web")
{
$bucket = "bucket-name";
$data = array();
$data['message'] = "false";
// For website only
if ($site == "web") {
if ($type == "image") {
$file_Path = compress($temppath, $image_path, 90);
} else {
$file_Path = $temppath;
}
}
try {
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'us-west-2',
'credentials' => [
'key' => 'aws-key',
'secret' => 'aws-secretkey',
],
]);
// For website only
if ($site == "web") {
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $image_path,
'SourceFile' => $file_Path,
//'body'=> $file_Path,
'ACL' => 'public-read',
//'StorageClass' => 'REDUCED_REDUNDANCY',
]);
$data['message'] = "sucess";
$data['imagename'] = $image_path;
$data['imagepath'] = $result['ObjectURL'];
} else {
// $tmp = base64_decode($base64);
$upload = $s3Client->upload($bucket, $image_path, $temppath, 'public-read');
$data['message'] = "sucess";
$data['imagepath'] = $upload->get('ObjectURL');
}
} catch (Exception $e) {
$data['message'] = "false";
// echo $e->getMessage() . "\n";
}
return $data;
}

Categories