I am using a php script to upload images to a directory.
I am trying to figure out why the script is not giving the images a unique filename before saving them in the directory. I am only uploading one image at a time and I have included the relevant piece of php here which I thought would create unique filenames. Can anyone tell me why the images are not getting unique names?
//proportionally resize image
private function resize_it(){
if($this->file_count > 0){
if(!is_array($this->file_data['name'])){
throw new Exception('HTML file input field must be in array format!');
}
for ($x = 0; $x < $this->file_count; $x++){
if ($this->file_data['error'][$x] > 0) {
$this->upload_error_no = $this->file_data['error'][$x];
throw new Exception($this->get_upload_error());
}
if(is_uploaded_file($this->file_data['tmp_name'][$x])){
$this->curr_tmp_name = $this->file_data['tmp_name'][$x];
$this->get_image_info();
//create unique file name
if($this->random_file_name){
$this->new_file_name = uniqid().$this->get_extension();
$this->unique_rnd_name[$x] = $this->new_file_name;
}else{
$this->new_file_name = $this->file_data['name'][$x];
}
$this->curr_tmp_name = $this->file_data['tmp_name'][$x];
$this->image_res = $this->get_image_resource();
$this->save_dir = $this->destination_dir;
Related
i am trying to do an update using dynamic for "education history" but there is an image also, i use eloquent to update too, for some reason the data is saved in the database but the image just tmp and cannot find in the folder.
//count array data inputed
for($incs=0; $incs < count($data_detail_user['institution_names']); $incs++) {
// update education
foreach( $data_detail_user['institution_names'] as $key => $file ){
// get old photo thumbnail
$get_photo = Educations::where('id', $key)->first();
// store photo
$path = $file->store(
'assets/education/thumbnail', 'public'
);
$education_user = Educations::find($incs);
$education_user->detail_user_id = $detail_user['id'];
$education_user->name = $data_detail_user['institution_names'][$incs];
$education_user->course = $data_detail_user['education_courses'][$incs];
$education_user->start = $data_detail_user['education_starts'][$incs];
$education_user->graduate = $data_detail_user['education_graduates'][$incs];
$education_user->address = $data_detail_user['education_addresses'][$incs];
$education_user->regencies = $data_detail_user['education_regencies'][$incs];
$education_user->provinces = $data_detail_user['education_provinces'][$incs];
$education_user->country = $data_detail_user['education_countries'][$incs];
$education_user->zip_code = $data_detail_user['education_zips'][$incs];
$education_user->certificate = $data_detail_user['education_certificates'][$incs][$path];
$education_user->save();
$data_detail_user = 'storage/' .$get_photo['certificate'];
if (File::exists($data_detail_user)) {
File::delete($data_detail_user);
} else {
File::delete('storage/app/public/' .$get_photo['certificate']);
}
}
}
[the error show Call to a member function store() on string]
this is the screenshoot of the error
[1]: https://i.stack.imgur.com/l96sm.png
$path = $request->file('path')->store('public/post');
I assume you have a directory where the image is suppose to be stored that's why i created the post directory after public.
I am having issues getting an image into my PDF. I have a form, and on it I have two upload fields. The user can upload a PDF, or an image. When the file is uploaded, it is saved in my temp folder without an extension. I pass my class two things: $fileData, which is the url to the file, and inputArray which is an array of other data from the form (name, address, etc).
My code is like so
private $tplidx;
public function __construct($fileData, $inputArray) {
$pdf = new \FPDI();
$count = 10;
$pdf->AddPage('P');
$pdf->SetFontSize(20);
foreach($inputArray as $input) {
$pdf->SetXY(50, $count);
$pdf->Write(1, $input);
$count = $count + 10;
}
foreach($fileData as $name => $extension){
if($extension == "application/pdf") {
$pagecount = $pdf->setSourceFile($name);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$this->tplidx = $pdf->importPage($i+1);
$pdf->useTemplate($this->tplidx, 10, 10, 200);
}
} else {
$pdf->AddPage();
$filetype = explode("/",$extension);
$pdf->Image($name.'.'.$filetype[1],30,120,25);
}
}
$pdf->Output('test.pdf', 'F');
}
The first foreach adds the inputs from the field to a page, this works fine.
The next foreach next checks if its a pdf, and if it is, it adds it to another page in the PDF. This also works fine.
My problem is in the else, because I am appending the files extension, I get the error
Can't open image file
If I remove the extension part, I get the error
Image file has no extension and no type was specified
Is there any way to solve this issue?
Thanks
You can pass the image type in the $type parameter of the Image() method.
I have image upload form on the site which allow users to upload their images. Now I'm trying to secure it as much as possible. Using php_image_magician..
This is what I have where I check images ( part of code )
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
$tempFile = $_FILES["user_files"]["tmp_name"][$i];
$getImgSize = getimagesize($tempFile);
// if valid image type then upload
if (in_array($image_mime, $valid_image_check, $getImgSize)) {
....
// upload image
}
Whit image_type_to_mime_type there is no problems. Now I have added this lines for getimagesize but I got error in here if (in_array($image_mime, $valid_image_check, $getImgSize)) - Warning: in_array() expects parameter 3 to be boolean, array given in. Parameter 3 is $getImgSize
$tempFile = $_FILES["user_files"]["tmp_name"][$i];
$getImgSize = getimagesize($tempFile);
var_dump($_FILES["user_files"]["tmp_name"][$i]) return string(14) "/tmp/phpkBZOW3"
The form is accepting more than one image so that's why is for there and [$i]. What can be the problem here?
You can try like this. But as #Paul said check the documentation.
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
$getImageFile = getimagesize($_FILES["user_files"]["tmp_name"][$i]);
if(!empty($getImageFile)){
echo 'Please ensure you are uploading an image.';
exit;
}
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
I want to get a random background image using php. Thats done easy (Source):
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
Lets optimize it to choose all background-images possible inside a folder:
function randImage($path)
{
if (is_dir($path))
{
$folder = glob($path); // will grab every files in the current directory
$arrayImage = array(); // create an empty array
// read throught all files
foreach ($folder as $img)
{
// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
}
return($arrayImage); // return every images back as an array
}
else
{
return('Undefine folder.');
}
}
$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:
$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);
When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:
http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"
Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?
You'll want to change
$myRandBkgd = "$bkgd[$i]";
to
$myRandBkgd = $bkgd[$i];
If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.
So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help