I found the below php file upload from the web and it worked fine till i designed a web application in angular 4 which a photo before being upload will have to be cropped. When the image is cropped, it saves the cropped image in a base64 format, now my problem is how i can configure my current php script to convert the base64 image to a real image
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(array('status' => false));
exit;
}
$path = '../myapp/img_folder/';
if (isset($_FILES['file'])) {
$originalName = $_FILES['file']['name'];
$ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION);
$generatedName = md5($_FILES['file']['tmp_name']).$ext;
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
echo json_encode(array(
'status' => true,
'originalName' => $originalName,
'generatedName' => $generatedName
));
}
}
else {
echo json_encode(
array('status' => false, 'msg' => 'No file uploaded.')
);
exit;
}
Here is the solution for your problem. Tested and Working Properly.
$encoded = "encoded---text---here===";
$file = fopen("mypicture.png", "w"); //(you can put jpg, png or any other extension)
fwrite($file, base64_decode($encoded));
fclose($file);
Related
I'm new to php and I can't seem to upload .docx files to the path specified.
It goes directly to invalid file type.
enter code here
if(!empty($_FILES["file"]["name"])) {
$allowed_types = ["application/msword"];
if(in_array($_FILES["file"]["type"], $allowed_types)) {
$input_name = "file";
$upload_path = "../finaid_organization/assets/documents";
$file_name = (!empty($_FILES[$input_name]["name"]) ? basename($_FILES[$input_name]["name"]) : "");
$file_name = "ld_".date("YmdHis").".".pathinfo($file_name)["extension"];
$path = $this->do_upload($input_name, $upload_path, $file_name);
$path = "/assets/documents/".$path;
$data += ["location_path" => $path];
$this->model_loan_doc->insert($data);
$ret = [
"success" => true,
"msg" => "<span class='fa fa-check'></span> Success"
];
} else {
$ret = [
"success" => false,
"msg" => "<span class='fa fa-warning'></span> Invalid file type"
];
}
}
You'd probably added a docx document, which you have to check with a different filetype
For docx check this MIME type:
application/vnd.openxmlformats-officedocument.wordprocessingml.document
so your array should be:
$allowed_types = ["application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
I'm creating a form where I've a place for attaching files. But, files with specific extensions like .xls, .sql etc., are not getting attached. But, other files like .docx, .pdf etc., are getting attached. This is how I tried:
function file_upload($control_id, $target_directory) {
if(isset_file($control_id)) {
if(file_exists($target_directory) == false) {
mkdir($target_directory, 0777, true); //to be create the directory recursively
}
$file_name = basename($_FILES[$control_id]["name"]); //to be get file name
write_log($file_name);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION); //to be get file extension
write_log($file_extension);
$file_size = $_FILES[$control_id]["size"]; //to be get file size in bytes
write_log($file_size);
$target_file_name = round(microtime(true) * 1000).".".$file_extension; //to be get target file name
$target_file_path = $target_directory.$target_file_name; //to be get target file
if(file_exists($target_file_path) == true) {
chmod($target_file_path, 0755); //Change the file permissions if allowed
unlink($target_file_path); //remove the file
}
if (move_uploaded_file($_FILES[$control_id]["tmp_name"], $target_file_path) == true) {
$arr = array(
"status" => true,
"message" => "The file ".$file_name." has been uploaded.",
"file_name" => $file_name,
"file_extension" => $file_extension,
"file_size" => $file_size,
"uploaded_file_name" => $target_file_name,
"uploaded_file_path" => $target_file_path
);
} else {
$arr = array(
"status" => false,
"message" => "Sorry, there was an error uploading your file."
);
}
} else {
$arr = array(
"status" => false,
"message" => "Please select file"
);
}
//echo json_encode($arr);
return $arr;
}
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["id"]));
$upload_directory = "uploads/attachments/";
$result = file_upload("contract_attachment", "../".$upload_directory);
if($result[status] == true) {
$query = "insert into `attachments`
(
`id`,
`file_name`,
`file_extension`,
`file_size`,
`uploaded_file_name`,
`uploaded_file_path`
)
values
(
'id',
'".addslashes($result['file_name'])."',
'".$result[file_extension]."',
'".$result[file_size]."',
'".$result[uploaded_file_name]."',
'".$upload_directory.$result[uploaded_file_name]."'
)";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
}
echo json_encode(array("message" => "Record submitted successfully"));
exit;
The problem is, when ever I try to attach a file with extension .xls or .sql, the $file_name, $file_extension, $file_size will get a value. For example, if the file I'm attaching is format.xls, it showed $file_name = format, $file_extension = .xls and $file_size = 0. Since the file size it's taking is zero, the condition "$result[status]" fails. So, the file is not getting attached.
If I attach files like .pdf or .docx I get the correct values. For example, if I attach file like format.pdf, it showed $file_name = format, $file_extension = .pdf, $file_size = 9824. And the file is also getting attached.
But, I don't know what's wrong with this code, since files with extensions .xls and .sql are not getting attached. Can someone correct this and tell whats wrong with this?
I'm using MashApe API to upload images to Imgur using PHP as follows:
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
$file_extension = strrchr($_FILES["file"]["name"], ".");
if (in_array($file_extension, $valid_file_extensions)) {
if (#getimagesize($_FILES["file"]["tmp_name"]) !== false) {
$filename = $_FILES['file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$response = Unirest\Request::post("https://imgur-apiv3.p.mashape.com/3/image",
array(
"X-Mashape-Key" => "key",
"Authorization" => "Client-ID ID",
"Content-Type" => "application/x-www-form-urlencoded"
),
array(
"image" => base64_encode($data)
)
);
var_dump(base64_encode($data));
$result = json_decode($response->raw_body);
if ($result->success) {
var_dump($result);
} else {
$Pointer->Bootstrap()->Alert($result->data->error, "danger");
}
}
}
but it always give me the following error: Image is corrupted or format is not supported.
If you downloaded a webm and changed the file type to gif when you saved it, the conversion is too corrupt for imgur. Try Cloudconvert until one of us figures out how to do it offline.
I recommend ShareX for automatic uploads to imgur.
Very new to this and have been trying to get it to work.
I have a bucket called app. I have followed the instructions to give my app permissions to the GCS (https://developers.google.com/appengine/docs/python/googlestorage/index#Prerequisites). It seems to be setup correctly.
I followed How do I upload images to the Google Cloud Storage from PHP form? which has worked for others. I haven't really diverted from it.
I get move_uploaded_file returning TRUE, but no file in GCS.
The output is "MoveResult did succeed".
Anyone see anything I am doing wrong. Am I missing some setup code or something?
Here is the code:
if(!is_uploaded_file($_FILES['file']['tmp_name'])) {
$profile_pic_path='default';
}
else { //file exists
$gs_name = $_FILES["file"]["tmp_name"];
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
$fileErrorMsg = $_FILES["file"]["error"];
$fileExt = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// change name if you want
$fileName = 'profile_pic.jpg';
// put to cloud storage
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
//file_put_contents("gs://app/".$fileName, $gs_name, 0, $ctx);
if(!move_uploaded_file($gs_name, 'gs://app/'.$fileName)){
echo json_encode(array('success' => 0,'error_message' => "MoveResult did not succeed"));
exit;
}
else{
//Get image key in or path or what not. THIS IS THE NEXT STEP
//$profile_pic_path=<something>;
echo json_encode(array('success' => 1,'info_message' => "MoveResult did succeed"));
exit;
}
}
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']);