PHP: Check if link is image and check if exists - php

i try to check if image exists and when i execute code say "Not Image".
if(#is_array(getimagesize("https://media.giphy.com/media/BvvBz8BnRqZOg/giphy.gif"))) {
echo "Work";
} else {
echo "Not Image";
}
Where is problem, Thanks in advance !

Try
$headers = get_headers('https://media.giphy.com/media/BvvBz8BnRqZOg/giphy.gif', 1);
if (strpos($headers['Content-Type'], 'image/') !== false) {
echo "Work";
} else {
echo "Not Image";
}
You only need to check the headers to see it it is an image, $headers['Content-Type'] in the example is 'image/gif' which is caught by the if statement. For reference check out get headers in the docs http://php.net/manual/en/function.getallheaders.php

Related

php alert message upload successful

I have this code:
<?php
if (isset ($_FILES['UploadFileField'])){
$UploadName = $_FILES['UploadFileField'] ['name'];
$UploadName = mt_rand (100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField'] ['tmp_name'];
$UploadType = $_FILES['UploadFileField'] ['type'];
$FileSize = $_FILES['UploadFileField'] ['size'];
$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);
if(($FileSize > 1250000)){
die ("Error - File to Big");
}
if(!$UploadTmp) {
die ("No File Selected");
}
else {
move_uploaded_file($UploadTmp, "Upload/$UploadName");
}
header('Location: /index.php');
exit;
}
?>
This code works, but I need insert a message of successful after that is done Upload file.
Thank you!
if (move_uploaded_file($UploadTmp, "Upload/$UploadName")) {
$message = "Successfully inserted";
header('Location: /index.php?success=true&message='.$message);
}
else {
$message = "Something went wrong";
header('Location: /index.php?success=false&message='.$message);
}
use the if condition for the move_uploaded_file function it will help you. And get the success, message from index file
if ($_GET['success'] == true) {
echo $_GET['message'];
}
Or you can use the SESSION
You can add a parameter when you redirect like :
header('Location: /index.php?upload=true');
And in your index check if you get the parameter and display a message if it's the case and if it's where you want to display the message. You can check also with if else statement if the upload work and change the var to sent

Php Content insert page not working

I'v been trying to make a content insert page with php and here is my code
<?php // Initialize variables to null.
$title =""; // Sender Name
$author =''; // Sender's email ID
$date =date('d-m-y'); // Subject of mail
$desc="";//meta description
$keywords="";//meta keywords
$content =""; // Sender's Message
$category="";//chosen category
$pattern1="";//preg_match pattern
$nameError ="";
$contentError ="";
$purposeError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
$img_dir=$_SERVER["DOCUMENT_ROOT"] . '/practise/grafitti/images/';
$img;
if(isset($_POST['submit'])) { // Checking null values in message.
//check and assign title title
if(empty($_POST["title_post"])){
$nameError = "A title is required";
errors($nameError);
exit();
}
else{
if (preg_match("/^(\w|\s)$/",$_POST['title_post']))
{
$titleError = "Only letters,numbers and white space allowed";
errors($titleError);
}else{
$title=$_POST['title_post'];
}
}
// Checking null values inthe content.
if (empty($_POST["content_post"]))
{
$contentError = "You have not posted any content.<br/> Please do to proceed";
errors($contentError);
exit();
}else {
$content=$_POST["content_post"];
}
//check and assign category
if(!empty($_POST["categories_post"]))
{
$category=$_POST["categories_post"];
}
//Chexk and assign authors name
if (!empty($_POST["author_post"]))
{
$author=$_POST["author_post"];
}
//check and assign value of description
if (!empty($_POST["desc_post"]))
{
$desc=$_POST["desc_post"];
}
//check and assign keywords
if (!empty($_POST["keywords_post"]))
{
$keywords=$_POST["keywords_post"];
}
//process images
if(isset($_FILES["img_post"])){
echo "good to go";
$name=$_FILES["img_post"]["name"];
$tmp_name=$_FILES["img_post"]["tmp_name"];
$type=$_FILES["img_post"]["type"];
$size=$_FILES["img_post"]["size"];
$img_dir;
if(upload($name,$type,$size,$tmp_name,$img_dir)){
if(move_uploaded_file($tmp_name,$img_dir.$name)){
echo "success";
}else{echo php_info;}
$img_upload_Success="File was uploaded successfully";
errors($img_upload_Success);
}else{
$img_upload_Error="File could not be uploaded";
errors($img_upload_Error);
exit();
}
}
echo $title."<br/>";
echo $author."<br/>";
echo $desc."<br/>";
echo $keywords."<br/>";
echo $category."<br/>";
echo $date."<br/>";
}
// Function for filtering input values.function test_input($data)
function errors($err){
echo "<script>
var err='$err'
alert(err)
</script>
";
}
#validate file upload
function upload($fl_name,$fl_type,$fl_size,$fl_tmp_name,$dir){
#check to see if the file is an image or not
if($fl_type!="image/jpeg" && $fl_type!="image/png" && $fl_type!="image/jpg" && $fl_type!="image/gif"){
$typeError="The file type you uploaded is not supported";
errors($fl_type);
exit();
}
#check file size limits
if($fl_size>512000){
$sizeError="Size of the file is too big. Should be at least 500KB";
errors($sizeError);
exit();
}
if(file_exists($dir.$fl_name)){
$existError="Sorry. File already exists";
errors($existError);
exit();
}
}
?>
the problem is,when I want to validate with the file upload. If I don't upload anything the the code still assumes that my $_FILES['img_post'] isset and it therefore runs the code that satisfies that conditions.
Moreover, if I manage to set the $_FILE variable, it still won't upload.Its like the
if(upload($name,$type,$size,$tmp_name,$img_dir))
returns a false value but the upload() is executed.Can someone please tell me how to handle the isset problem and at least a way to show the error causing the file not to be uploaded
you can try this.
if($_FILES['img_post']['error']==0) {
// process
} else {
$error_message = $error_types[$_FILES['img_post']['error']];
// do whatever with the error message
}
For more details you can refer this.
Use this condition below:
if($_FILES['img_post']['error'] == 0){
//uplode file
}
This will check is it's empty or file been selected. If selected, then it will only upload the file.
change this code
if(isset($_FILES["img_post"])){
to
if(isset($_FILES["img_post"]["tmp_name"])){
Use below code:-
if(isset($_FILES["img_post"]["tmp_name"]) && $_FILES["img_post"]["tmp_name"] != ''){
//uplode file
}
OR
if(!empty($_FILES["img_post"]["tmp_name"])){
//uplode file
}

How to check if file field is empty in codeigniter?

I have a form with a file field called image, but this field is not required.
When user don't choose any file in form, the do_upload() always return a error.
How can I check if user chosen a file before perform the upload action in my controller?
Please use empty()
if (empty($_FILES['userfile']['name'])) {
}
Try to check if the file is valid using is_uploaded_file(). For example:
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
do_upload();
}
In your controller, on the function that receives the submitted form:
if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
// do_upload
}
Here is full script to check if file field is empty or not in php
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations.
refer http://www.techzigzag.com/how-to-check-that-user-has-upload-any-file-or-not-in-php/
Hope it will help you.
Just use native php code to check file upload.
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
use empty() empty function does check if the file field is empty or not
if ( ! empty($_FILES)) {...}
if(!empty($_FILES['myFileField'])) {
// file field is not empty..
} else {
// no file uploaded..
}
As file upload error "No file selected" is number 4, correct way of doing this is:
if ($_FILES['my_image_field_name']['error'] !== 4){
if ($this->upload->do_upload('my_image_field_name')) { ...
When checking by name or tmp_name, there might be other reasons why these fields didn't get populated, and you may miss these.
if(!empty($_FILES[$file_name]['name'])){
// TODO your logic
}else{
echo "empty";
}
$file['file']->isValid()
CI4 user guide link

php/jquery - check if image in url really exists

I found this nifty way to check if a page really exists:
$headers=#get_headers($imageurl);
if(strpos($headers[0],'200')===false){
echo "not valid";
exit;
}
What I need to achieve, though, is to check whether on that page is really only an image.
For example, when you try the following link:
www.google.com/image.jpg
it will return 200 because Google has it's own error page - however, it should be possible to find out not only that there is no image on that page, but also that an image is not the only thing on that page, even when there is other content (like here: http://www.kapstadt-entdecken.de/wp-content/gallery/robben-island/1robben-island.jpg).
How I can I achieve that?
Thanks a lot!
Dennis
You will probably want to use HEAD requests when getting headers (it doesn't do that by default):
stream_context_set_default(array(
'http' => array(
'method' => 'HEAD'
)
));
Second, you can pass a second parameter to get_headers to parse it for you:
$headers = get_headers($imageurl, 1);
Then, you can check the rest as per normal:
if (strpos($headers[0], '200') === false) {
echo "not valid";
exit;
}
if (isset($headers['Content-Type']) && 0 === strncmp($headers['Content-Type'], 'image/', 6)) {
echo "valid image";
} else {
echo "probably not an image";
}
also with get_headers ... one of them will be
image/png
image/jpeg
image/gif
so
$isImage = false;
foreach($headers as $header){
if(strpos($header,'image/')==true){
$isImage = true;
}
}
$headers = #get_headers($imageurl);
$is_image = false;
foreach ($headers as $header) {
if (strpos($header, 'Content-Type: image/') === 0) {
$is_image = true;
break;
}
}

file_exists() returns false, even for paths that do exist

OK programmers, I'd like to figure this one out before the New Year. I want to display a photo only if it exists, otherwise use a default photo. Here is my code that always correctly returns "File Exists"
<?php
$photolocation = '../wp-content/gallery/playerphotos/Joe Smith.jpg';
if (!file_exists($photolocation))
{
echo "File exists";
}
else
{
echo "File does not exist";
}
?>
When I change the photolocation to:
$photolocation = '../wp-content/gallery/playerphotos/XXX Smith.jpg';
I incorrectly get "File exists".
I can't figure out why the condition !file_exists always returns a positive value.
That should be:
<?php
$photolocation = '../wp-content/gallery/playerphotos/XXX Smith.jpg';
if (file_exists($photolocation))
{
echo "File exists";
}
else
{
echo "File does not exist";
}
?>

Categories