File not saving

I have the following file with the function fred(…) which I include for debugging purposes:

fred.php

<?php declare(strict_types=1);
//===============================
// usage:
//   fred($val); // uses print_r(...)
//   fred($val, TRUE); // uses var_dump(...)
//===============================
function fred($val='Nothing passed???', $vd=FALSE)
{
$style='width: 88%; margin: 1em auto; background-color: #ffd; color: #000';
echo '<pre style="' .$style .'">';
if( $vd ) :
  var_dump($val);
else: 
  print_r($val);
endif;
echo '</pre>';
}///

Calling fred( $any_variable_type_including_objects ) will format the variable details:

Example - fred($_SERVER) :

1 Like

If your intent is to grab an image URL and be able to save the image to your server, you’re doing it all wrong. You should be using cURL and making sure the result isn’t empty. If it isn’t, then proceed with saving the file using fopen. You’re also relying too heavily on the file extension which isn’t a good thing. The file extension can be maliciously altered to have malicious code hidden inside the file. So relying on the file extension won’t do you any good.

Choosing a possible selection from an available option is another debate sir, and CURL I know is a better option, but I followed a tutorial and if theirs is working mine should also work.

And thanks for suggesting another better way once I am through this. I will try to use those methods also.

In the meanwhile, I tried some debugging, but could not interpret much.

I searched and found the above article source and noticed that a new upload directory is essential and also requires the correct user permissions.

I downloaded all the files, made the directory and was still unable to get the project to work.

I had difficulty in trying to debug the AJAX file and would be very grateful for exactly how to achieve this bottleneck.

There is an unanswered comment:

Do you have php’s error_reporting set to E_ALL and (temporarily) display_errors set to ON, so that any php detected errors would be displayed?

And yet, you still don’t look at the return from file_get_contents() and file_put_contents(). What is in $image_data? Does it contain your image, or is it false, indicating it was unable to get the data? If that does contain the correct information, what does file_put_contents() return? If it gives false, that indicates it could not write the data to your location.

Sorry if you’ve done that and I’ve missed it.

@mabismad @droopsnoot,

Check the supplied link, there are only two files to download and to create the upload directory. Should only take about a minute to install.

I set maximum error reporting and there are no errors.

I’ve always had problems debugging AJAX. I would like to know how you debug because normal debugging does not work :frowning:

I have downloaded the code. Checking the return from file_put_contents() gives “Warning: file_put_contents(/sitepoint/codeisp/upload/374365915.png): failed to open stream: No such file or directory in C:\wamp64\www\sitepoint\codeisp\upload.php on line 32”.

As soon as I change the line to use getcwd() for the directory it works just fine. In my case the “upload” directory is beneath the directory that my code is running in, so it works. I suspect there may be a better way to get the absolute directory.

But, just checking the return from the function that is falling over showed me what the problem is. And, of course, the OP needs to add that functionality into their code, rather than just call file_put_contents() and then immediately output “Image Uploaded”, which it may not have been.

In actual fact, while I do echo $put; to see the return, by adding the error() function that showed me the standard PHP error screen.

All I’ve done here is add various echo statements, followed by exit(). I then use Chrome to run the code, enable the developer tools and look at the console, which shows me either the raw response (the text I echoed) or the html for an error message if I have one.

<?php 
//upload.php
/*
echo "In PHP Code";
var_dump($_POST);
exit();
*/

if (isset($_POST["image_url"])) {
	$message = '';
	$image = '';
	if (filter_var($_POST['image_url'], FILTER_VALIDATE_URL)) {
		$allowed_extension = array("jpg","png","jpeg","gif");
		$url_array = explode("/", $_POST["image_url"]);
		$image_name = end($url_array);
		$image_array = explode(".", $image_name);
		$extension = end($image_array);
		// echo var_dump($extension) . "<br>";

		if (in_array($extension, $allowed_extension)) {
			$image_data = file_get_contents($_POST["image_url"]);
			/*if ($image_data == false) {
				echo "couldn't get image";
				exit;
			} else {
				echo "Got image " ;
				exit();
		}*/
			$new_image_path =  getcwd()."/upload/".rand().".".$extension;			
			
			$put = file_put_contents($new_image_path, $image_data);
			//echo $put; Did we get 'false'? Code should check this before saying image uploaded
			$message = 'Image Uploaded';
			$image = '<img src="'.$new_image_path.'" class="img-responsive img-thumbnail">';
			//echo var_dump($image) . "<br>";
		}else{
			$message = 'Image not Found';
		}
	}else{
		$message = 'Invalid URL';
	}
	$output = array(
		'message' => $message,
		'image'   => $image
	);
	echo json_encode($output);
}

I’ve also added an “error” function in the Ajax call, because this seems to be required:

$('#upload').attr("disabled","disabled");
    				$.ajax({
    					url:"upload.php",
    					method:"POST",
    					data:{image_url:image_url},
    					dataType:"JSON",
    					beforeSend:function(){
    						$('#upload').val("Upload in Process...")
    					},
    					success:function(data){
							console.log(data);
    						$('#image_url').val('');
    						$('#upload').val('Upload');   
    						$('#image_url').attr('disabled',false); 		
    						$('#result').html(data.image);	
    						alert(data.message);			
    					},
						error: function(data) { 
						console.log("error");
						console.log(data);
						}
2 Likes

Also, because the OP uses the same variable to display the image when the upload is done by returning the html as part of the response, that won’t work. Because I’m now using the absolute path to store the image because that is what file_put_contents() requires, that is no longer correct for the img tag, which will need the relative path. I’ll leave the OP to sort that out.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.