Post multiple URL - php

I want to post multiple images by posting the url's but I don't know how to do this because I am new to PHP.
<?PHP
if(isset($_POST['post_image']))
{
$image_url=$_POST['image_path'];
$data = file_get_contents($image_url);
$new = '../images/myimage.jpg';
$upload =file_put_contents($new, $data);
if($upload) {
echo "<img src='../images/myimage.jpg'>";
}else{
echo "Please upload only image files";
}
}
?>

The problem with your script is, that you are not saving the file anywhere. So you have no access to it when trying to return it to the client.
In order to save an image using a POST you need to make sure you have set the following enctype inside your form.
<form action="upload.php" method="post" enctype="multipart/form-data">
Then you can use this function to save the img
move_uploaded_file($_FILES["myImg"], "/path/to/imgDir")
And later show it to the client using:
echo "<img src='/path/to/imgDir/myImg'>"
For more information about the topic i advice you to consult the following URL
https://www.w3schools.com/php/php_file_upload.asp

Related

how to decode json with twig?

I'm creating a website where users can uploads some images, URL images are saved into json and inserted into database so when I select all of the rows in the table it gives me something this.
{
"sroxrafm72pgipmpa4nz":
"http:\/\/res.cloudinary.com\/dok4nvr2e\/image\/upload\/v1444610510\/sroxrafm72pgipmpa4nz.jpg"
},
{
"egrrhg4umqgyjoltxrky":
"http:\/\/res.cloudinary.com\/dok4nvr2e\/image\/upload\/v1444610511\/egrrhg4umqgyjoltxrky.jpg"
},
{
"rfurg40o5af2h6s55thb":
"http:\/\/res.cloudinary.com\/dok4nvr2e\/image\/upload\/v1444610511\/rfurg40o5af2h6s55thb.jpg"
}
I need to decode it with twig to get the url of each id to display the images, but I just can't figure out to do this. I hope you guys can help me.
I'd say this is a clone of: Decoding JSON in Twig
What might be easier is to base64 encode the images and store the string inside of the database. I use the following:
In HTML:
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="image" />
</form>
upload.php:
function getImageBase64($image_path) {
$image = imagecreatefromfile($image_path);
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
$image_string = 'data:image/png;base64,' . base64_encode($contents);
imagedestroy($image);
return $image_string;
}
if (getimagesize($_FILES["image"]["tmp_name"]) !== false) {
$image = getImageBase64($_FILES["image"]["tmp_name"]);
//Add to database...
}

Displaying an image from an SQL BLOB with PHP

I have two files, one to upload an image and another to retrieve it from the database and present it on the web page. However the image only appears as broken image icon. I do not understand why.
Thanks for any help in advance.
The HTML form:
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
The php to upload it(The connection to the DB is left out below but it works perfectly):
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image";
else {
$image=addslashes(file_get_contents($_FILES['image']['tmp_name']));
$imageName=addslashes($_FILES['image']['name']);
$imageSize=getimagesize($_FILES['image']['tmp_name']);
if(!$imageSize)
echo "Thats not an image you mong";
else {
//upload
$query="INSERT INTO store VALUES('','$imageName','$image')";
$sendQuery=mysql_query($query);
if(!$sendQuery)
echo "This is embarressing. It didn't work";
else {
$lastid=mysql_insert_id();
echo "Image was uploaded. <br>Your image:";
echo "<img src=get.php?id=$lastid/>";
}
}
}
The PHP to retrieve the image(Again the DB connection is left out below but works perfectly):
$id=addslashes($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
Make sure the the opening php tag is the very first line of the file. If the opening php tag is not on the first line of the file then content has already been written to the response causing calls to the header() function to be ignored.
<?php // this has to be on line 1
// do database connections stuff, no output can be sent to the response.
$id=addslashes($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
Maybe one of the magic quote setting (magic_quotes_gpc), try:
$image=stripslashes($image['image']);
You should be using mysql_real_escape_string() instead of addslashes() and only if magic quotes are not enabled.

Secure images failing - Codeigniter

My script pretty much works, however when I run a for loop it fails, in the view:
<?php foreach($pics as $index=>$pic){?>
<td class='Pictures'>
<center>
<?php
$piece = explode('/',$pic["ThumbImg"]);
$string = $piece[5];
?>
<img src='<?php echo base_url(); ?>index.php/Controller/getImage/<?php echo $string; ?>/1' width="100px">
</a>
Controller class - Get image function:
//function to protect images from being accessed directly by obfuscating the URL
function getImage($img_id,$type){
if($this->members->logged_in()){
//code to authenticate user goes here then...
//code to decide which type of file it is/thumb/full size image
if($type==1)
{
$url = $this->data['base_url'].'system/application/images/pic/thumbs/';
}else if($type==0){
$url = $this->data['base_url'].'system/application/images/pic/';
}
$filepath = $url.$img_id;
//send image to web browser.
header("Content-type: image/jpeg");
//get path
$img_handle = imagecreatefromjpeg($filepath) or die("");
//create and send
ImageJpeg($img_handle);
}
I suspect that this could be due to the headers being resent, if so how can I resolve this.
Cheers
Fixed the problem - used "Hotlinking"
You will basically only need to set the header information header("Content-type: image/jpeg") if you're loading the image from the database. But since you're loading it from a folder you might want to skip the php file and immediately fetch the image from the folder:
<img src='<?php echo base_url(); ?>img_folder/<?php echo $string; ?>/1'
width="100px">

How to serve multiple images which reside above the www root within a single page?

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">

why isnt this php working, i get undefined index...?

I am trying to upload an image to the server.
I hava a form with a couple of inputs...
INSIDE this form, I have an Iframe which contains another form for the upload, this because I dont want the original form to submit().
The original form basically:
<form> ...... bla bla bla alot of inputs....<iframe src="pic_upload.html"></iframe></form>
Here is pic_upload.html:
</head>
<body><form name="pic_form" id="pic_form" action="bincgi/imageUpload.php" method="post" target="pic_target"><input name="pic_file" type="file" id="pic_file" size="35" onchange="this.form.submit();"></form><div id="pic_target" name="pic_target" style="width:80px; height:80px;"></div></body>
</html>
Here is imageUpload.php:
<?php
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if(#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
?>
I get this error: Undefined index: pic_file on line 5 in imageUpload.php
ALSO, if I get this to work, is there a good way to display the uploaded image inside the target of the form?
Thanks alot!
PS: I will add javascript to the tags because maybe thats what I need here!
Don't forget about form attribute
enctype="multipart/form-data"
The form needs to be like this
<form enctype="multipart/form-data" action="__URL__" method="POST">
Check out this PHP.net documentation for more information.
You first need to test if $_FILES has an item with the key pic_file. So use the isset function to do so:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
if (isset($_FILES['pic_file'])) {
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if (#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
}

Categories