I'm creating a function where users can upload multiple images and upload them to the server. Using a global variable for this matter works, but I've heard global variables are bad especially in OOP. So, I'm wondering what a good alternative would be? (I'm a starting PHP programmer, any detailed information is appreciated)
Code:
function addImgToNieuws($images){
if (isset($images) && $images != "") {
$countFiles = count($images["name"]);
for ($i = 0; $i < $countFiles; $i++) {
$fileName = $images["name"][$i];
$fileType = $images["type"][$i];
$fileSize = $images["size"][$i];
$fileError = $images["error"][$i];
$fileTmp = $images["tmp_name"][$i];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = rand(100000, 999999) . "." . $fileExt;
$output = $this->db->real_escape_string($db_file_name);
global $string;
$string .= ",$output";
$string = substr($string, 1);
}
echo $string;
}
}
function addImgToNieuws($images){
if (isset($images) && $images != "") {
throw new Exception("bad input bro");
}
$countFiles = count($images["name"]);
$db_names = array();
for ($i = 0; $i < $countFiles; $i++) {
$fileName = $images["name"][$i];
$fileType = $images["type"][$i];
$fileSize = $images["size"][$i];
$fileError = $images["error"][$i];
$fileTmp = $images["tmp_name"][$i];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = rand(100000, 999999) . "." . $fileExt;
$db_names[] = $this->db->real_escape_string($db_file_name)
}
return $db_names;
}
Assuming you wanted to get the $db_names. It's a little bit odd to do the escaping here, I would delay it until the very moment you insert it in the query.
If you really wanted the $db_names as a string you can do:
echo join(",", $obj->addImgToNieuws($images));
Related
I have a short PHP code to help me display random images from a specific folder. But now it seems to select any image in any size. I want those selected images are between 100-500 kb. If it's less than 100 kb or over 500 kb, the function won't select and display it.
Could you please tell me how to modify this code? Probably need to add some function.
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1);
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>
Try this one We have to set 2 conditions
$min = 100; //KB
$max = 500; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}
Try now
<?php
$dir_name = 'images/random/';
$pattern="/(gif|jpg|jpeg|png)/";
$min = 100;
$max = 500;
$imagearray = array();
$scanned_directory = array_diff(scandir($dir_name), array('..', '.'));
$count = count($scanned_directory);
$ids = array_keys($scanned_directory);
$s = TRUE;
$stop = $count;
while( ($s === TRUE) && ($stop >=0))
{
$random = mt_rand(0, $count - 1);
$full_path_to_file = $dir_name.$scanned_directory[$ids[$random]];
$ext = pathinfo($full_path_to_file, PATHINFO_EXTENSION);
$file_size_kb = round(filesize($full_path_to_file)/1024);
if (preg_match($pattern, $ext) && ($file_size_kb>=$min && $file_size_kb<=$max))
{
$s = FALSE;
echo '<img src="'.$full_path_to_file.'" alt />';
}
$stop--;
}
?>
I have 2 separate PHP functions to post form data and upload images. I want to combine both functions so I can have data and upload images in the same form.
1.
public function PostStep2()
{
$user = $this->check_profile();
$id = $user['id'];
if ($_POST)
{
$_POST['profile'] = '1';
$this->model->_update('user_details', $_POST, array("id"=>$id));
redirect('ProfileStep3');
}
else
{
err('Something wrong');
}
}
2.
public function PostStep3()
{
$user = $this->check_profile();
$id = $user['id'];
$upload = false;
for ($i=0; $i < 5; $i++)
{
$file_name = md5(date('YmdHms')).basename($_FILES['img']['name'][$i]);
$path = dirname(__FILE__);
$new_path = strrpos($path, "controller");
$new_path = substr($path, 0,$new_path-1);
// $path = $new_path.UPLOAD.'files/'.$file_name;
$path = $new_path.'/resources/uploads/files/'.$file_name;
$fileName = strtolower($_FILES['img']['name'][$i]);
$allowedExts = array('jpg','JPG','jpeg','JPEG','png','PNG');
$extension = explode(".", $fileName);
$extension = end($extension);
if(in_array($extension, $allowedExts))
{
Make a single file that the form will submit to.
<form action='seperatefile.php' method='post'>
Seperatefile.php, paste all of the functions and uploading parameters.
Can someone tell me why this php code doesn't work? It doesn't chek if file_exists, but it just run the code. Sorry for my bad (grammer) english, english is not my main langue :).
$files = glob("../templates/Default/*");
for ($i=0; $i<count($files); $i++) {
$src = $files[$i];
$fileName = $src;
$fileName = str_replace("../templates/Default/", "", $fileName);
$dirName = $fileName;
$dest = "../Sites/NewSite1/$fileName";
if(file_exists($fileName)){
copy($src, $dest);
echo $fileName;
}else{
$fileName = "../templates/Default/$dirName";
$fileName = str_replace("$dirName", "$dirName/*", $fileName);
$dFiles = glob($fileName);
for ($t=0; $t<count($dFiles); $t++) {
$src2 = $dFiles[$t];
copy($src2, $dest);
echo $src2;
}
}
}
if you want to check whether the file exists in the directory where you are trying to copy it to, then you need to provide file_exists() with the entire directory path, therefore do the following:
change this: if (file_exists($fileName)) {
to this: if (file_exists($dest)) {
Here is the right code: (it still need some tweeking).
$files = glob("../templates/Default/*");
for ($i=0; $i<count($files); $i++) {
$src = $files[$i];
$fileName = $src;
$fileName2 = str_replace("../templates/Default/", "", $fileName);
$dirName = $fileName2;
$dest = "../Sites/$websiteName/$fileName2";
if (!copy($src, $dest)) {
$fileName3 = "../templates/Default/$dirName/*";
$dest2 = "../Sites/$websiteName/$fileName2";
$dFiles = glob($fileName3);
for ($t=0; $t<count($dFiles); $t++) {
$src2 = $dFiles[$t];
$fileName4 = $src2;
$fileName4 = str_replace("../templates/Default/$dirName/", "", $fileName4);
mkdir("../Sites/$websiteName/$dirName");
$dest2 = "../Sites/$websiteName/$dirName/$fileName4";
copy($src2, $dest2);
}
}
}
If I submit a form with multiple files in it, how can I upload each of them after some kind of execution one by one?
Add something like this to your PHP page
//upload image 1
if ($filename1<>"") {
$filename = $filename1;
$file = 'file1';
$temp = explode(".", $_FILES["file1"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image1 = '$newfilename' where yachtid = '$yachtid'");
}
//upload image 2
if ($filename2<>"") {
$filename = $filename2;
$file = 'file2';
$temp = explode(".", $_FILES["file2"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image2 = '$newfilename' where yachtid = '$yachtid'");
}
And then the file called "upload_file.php should look something like this (change the validation sections if you want it to validate on different file names). Also, this renames the file to a random name before saving it to your location);
<?php
$length = 30;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$code = "";
for ($p = 0; $p < $length; $p++) {
$pos = mt_rand(0, strlen($characters)-1);
$code .= $characters{$pos};
}
$parts = explode('.',$filename);
$extension= end($parts);
$newfilename=$code .".".$extension;
$success = 0;
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end($temp);
if ((($_FILES[$file]["type"] == "image/gif") || ($_FILES[$file]["type"] == "image/jpeg") || ($_FILES[$file]["type"] == "image/jpg")
|| ($_FILES[$file]["type"] == "image/pjpeg") || ($_FILES[$file]["type"] == "image/x-png") || ($_FILES[$file]["type"] == "image/png"))
&& ($_FILES[$file]["size"] < 1000000) && in_array($extension, $allowedExts)) {
$filenamepng = "./images/yacht/".$code.".png";
$filenamegif = "./images/yacht/".$code.".gif";
$filenamejpeg = "./images/yacht/".$code.".jpeg";
$filenamejpg = "./images/yacht/".$code.".jpg";
$filenamepjpeg = "./images/yacht/".$code.".pjpeg";
$filenamexpng = "./images/yacht/".$code.".x-png";
if (file_exists($filenamepng)||file_exists($filenamegif)||file_exists($filenamejpeg)||file_exists($filenamejpg)||file_exists($filenamepjpeg)||file_exists($filenamexpng)) {
if (file_exists($filenamepng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.png';
unlink($filename);
}
if (file_exists($filenamegif)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.gif';
unlink($filename);
}
if (file_exists($filenamejpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpeg';
unlink($filename);
}
if (file_exists($filenamejpg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpg';
unlink($filename);
}
if (file_exists($filenamepjpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.pjpeg';
unlink($filename);
}
if (file_exists($filenamexpng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.x-png';
unlink($filename);
}
}
move_uploaded_file($_FILES[$file]["tmp_name"],
"images/yacht/" . $newfilename);
//echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
unset($code);
$success = 1;
}
else
{
$error = "Your image is over 1mb OR is not in an accepted format; gif, jpeg, jpg, pjpeg, x-png, or png. Please try again.";
}
?>
www.clubtray.com
www.clubtray-clubmembershipsoftware.com
I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!
PHP
$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$actual_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Here's a minor modification that I think should do what you want:
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Inspired from #Jason answer, i created a function which i deemed shorter and more readable filename format.
function newName($path, $filename) {
$res = "$path/$filename";
if (!file_exists($res)) return $res;
$fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Example:
$name = "foo.bar";
$path = 'C:/Users/hp/Desktop/ikreports';
for ($i=1; $i<=10; $i++) {
$newName = newName($path, $name);
file_put_contents($newName, 'asdf');
}
New version (2022):
function newName2($fullpath) {
$path = dirname($fullpath);
if (!file_exists($fullpath)) return $fullpath;
$fnameNoExt = pathinfo($fullpath,PATHINFO_FILENAME);
$ext = pathinfo($fullpath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Usage:
for ($i=1; $i<=10; $i++) {
$newName = newName2($fullpath);
file_put_contents($newName, 'asdf');
}
There are several ways for renaming image in PHP before uploading to the server.
appending timestamp, unique id, image dimensions plus random number etc.You can see them all here
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
function rename_appending_unique_id($source, $tempfile){
$target_path ='uploads-unique-id/'.$source;
while(file_exists($target_path)){
$fileName = uniqid().'-'.$source;
$target_path = ('uploads-unique-id/'.$fileName);
}
move_uploaded_file($tempfile, $target_path);
}
if(isset($_FILES['upload']['name'])){
$sourcefile= $_FILES['upload']['name'];
tempfile= $_FILES['upload']['tmp_name'];
rename_appending_unique_id($sourcefile, $tempfile);
}
Check more image renaming tactics
I checked SO and found a nice C# answer here, so I ported it for PHP:
['extension' => $extension] = pathinfo($filePath);
$count = 0;
while (file_exists($filePath) === true) {
if ($count === 0) {
$filePath = str_replace($extension, '[' . ++$count . ']' . ".$extension", $filePath);
} else {
$filePath = str_replace("[$count].$extension", '[' . ++$count . ']' . ".$extension", $filePath);
}
}