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.
Related
I use this Simple upload and resize image on PHP project to do my project.
https://gist.github.com/zeuxisoo/910107/483c7b6082dcc484d7b4cee21aad12650c53e416
but I don't know how to rename the file after upload.
I want to rename file and upload it into server as well as in database. The follow is code:
public function run() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
I use a lot of method , eg basename
It can't to it, any idea?? Thanks
You can do this
public function run() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
$tempName = explode(".", $this->files['name'][$i]);
$newName = "IMAGE_NAME"; //generate unique string to avoid conflict
$newfilename = $newName . '.' . end($tempName );
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$newfilename) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
In $newName you can generate new name for your file.
Update
To avoid conflict use unique string each time when you generate the name.
Instead of using move_uploaded_file use it as per code example given below.
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Here is your solution
public function run(){
$total = count($this->files);
for($i=0; $i<$total; $i++){
if(empty($this->files['name'][$i]) === false){
$ext = substr(strtolower(strrchr($this->files['name'][$i], '.')), 1); //get the extension
$new_name = 'new-name'.date('dmY').$ext;
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$new_name) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
I would like to upload some files to my server. So far, they have been successfully stored in a MySQL database, but the problem is that the uploaded file is not found in a folder that is located on the server.
Here's my code:
$dir = $filename;
$target_dir = "file/$dir/";
if( is_dir($target_dir) === false )
{
mkdir($target_dir);
}
if(isset($_POST["submit"])) {
$formatfile = array('pdf');
$filetest= $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence= strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if(in_array($existence, $formatfile) === true){
if($pdfsize < 1044070){
move_uploaded_file($file_tmp, "$target_dir.$filetest");
}
}
}
$sql = "INSERT INTO test (filename) VALUES ('$filetest')";
Is there anything I missed?
Please change $formatfile = array('pdf') to $formatfile = array('.pdf'=>'application/pdf');
$dir = $filename; Whis is vlaue of $filename ?
please use like this.
$dir = '/var/www/uploads/';
if(in_array($existence, $formatfile)){
if($pdfsize < 1044070){
move_uploaded_file($file_tmp, "$target_dir.$filetest");
}
}
}
whenever you are uploading a file.try the full path.
<?php
$dir = $filename;
$target_dir = dirname(__FILE__).'/file/'.$dir.'/';
if (is_dir($target_dir) === false) {
mkdir($target_dir);
}
if (isset($_POST['submit'])) {
$formatfile = array('pdf');
$filetest = $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence = strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if (in_array($existence, $formatfile) === true) {
if ($pdfsize < 1044070) {
move_uploaded_file($file_tmp, $target_dir.$filetest);
}
}
}
$sql = 'INSERT INTO test (filename) VALUES ('.$filetest.')';
$dir = $filename;
$target_dir = "file/$dir/";
if( is_dir($target_dir) === false )
{
mkdir($target_dir);
}
if(isset($_POST["submit"])) {
$formatfile = array('pdf');
$filetest= $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence= strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if(in_array($existence, $formatfile) === true){
if($pdfsize < 1044070){
//Remove ""
move_uploaded_file($file_tmp, $target_dir.$filetest);
//If file upload then and then execute query.
$sql = "INSERT INTO test (filename) VALUES ('$filetest')";
}else{
//Fire error
}
}else{
//Fire error
}
}else{
//Fire error
}
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));
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);
}
}
Here is the normal php function which is used in codeigniter which uploads the picture from an android device. I want someone to help to convert into codeigniter function to make it work.
private function uploadImages(){
//get the data from the $_POST and $_FILES
$postKeyPairs = $_POST;
$files = $_FILES['files'];
$titles = "";$description = "";
//fetch the titles
if(array_key_exists('title',$postKeyPairs)){
$titles = $postKeyPairs['title'];
}
//get the description
if(array_key_exists('description',$postKeyPairs)){
$description = $postKeyPairs['description'];
}
//the root file path for the uploaded images
$file_path = "uploads/";
//count the number of files to upload
for($i = 0; $i < count($files['name']); $i++){
//make sure the filename is unique
$filename = basename($files['name'][$i]);
//get the proper filepath for the individual files
$file_path = $file_path.$filename;
//get the title for the current image
if(isset($titles[$i]) && $titles[$i] != null){
$imageTitle = $titles[$i];
}
else{
$imageTitle = "NA";
}
//and get the image description
if(isset($description[$i]) && $description[$i] != null){
$imageDescp = $description[$i];
}
else{
$imageDescp = "NA";
}
//upload the file into the file system
if(!move_uploaded_file($files['tmp_name'][$i], $file_path)){
//any exception occurs
throw new Exception("Couldn't upload image ".$files['name'][$i]);
}
}
return true;
}