Rename an image during the uploading in php - php

Am trying to rename an image during upload i know i am met to put the function rand() and end() but i just do not know where to put it here is my code below
php / html section
if (isset($_POST['uploadimage'])) {
list($typed) = $_FILES['images']['type'];
if(!ereg("image",$typed)){
echo "<div class='msg1'>File is not an image or field is empty</div>";
}else{
$pixsname = $_FILES['images']['name'];
while(list($key,$value) = each($_FILES['images']['name'])){
if(!empty($value)) {
$pixsname = $value;
$add = "./img/venues/$pixsname";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
}
$image = new Image();
$image->load("$add");
$image->resize(652,300);
$image->save("$add");
}
echo "<div class='msg1'>Image profile has been updated</div>";
}
}
form method="post" enctype="multipart/form-data" id="loginform" >
<input type="hidden" name="MAX_FILE_SIZE" value="200000000">
<input type="file" name="images[]" id="fileField" class="field_ss"/>
<?php echo $pix; ?>
<input type="submit" name="uploadimage" value="Upload Image"/>
</form>

Replace
$pixsname = $value;
with
$pixsname = 'The_New_Name_Of_Your_Picture';

Related

Upload multiple files with a php script

I've been modify this php script but it won't work, it always fail. It managed to create the folder, but it fails to move the files from the temporary folder to the right one, the function move_uploaded_file return always false. This is the code:
<?php
include 'connection.php';
include '../empty.html';
session_start();
if(isset($_FILES['filearray'])){
$name_array = $_FILES['filearray']['name'];
$tmp_name_array = $_FILES['filearray']['tmp_name'];
$type_array = $_FILES['filearray']['type'];
$size_array = $_FILES['filearray']['size'];
$error_array = $_FILES['filearray']['error'];
$titlealbum=$_POST['titoloalbum'];
$username=$_SESSION['username'];
$path="../users/".$username."/".$titlealbum."/";
echo $path;
mkdir($path,0777);
$total=count($tmp_name_array);
for($i=0; $i<$total; $i++){
$rightpath=$path.$name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $rightpath)){
echo $name_array[$i]." upload is complete<br>";
echo "upload completato";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]." into".$path."<br>";
}
}
}
else
echo "Files not found";
?>
This is the html form:
<form id="albumform" style="display:none" enctype="multipart/form-data" action="scripts/albumupload.php" multiple="multiple" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000">
Name: <input name="titoloalbum" type="text" required><br><br>
Cover: <input name="userfile" type="file">
<br><br>Select your songs:<br />
<input name="filearray[]" type="file" value="10000000" /><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input type="submit" value="Send files" />
</form>
I know that this form kinda sucks, but i don't like the multiple selection with a signle "input". Thanks in advice
You have error in your code :
$total=count($tmp_name_array);
change this to
$total=count($name_array);
You are using count function with wrong variable.
Also remove so many file types with same name from the form. Either name them different.
<input name="filearray[]" type="file" value="10000000"/><br />
You could use the following commented algorithm for Multiple-Files upload:
PHP
<?php
// FILENAME: albumupload.php
include 'connection.php';
include '../empty.html';
session_start();
$filesArray = isset( $_FILES['filesArray'] ) ? $_FILES['filesArray'] : null;
$titleAlbum = isset($_POST['titoloalbum']) ? isset($_POST['titoloalbum']) : null;
$arrFilesData = array();
if( $filesArray && !empty($filesArray) ){
$arrFilesKeys = array_keys($filesArray['name']);
$arrFilesNames = $filesArray['name'];
$arrFilesTypes = $filesArray['type'];
$arrFilesTmpNames = $filesArray['tmp_name'];
$arrFilesErrors = $filesArray['error'];
$arrFilesSizes = $filesArray['size'];
foreach($arrFilesKeys as $intKey=>$strKeyName){
$tempFileData = new stdClass();
$tempFileData->key = $strKeyName;
$tempFileData->name = $arrFilesNames[$strKeyName];
$tempFileData->type = $arrFilesTypes[$strKeyName];
$tempFileData->tmp_name = $arrFilesTmpNames[$strKeyName];
$tempFileData->error = $arrFilesErrors[$strKeyName];
$tempFileData->error = $arrFilesSizes[$strKeyName];
$arrFilesData[$strKeyName] = $tempFileData;
}
// UPLOAD THE FILES:
if($titleAlbum){
$username = trim($_SESSION['username']);
$path = __DIR__ . "/../users/" . $username . "/" . $titleAlbum;
//CREATE UPLOAD DIRECTORY IF IT DOESN'T ALREADY EXIST...
if(!file_exists($path)){
mkdir($path, 0777, TRUE);
}
// LOOP THROUGH THE FILES OBJECT ARRAY AND PERFORM FILE-UPLOAD
foreach($arrFilesData as $fileKey=>$objFileData){
$rightPath = $path . DIRECTORY_SEPARATOR . $objFileData->name;
if(move_uploaded_file($objFileData->tmp_name, $rightPath)){
echo $objFileData->name . " upload is complete<br>";
echo "upload completato";
} else {
echo "move_uploaded_file function failed for ". $objFileData->name ." into". $path . "<br>";
}
}
}
}
In this case, your HTML Form is expected to look like this:
HTML
<form id="albumform" style="" enctype="multipart/form-data" action="scripts/albumupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000">
Name: <input name = "titoloalbum" type="text" required><br><br>
Cover: <input name = "filesArray[userfile]" type="file">
<br><br>Select your songs:<br />
<input name="filesArray[file_1]" type="file" value="" /><br />
<input name="filesArray[file_2]" type="file" value=""/><br />
<input name="filesArray[file_3]" type="file" value=""/><br />
<input name="filesArray[file_4]" type="file" value=""/><br />
<input type="submit" value="Send files" />
</form>

Image not getting upload in PHP

I am uploading an image using the following php code but the file is not getting upload.
if(isset($_POST['submit'])){
$title = $_POST['title'];
$target_folder = "../newsimageuploads/";
$bannerimagelink = "http://example.com/newsimageuploads";
$bannerimage = addslashes(file_get_contents($_FILES['bannerimage']['tmp_name']));
$bannerimage_name = addslashes($_FILES['bannerimage']['name']);
$bannerimage_size = getimagesize($_FILES['bannerimage']['tmp_name']);
if ($bannerimage!=""){
$rand = rand(111111, 9999999);
$fname = $_FILES["bannerimage"]["name"];
$newname = "Image ".$rand.".png";
move_uploaded_file($_FILES["bannerimage"]["tmp_name"], $target_folder.$newname);
$bannerimage_location = $bannerimagelink."/".$newname;
}
$query =mysql_query("INSERT INTO mytable (title,image) VALUES ('$title','$bannerimage_location')")or die(mysql_error());
if (($query) === TRUE) {
echo "<p style='color:green;'>Added Successfully</p>";
} else {
echo "Some Error Occured :(";
}
}
And my HTML part is
<form action="#" method="post">
<input type="text" name="title">
<input type="file" name="bannerimage" accept="image/jpeg,image/png,image/gif">
<button type="submit" name="submit">Add</button>
</form>
My title is getting insert in the MySQL table but image does not.
You are missing enctype='multipart/form-data' in your form
<form action="#" method="post" enctype="multipart/form-data">
Look here for more details
Add
enctype="multipart/form-data"
to the form tag. Without this attribute you will only get the name of the file. But the file itself won't be uploaded.
<form action="#" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="bannerimage" accept="image/jpeg,image/png,image/gif">
<button type="submit" name="submit">Add</button>

Upload multiple images to Database MYSQLI

I am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?
You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");
First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs

Upload multiple images to a folder with each input having a different name

I am trying to upload multiple images to a folder using PHP using this tutorial I managed:
In the PHP form
<?php
$success = 0;
$fail = 0;
$uploaddir = 'uploads/';
for ($i=0;$i<4;$i++)
{
if($_FILES['userfile']['name'][$i])
{
$uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpg|gif|png|bmp)/",$ext))
{
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile))
{
$success++;
}
else
{
echo "Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}
else
{
$fail++;
}
}
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
?>
In the HTML form
<form enctype="multipart/form-data" action="upload.php" method="post">
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
Image4: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>
As you can see in the HTML form the input name is userfile[] for all of them. Now in my HTML for the input names are as follows: picture01, picture02, picture 03, etc...
How can I modify the PHP code to have my input names {: picture01, picture02, picture 03} rather than userfile[].
Thanks.
UPDATE
I want the above to fit in my HTML Form
<form enctype="multipart/form-data" action="upload.php" method="post">
Picture 01<input id="picture01" name="picture01" type="file" ><br />
Picture 02<input id="picture02" name="picture02" type="file" ><br />
Picture 03<input id="picture03" name="picture03" type="file" ><br />
Picture 04<input id="picture04" name="picture04" type="file" ><br />
<input type="submit" value="Upload" />
</form>
This code is working locally. It uses a combination of your code and the example from php.net. You should probably use pathinfo to get the extension but that's a minor detail.
form.html
<form enctype="multipart/form-data" action="upload.php" method="post">
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
Image4: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>
upload.php:
<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
$success = 0;
$fail = 0;
$uploads_dir = 'uploads';
$count = 1;
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
$uploadfile = "$uploads_dir/$name";
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpg|gif|png|bmp)/",$ext)){
$newfile = "$uploads_dir/picture".str_pad($count++,2,'0',STR_PAD_LEFT).".".$ext;
if(move_uploaded_file($tmp_name, $newfile)){
$success++;
}else{
echo "Couldn't move file: Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}else{
echo "Invalid Extension.\n";
$fail++;
}
}
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
When you have change the names in the form, change the name when you try to get an array element of the file
ex.
echo $_FILES["picture$i"]['name'];
and change the for as this
for ($i=1;$i<=4;$i++)

myproblem in uploading in php

i have this page for upload:
<?php
require ('incs/db.php');
require_once ('incs/funcs.php');
?>
<?php
if (array_key_exists('upload', $_POST)) {
$directory = str_replace(basename($_SERVER['PHP_SELF']),'',$_SERVER['PHP_SELF']);
$uploadHandler = $_SERVER['DOCUMENT_ROOT']. $directory . 'images/';
// $uploadHandler = "echtitipi".$_SERVER['HTTP_HOST']. '/images/';
$max_file_size = 30000;
define('UPLOAD_DIR', $uploadHandler);
$ext= end(explode(".", $_FILES['image']['name']));
$name = rand(1111111,9999999).'.'.$ext;
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadHandler. $name))
{
$upload = true;
$title = $_POST ['title'];
$sql = "INSERT INTO photo (id, keyword, photoName)
VALUES ('','$title','$name')
";
$result = mysql_query ( $sql, $con );
}
else
{
$upload = false;
$msg = 'Cant Upload!';
}
}
?>
<?php
include ('incs/header.php');
?>
<?php
getUrlQuery();
?>
<script language="javascript">
<!--
function pick(symbol, path) {
if (window.opener && !window.opener.closed)
window.opener.document.form.img.value = symbol;
window.opener.document.form.imgbox.src = path;
window.close();
}
// -->
</script>
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">
Tanım:
</label>
<input type="text" name="title" id="title" />
<label for="image">
Upload image:
</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<?php
if($upload == true)
{
echo "<a hrf(because spam!)=\"javascript:pick('$name','images/$name')\"><im(g) src=\"images/$name\" border=\"0\" alt=\"use\"></a>";
}
?>
<?php
include ('incs/footer.php');
?>
`
this upload image to curretnt root's images folder. My current folder is admin:
root/admin/images
root/images
when i use
$uploadHandler = "http://".$_SERVER['HTTP_HOST']. '/images/';
script doesnot work.
<?php
if($upload == true)
{
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
}
?>
the image couldnot add to editor. I guess There is a problem with javascript.
what is wrong in script
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
change into
echo "<img src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\">";
I guess this will help...
Im sorry for bad dictation because i cant write the right script because sending errors(link and images)
above code uploaded code to
/www/admin/images
and save information to database and add image to tinymce editor. But I want to upload code to:
www/images
when I use :
$uploadHandler = $_SERVER['DOCUMENT_ROOT'].'/images/';
and
"<img src=\"images/$name\" border=\"0\" alt=\"use\">"
the image couldnot add to editor. This is my problem.

Categories