I have this code code below to upload image in a foder uploads/year/month, if this directory does not exist it will create if exists I only do the upload.
After this code, Im doing a insert into my "news" table with this thumb info and the other table news fields.
And it is working fine, Im inserting without any error, its inserting in my database, and the image file is uploading with sucess in my uploads/year/month folder.
But now in my other file "news-edit.php", to edit my news, and I want to show the thumb file in my label.
Im trying to do this for hours and its not working, somebody there can give me a help understanding what is happening?
My php code to upload image
if(!empty($_FILES['thumb']['tmp_name'])){
$folder = '../uploads/';
$year = date('Y');
$month = date('m');
if(file_exists($folder.$resultReadEdit['thumb']) && !is_dir($folder.$resultReadEdit['thumb']))
{
unlink($folder.$resultReadEdit['thumb']);
}
if(!file_exists($folder.$year)){
mkdir($folder.$year,0755);
}
if(!file_exists($folder.$year.'/'.$month)){
mkdir($folder.$year.'/'.$month,0755);
}
$img = $_FILES['thumb'];
$ext = substr($img['name'],-3);
$f['thumb'] = $year.'/'.$month.'/'.$f['url'].'.'.$ext;
uploadImage($img['tmp_name'], $f['url'].'.'.$ext, '300', $folder.$year.'/'.$month.'/');
}
My php to show the image file:
<label class="line">
<?php
$folder = '../uploads/';
$year = date('Y');
$month = date('m');
echo '<a href="'.$folder.$year.'/'.$month.'/'.$resultReadEdit['thumb'].'" rel="Shadowbox">';
echo '<img src="'.$folder.$year.'/'.$month.'/'.$resultReadEdit['thumb'].'" width="50" />';
echo '</a>';
print_r($resultReadEdit['thumb']);
?>
<input type="file" class="fileinput" name="thumb" size="60" />
</label>
What Im getting:
Look at your generated html source code. Since your print_r($resultReadEdit['thumb']) is returning
2014/04/title-of-my-news.png
you are saving $resultReadEdit['thumb'] as year/month/thumb so your html source code probably is looking like
src="uploads/2014/04/2014/04/title-of-my-news.png"
So try changing
echo '<img src="'.$folder.$year.'/'.$month.'/'.$resultReadEdit['thumb'].'" width="50" />';
to
echo '<img src="'.$folder.$resultReadEdit['thumb'].'" width="50" />';
Related
I am having trouble making a image deleter in php i do not know what is wrong
PHP:
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
$image = $_POST['dcheck'];
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
?>
HTML:
<form action="Admin3.php" method="post">
<?php
while($check = mysql_fetch_array($query2)){
echo '<img class="images2" src= "/PhotographyMML/Uploads/resized' . $check['PhotoName'] . $check['PhotoType'] . '" height="100" width ="100" ><input type="checkbox" name="dcheck[]" value="'. $check['PhotoNumber'] .'" />';
}
?>
<input type="submit" value="Delete Image(s)" />
</form>
Your dcheck variable is an array. You will want to create an outer loop around the existing query code you have and foreach through the array, deleting each time.
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
foreach ($_POST['dcheck'] as $image) {
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
}
?>
A small optimization would be to alter the query so it uses WHERE A small optimization would be to alter your delete query so that it uses WHERE PhotoNUmber IN (1, 2 ...).
This would cause your deletion to happen in one query rather than N queries.
What seems to be missing is any code to actually remove the original file you're alluding to. That would require some sort of file deletion function typically utilizing http://php.net/manual/en/function.unlink.php
i have multiple image upload options in the form and they are working fine and update file name in the mysql database columns?
when i uploads image1 then image move on to the server and also it is showing next to html table columns now problem is that when i upload image with file option2 after form submit then image1 which is on the next to the image1 file option will be disappeared and in the mysql database image1 columns will be blank?
Multiple Images Uploading Functions
$id=$_REQUEST['id'];
if(isset($_POST['submit']))
{
if (!empty($_FILES['image']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 25;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image', $file_name, $file_path))
$demo_image = $image->img_path;
}
if (!empty($_FILES['image1']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image1']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image1', $file_name, $file_path))
$demo_image2 = $image->img_path;
}
if (!empty($_FILES['image2']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image2']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image2', $file_name, $file_path))
$demo_image3 = $image->img_path;
}
Update Query
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
Select Images Query
$query1=mysql_query("select images,addimages1,addimages2 from products
where id='$id' ")or die("query");
$row2=mysql_fetch_array($query1);
<form method="post" enctype="multipart/form-data">
Image Upload Option1
<input type="file" name="image" id="image" />
<img src="<?php echo $image['image'] ?>" width="150" height="150" />
Image Upload Option2
<input type="file" name="image1" id="image1"/>
<img src="<?php echo $image['addimage1'] ?>" width="150" height="150" />
Image Upload Option3
<input type="file" name="image2" id="image2"/>
<img src="<?php echo $image['addimage2'] ?>" width="150" height="150" />
<input type="submit" class="bg" name="submit" />
</form>
The problem lays here:
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
From what I understood you first submit the form where you upload the first image and then you submit the form again where you upload the second image. The reason of this is that during your second upload the variable $demo_image will be blank because you are not sending any value of the input "image" during the resubmit. See here:
$demo_image = $image->img_path;
$image->img_path is blank, therefore $demo_image will be blank (or NULL? - not sure) as well.
There are many solutions of this problem. You can retrieve data from you db to the form and then resubmit, or test if your variables are blank (or NULL?) and then having different UPDATE commands for different variations, or retrieving data from MySQL just before you run UPDATE and many more.
I'd pick retrieving "old" data from MySQL and then just test if their NULL. If they are not NULL in MySQL, you will just resubmit the same data to your db. Like this:
if ($demo_image_from_db!=NULL) $demo_image = $demo_image_from_db;
It is possible that there is also a MySQL native function for updating only when NULL - I've heard of COALESCE but I don't exactly know how to use it - that would be definitely the simplest way to do it.
I'm trying to implement a small update profile pic form.
<form method="post" action="<?php echo $filename;?>" name="change_picture_form" id="change_picture_form" enctype="multipart/form-data">
<input type="hidden" name="action" value="change_picture" />
<input type="file" name="new_user_picture">
<input type="submit" class="submitButton" value="Save Changes"/>
</form>
The target php file has the following code:
echo $_FILES['new_user_picture']['size']." ";
echo $_FILES['new_user_picture']['tmp_name']." ";
echo $_FILES['new_user_picture']['name']." ";
echo $_FILES['new_user_picture']['error']." ";
echo $_FILES['new_user_picture']['type']." ";
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"];
if( is_uploaded_file( $picture_uploaded ) ) {
$imagesize = getimagesize( $picture_uploaded );
switch( $imagesize[2] ) {
case IMAGETYPE_PNG:
$extension = '.png';
echo "<script>console.log('Reached here!!')</script>";
try {
$image_original = imagecreatefrompng( $picture_uploaded );
if (!$image_original)
echo '<script>console.log("not image original")</script>';
} catch(Exception $e) {
echo "<script>console.log('Error!!')</script>";
}
break;
case IMAGETYPE_JPEG: ....
...
}
}
Here, I have similar code for many image types. I tested this code by trying to uploading a png image. The first 5 echo statements display expected results - the size, error value of zero, the name, the type and the temp name.
I get "Reached here!!" on my console.
imagecreatefrompng, however, seems to crash silently. Try-catch somehow doesn't seem to catch the error.
Help? Thanks!
I haven't handled file uploads in PHP in forever, but is it possible that this line:
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"]
should be
$picture_uploaded = $_FILES["new_user_picture"] ?
The first line, as is, should be getting you the uploaded file's file name, whereas the second line (the edited line above) should be a reference to the file itself.
HTH.
EDIT: Well, seeing as how my answer is incorrect... does this help? http://www.php.net/manual/en/function.imagecreatefromstring.php
. There's a helper function in the user notes/comments that might simplify what you're doing
i am making a login system with registration and a profile page in php and i am trying to make a profile picture work.
if the user has not uploaded a profile picture yet then make it show a "no profile picture" image if the user has uploaded a profile picture make make it show the image that he has uploaded.
Right now it only show the default picture, noprofile.png.
< img src="uploads/< ? echo "$username" ? >/noprofile.png">
i want it to show icon.png if icon.png has been uploaded and if it hasnt been uploaded make it show, noprofile.png.
Just run it through the logic, using file_exists:
$image="/path/on/local/server/to/image/icon.png";
$http_image="http://whatever.com/url/to/image";
if(file_exists($image))
{
echo "<img src=\"$http_image\"/>\n";
}
else
{
echo "<img src=\"uploads/$username/noprofile.png\"/>\n";
}
Check to see if the file has been uploaded by using file exists. If the file exists, use that url else use the default noprofile.png.
you could make a column in the DB to store a value if it has been uploaded or not.
OR
you could see if the file exists.
<?php
if (file_exists('uploads/' . $username . '/icon.png')) {
echo '<img src="uploads/' . $username . '/icon.png">';
}
else {
echo '<img src="uploads/' . $username . '/noprofile.png">';
}
?>
<?php
$img = file_exists(sprintf('/path/to/uploads/%s/icon.png', $username))
? 'icon.png' : 'noprofile.png';
?>
<img src="uploads/<?php printf('%s/%s', htmlspecialchars($username), $img) ?>">
You could use http://us3.php.net/file_exists to check if the image file is there.
Another alternative is - assuming you keep your user info in a database - have a column with the image name. Since you have to retrieve info from your user table anyway, check to see if that column is NULL or blank. If it is, the user has not uploaded an image yet.
Then, in the page you display the user photo, you might have code something like this:
$userPhoto = ($photoName)? $photoName : 'placeholder';
echo '<img src="uploads/'.$userPhoto.'.png" />
Assuming the filepaths are correct, here's what you do...
<?php $filename = "uploads/".$username;
$imgSrc = file_exists($filename) ? $filename : "uploads/noprofile.png"; ?>
<img src=<?php echo $imgSrc?>
Use onerror attribute in img tag
<img onerror="this.src= 'img/No_image_available.png';" src="<?php echo $row['column_name ']; ?>" />
I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">