move_uploaded_file is not WORKING - php

I have a code. But move_uploaded_file is not working.
This is my code below:
is there any way to upload all types of with one field like Image/Video?
<?php
if(isset($_POST['save_news']))
{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$location="news/" . $_FILES["image"]["name"];
$vfile=$_FILES['video']['tmp_name'];
$vid= addslashes(file_get_contents($_FILES['video']['tmp_name']));
$video_name= addslashes($_FILES['video']['name']);
$video ="news/" . $_FILES['video']['name'];
$q = mysql_query("INSERT INTO news(video,image) VALUES('$video',
'$location')");
if(!$q)
{
echo mysql_error();
}
else
{
move_uploaded_file($_FILES["video"]["tmp_name"],"../news/" . $_FILES["video"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],"../news/" . $_FILES["image"]["name"]);
$_SESSION['mass_added']= 'echo"you are logged in"';
echo "<script>window.location = 'manage_news.php?user_type=admin'</script>";
}
}
?>

You need to check the errors to find out why. Do this by looking at $_FILES['video']['error'].
My guess would be that if you're uploading videos, their filesize is too large. You can change the maximum upload file size in php.ini with `upload_max_filesize=..." (see here).

Related

Resize image uploading php

is there an easy way to resize an image before uploading. Been looking for a while now but nothing seems to be working well for me. I want to resize everything to ratio and only resize if something is bigger then lets say 150. Height should move down so the image still looks as it should. I have the following code which works for uploading and renaming but now i want to implement a resize on top of this
$uploadDir = 'images/'; //Image Upload Folder
$fileName = $_FILES['file-0']['name'];
$tmpName = $_FILES['file-0']['tmp_name'];
$fileSize = $_FILES['file-0']['size'];
$fileType = $_FILES['file-0']['type'];
$temp = explode(".", $fileName);
$newfilename = $id . round(microtime(true)) . '.' . end($temp);
$result = move_uploaded_file($_FILES["file-0"]["tmp_name"], "images/" . $newfilename);
$filePath = $uploadDir . $newfilename;
if (!$result) {
echo "Error uploading file";
exit;
}
$query = "
update
pictures SET picture = '$filePath' Where
id = :id
";
$query_params = array(
':id' => $id
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch (PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
You can use php class from the address below. I tried and it works like a charm. It resizes images on the fly.
http://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html
You can check this link below too, to have an idea:
PHP upload and resize image

How can i replace the image name and add date time and arandom number as image name using php

I am having trouble in managing images in a gallery. For example if abc.jpg is already exist. If i try to upload an image having the same name (abc.jpg) the previous image is replaced with new one . So i was thinking about renaming the image with a random number as image name (i.e current date+Time+Random Number). Here is my code
<?php
session_start();
include("includes/connect.php");
$name= $_SESSION['email'];
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
$location="photos/" . $_FILES["image"]["name"];
$pname=$_POST['p_name'];
$email= $_SESSION['email'];
$category=$_POST['category'];
$dimention=$_POST['dimention'];
$desc=$_POST['description'];
$price=$_POST['price'];
$status=$_POST['status'];
$dop=$_POST['dou'];
$save=mysql_query("insert into paintings (location,p_name,email,category,dimention,description,price,status,dou,varify) values ('$location','$pname','$email','$category','$dimention','$desc','$price','$status','$dop','0')")or die(mysql_error());
$result= mysql_query ("select p_id from paintings ORDER BY p_id DESC LIMIT 1");
$row=mysql_fetch_array($result);
$pid=$row['p_id'];
$save1=mysql_query("insert into upload (email,p_id,u_date) values ('$name','$pid',now())")or die(mysql_error());
header('Location: user_profile.php');
}
$newfile=date('d-m-Y')."_".rand(0000,9999).$_FILES['image']['name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $newfile);
$filename=$_FILES["image"]["name"];
$ext = explode('.', $filename);
$without_extension = substr($filename, 0, strrpos($filename, "."));
$final_name=$without_extension.time().'.'.$ext
This will work I guess there is no need for random number since we use unix timestamp. To make it simple
$filename=$_FILES["image"]["name"];
$final_name=time().$filename;

PHP image upload script (need to add reduce size, compress and rotate with EXIF data)

I am a newbie to programming, and this is my first exposure to PHP. I am building a mobile web app where users can upload pictures to the site while at the social event.
I used the PHP script from W3schools (don't hate me please, but it works for my limited knowledge).
Because it is a mobile app I need to add extra functionality but cannot figure out how with the multitude of scripts and my lack of knowledge.
Before the image is uploaded in the script, I would like first do the following.
1) Reduce the dimension to 500px wide and 'auto' the height to retain picture ratio.
2) Compress the file so it is more appropriately filesized for resolution on mobile devices (it will never be printed) and to speed up the upload over cell network.
3) Ensure that the display is correct by way of EXIF data. Right now, iOS, Android and Windows all display portrait and landscape images differently,...I need consistency
Here is my code,...I have remarked where I think it should go but I am not entirely sure.
This code comes up in a pop-up div tag over the page that displays the images.
<?php
$target_dir = "uploads/";
$target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]);
$target_dir1 = $target_dir . basename( $_FILES["uploadFile"]["tmp_name"]);
$fileTmpLoc = $_FILES["uploadFile"]["tmp_name"];
$uploadOk=1;
// Check if Upload is done without file.
if (!$fileTmpLoc) { // if file not chosen
echo '<script language="javascript">';
echo 'alert("Please browse for a file before clicking the upload button")';
echo '</script>';
echo '<script language="javascript">';
echo 'window.history.back()';
echo '</script>';
}
// Check if file already exists
if (file_exists($target_dir . $_FILES["uploadFile"]["name"])) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($uploadFile_size > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
//Check no php files
if ($uploadFile_type == "text/php") {
echo "Sorry, no PHP files allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
//Reduce file to 500px wide
//Compress file
//Rotate file with EXIF data to properly display.
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir1)) {
echo header( 'Location: gallery.php' ) ;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Thanks for any help and as mentioned this is my first exposure to PHP.
There is a free utility called SimpleImage.php, available at http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php that will handle resizing and compression and might be a good starting point. There are great examples on their page on how to use it, below is an example of how I use it to resize uploaded images to a certain width:
require_once("SimpleImage.php");
function createThumbnail($cat_code) {
// Check for full size product image
$fname = $this->getImageFilename($cat_code);
if($fname === "") {
echo "<b>createThumbnail: No image file found for " . $cat_code . "!</b><br>";
return false;
}
$thumb = "images/t/" . $cat_code . ".100.jpg";
if($fname !== "") {
$image = new SimpleImage();
$image->load($fname);
$image->resizeToWidth(100);
$image->save($thumb);
}
return true;
}
function process_upload($file, $cat_code, $format, $price=NULL) {
$imageFileExtensions = array('jpg', 'gif', 'png');
$target_path = "uploads/";
$target_path1 = $target_path . basename($file['name']);
$path_info1 = pathinfo($target_path1);
$ext = $path_info1['extension'];
if(move_uploaded_file($file['tmp_name'], $target_path1)) {
if(rename($target_path1, $main_path1)) {
echo "File ". $file['name'] . " verified and uploaded.<br>";
//Create thumbnail if this is an image file
if(in_array($ext, $imageFileExtensions))
$createThumbnail($cat_code);
} else {
echo "<b>ERROR renaming " . $file['name'] . "</b><br>";
}
}
else
echo "<b>move_uploaded_file(" . $file['tmp_name'] . ", $target_path1) failed</b><br>\n";
}
To do a rotate just add another function to the SimpleImage class that uses imagerotate(), for example the following:
function rotate($angle, $bgd_color, $ignore_transparent=0) {
imagerotate($this->image, $angle, $bgd_color, $ignore_transparent);
}
The php.net page for imagerotate has more details on the function parameters.
To work with EXIF data, I use another free utility called PelJpeg.php, available at http://lsolesen.github.io/pel/. There are many examples on how to use this if you google PelJpeg.php. It can get kind of complicated, because as you mention, every platform handles images and meta data a little differently, so you have to do a lot of testing to see what things are handled the same on various platforms, what things are different, and how to bridge across those gaps.

How to Insert images as file instead of inserting them in Database as BLOB

I am new to php. i want to upload images from html form into file. i searched on net but unable to find anything helpful. Please tell me how to uplaod images in file rather than database. i know the method of uploading images in database, and its very easy. Is there any way like this of uploading images in file. sorry for my bad english.
$_FILES['image']['tmp_name'];
$original_image=file_get_contents ($_FILES['image']['tmp_name']);
$name= $_FILES['image']['name'];
Take a look at move_uploaded_file.
This is an example from the link:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Shorter example without support for multiple files/error checking:
<?php
$tmp_name = $_FILES["image"]["tmp_name"];
$name = $_FILES["image"]["name"];
move_uploaded_file($tmp_name, "uploads/$name");
?>
Even shorter as a one-liner:
<?php
move_uploaded_file($_FILES["image"]["tmp_name"], "uploads/" . $_FILES["image"]["name"]);
?>
do you mean you want to store your image to your server.
just use these two functions
<?php
copy($_FILES['image']['tmp_name'], $imgPath); //copy your image to a specific path on server
move_uploaded_file($_FILES['image']['tmp_name'], $imgPath); //copy your image to a specific path on server and delete uploaded image in temp folder
?>

Upload image php mysql twice with different names

I am trying to upload an image to the server (with a path in mysql table) twice through php with different names. One version of the image as "xxxx.png" and the other version of the image as "xxxxt.png".
My php is:
<?php
if ($_FILES['photo']) {
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
} else {
echo "Error uploading new image - please check the format and size";
}
}
?>
The above code inserts the image into the mysql database and uploads the file to the server correctly.
I am however trying to upload the same image twice with a different naming convention on a "thumbnail" version. The slideshow script in my html only recognises the thumbnails if there are named with a "t" at the end of the filenames hence my problem.
I have been advised to look at the php copy() function to achieve this but am incredibly unclear as to how to incorporate such a function into my existing code.
Happy to provide the html or any other info if required.
Any help much appreciated. I did have another thread attempting to find out the same thing but I wasn't very clear!
Thanks
JD
If I correctly understand you, you do not need to upload this file twice. You already have this file on your server. So you should copy it (optionally do some transitions to make it more like a thumbnail) on your server's hard drive and update database.
Your code should like similar to this:
<?php
if($_FILES['photo'])
{
$target_dir = "images/properties/";
$upload_file_name = basename( $_FILES['photo']['name']);
$upload_file_ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . $upload_file_name . '.' . $upload_file_ext;
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.' . $upload_file_ext);
$target_thumb = $target_dir . $upload_file_name . 't.' . $upload_file_ext;
$target_thumb_sql = $target_dir . mysql_real_escape_string($upload_file_name . 't.' . $upload_file_ext);
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_file_sql' )");
echo "The new image has been added successfully";
if (copy($target_file, $target_thumb))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_thumb_sql' )");
echo "The new thumb image has been added successfully";
} else
{
echo "Error copying thumb file";
}
} else
{
echo "Error uploading new image - please check the format and size";
}
}
Again, the idea is that you do not need to upload file twice in a row. All you need to do is just copy it on server.
As you've been advised you should use copy(). I didn't fully test this but give it a try:
<?php
if ($_FILES['photo'])
{
$target = "images/properties/";
$ext = array_pop(explode('.', $_FILES['photo']['name']));
$copy = $target . basename($_FILES['photo']['name'], '.' . $ext) . 't.' . $ext;
$target = $target . basename($_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
copy($target, $copy);
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
}
else
{
echo "Error uploading new image - please check the format and size";
}
}
?>

Categories