I want to hide the broken image icon, but the image server that i'm using doesn't throw a 404 page, instead it redirects it to their alternative image, so I can't use the conventional onerror method.
This method works well if the server throws a 404 page in response.
<html>
<body>
<div><img src="http://stackoverflow.com/image.jpg" alt="image" onerror="this.style.display='none'"/></div>
</body>
</html>
but in conditions like, where image URL is: http://tinypic.com/someimage.jpg
the above method won't work. because this is a 302 response, which redirects it to some other image. I want to hide that as well.
Is that possible to somehow use http response as condition to display/hide image.
Here are http headers of the above image:
$ curl -I http://tinypic.com/notfound.jpg
HTTP/1.1 302 Found
Server: Apache
Location: http://tinypic.com/images/404.gif
Expires: Fri, 21 Mar 2014 21:33:07 GMT
Cache-Control: max-age=300
Content-Type: text/html; charset=iso-8859-1
Content-Length: 217
Accept-Ranges: bytes
Date: Fri, 21 Mar 2014 21:28:07 GMT
X-Varnish: 1535787681
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Varnish-Server: den2tpv01
X-Cache: MISS
Now, I think HTTP/1.1 302 Found can be used in someway. any suggestions?
Here you go, the simple solution:
<img src="www.google.com/noanyimage.png" width="200px" height ="200px" onerror="this.src ='';" />
Here is the solution using php...
<?PHP
$url = "http://tinypic.com/notfound.jpg"; //Image link here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
$status_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($status_code==302 or $status_code==301 or $status_code==404){
echo "no image found";
}
else {
echo '<img src="'.$url.'" />';
}
curl_close($ch);
?>
Related
Everything seems to be working as I do not get any error but I get garbage code instead of the image itself. The code is very simple in the controller:
// get image & resize
$img = ImgMgr::make('http://pathToImage.jpg')->resize(200,100);
// send HTTP header and output image data
echo $img->response('jpg', 70);
Then I get : HTTP/1.0 200 OK Cache-Control: no-cache, private Content-Length: 2900 Content-Type: image/jpeg Date: Wed, 21 Jul 2021 16:05:21 GMT ����JFIF``��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), quality = 70 ��C #%$""!&+7/&)4)!"0A149;>>>%.DIC;��C ;("(;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;��dd"��
What am I missing?
Here is the solution...
$img = ImgMgr::make('http://pathToImage.jpg')->resize(200,100);
$img->response('jpg', 70);
$type = 'png';
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($img);
<img src="{!! $base64 !!}">
I'm trying to implement a download link for users to download a record in .txt file.
Firstly it was a simple <a> tag
download
I could download the file from server in .txt format. But I found that it does not bring Auth header. So I tried to use a http get method to fetch it.
service.js
getCdrFile(url) {
return this.http.get<any>(`${this.env.service}/service/api/downloadFile?` + url);
}
component.js
downloadFile(url) {
this.service.getCdrFile(url).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
}
);
}
I can successfully call the API with auth head, then I got nothing happened after I clicked the download button but the txt data displayed in the "response" tab in Chrome developer tool. Also, I got nothing from console.log(data); inside my http request.
Is there anyway I can download the file? thanks!
(and here is my response detail)
# GENERAL
Request URL: http://localhost:8080/service/api/downloadFile?fileType=daily&trsDate=20190918
Request Method: GET
Status Code: 200
Remote Address: 127.0.0.1:8080
Referrer Policy: no-referrer-when-downgrade
# RESPONSE HEADER
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Disposition: attachment; filename=20190918.txt
Content-Type: application/json
Date: Wed, 02 Oct 2019 03:51:01 GMT
Expires: 0
Pragma: no-cache
Server: nginx/1.15.2
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
You can create a Blob response and create a blob url with it and download on the fly.
Service:
Modify your service to receive a blob response
getImage() {
return this.httpClient.get(
your_image_link,
{
responseType: 'blob', // <-- add this
headers: {your_headers}
}
);
}
Component:
On click of your link on the page call your service to get the response blob of your file
Create a blob url URL.createObjectUrl method
Create a dummy anchor element assign the blob url and name of the file to download
Trigger a click event on the anchor element
remove the blob url from browser using URL.revokeObjectUrl method
downloadImage() {
this.service.getImage().subscribe(img => {
const url = URL.createObjectURL(img);
const a = document.createElement('a');
a.download = "filename.txt";
a.href = url;
a.click();
URL.revokeObjectURL(url);
});
}
Stackblitz: https://stackblitz.com/edit/angular-kp3saz
You have two ways to download the file from the server.
1:-) Ater getting a response from HTTP call to create base64 and create a dummy anchor tag and download.
2:-) Modify backend response as download response.
I'm using a react app running on localhost:3000 which makes ajax requests to our website. We recently switched our authentification system from using WordPress authentification to https://github.com/delight-im/PHP-Auth.
Since then, using the same settings inside ajax and on our web server, our authentification cookies are not sent cross domain. However, it's working when requesting them from the same domain.
Our request:
fetchLoginStatus = () => {
const ajax = new XMLHttpRequest();
ajax.withCredentials = true;
ajax.open("POST", "https://our-website.com/src/php/checkLoggedIn.php");
ajax.onload = () => {
const response = JSON.parse(ajax.responseText);
};
ajax.send();
};
Our request headers (from localhost:3000):
:authority: my-website.com
:method: POST
:path: /src/php/checkLoggedIn.php
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
content-length: 0
cookie: plesk-items-per-page; plesk-sort-field, phpMyAdmin; databases-active-list-state-collapsed; plesk-list-type; io=R_dL3fjUEYe64ykHAAAp; isAsyncProgressBarCollapsed=true; PLESKSESSID; plesk-sort-dir;
origin: https://localhost:3000
referer: https://localhost:3000/
Our response headers (we are running an nginx server):
access-control-allow-credentials: true
access-control-allow-headers: origin, x-requested-with, content-type
access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS access-`
control-allow-origin: https://localhost:3000
cache-control: no-store, no-cache, must-revalidate
content-encoding: br
content-type: text/html; charset=UTF-8
date: Sun, 10 Mar 2019 15:26:08 GMT
expires: Thu, 19 Nov 1981 08:52:00 GMT pragma:
no-cache server: nginx
set-cookie: PHPSESSID=someId;
path=/; SameSite=Lax status: 200
vary: Accept-Encoding
x-powered-by: PleskLin`
When I don't send the request cross-domain PHPSESSID is inside the cookies of my request headers. However when I send the request from localhost:3000 it's not there.
Does somebody know how I can send the PHPSESSID from localhost too?
Thanks for any help in advance!
Asked the same question inside the github repository and the owner solved it.
https://github.com/delight-im/PHP-Auth/issues/154
Solution:
vendor/delight-im/auth/src/UserManager.php
Replace Session::regenerate(true); with Session::regenerate(true, null);
vendor/delight-im/auth/src/Auth.php
Replace #Session::start(); with #Session::start(null);
Replace Session::regenerate(true); with Session::regenerate(true, null);
After $cookie->setSecureOnly($params['secure']); append $cookie-
>setSameSiteRestriction(null); in all three (!) occurrences
I'm creating a SSL Connection using PyOpenSSL and the trying to make a GET call but i run into :
`'HTTP/1.1 400 Bad Request\r\nDate: Fri, 14 Jul 2017 20:04:51 GMT\r\nServer: Apache/2.4.18 (Ubuntu)\r\nContent-Length: 305\r\nConnection: close\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n'
(Pdb) c
.. info: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at ecdhe-server Port 443</address>
</body></html>`
The Code i have is as follows :
1) I create SSL Connection as follows :
client = socket()
if self._proxy:
client.connect((proxy, 8080))
else:
client.connect((host_name, port))
context = Context(self._ssl_version)
if self._ciphers:
context.set_cipher_list(self._ciphers)
ssl_connection = Connection(context, client)
if self._extension=='SNI':
ssl_connection.set_tlsext_host_name(host_name)
ssl_connection.set_connect_state()
ssl_connection.do_handshake()
self._session_ref = ssl_connection.get_session()
self._ssl_connection = ssl_connection
And then call the get() function which is as follows:
def get(self, http_version='1.0'):
#self._ssl_connection.sendall("GET / HTTP/1.1\r\n\r\n")
self._ssl_connection.sendall("GET / HTTP/1.0\r\n\r\n")
response_contents = self._ssl_connection.recv(4096)
return response_contents
I tried all combinations of sendall and send(also i think) but i run into :
.. info: HTTP/1.1 400 Bad Request
Date: Fri, 14 Jul 2017 20:19:13 GMT
Server: Apache/2.4.18 (Ubuntu)
Content-Length: 305
Connection: close
Content-Type: text/html; charset=iso-8859-1
I would appreciate if some one would help out in resolving the issue.
I use Laravel 5.1.
A jQuery ajax call is made like that:
$('#export_selected').click(function(){
var checked = $('.select_rows:checked');
var ids = [];
$.each(checked, function(index, value){
ids.push(value.id);
})
$.ajax({
method : "POST",
url : "{{URL::to('/spot/exportTable')}}",
data : {ids:ids}
});
});
And then the php method is defined that way:
public function exportTable(Request $req) {
$spots = array_flatten($req->all());
$res = Spot::whereIn('id', $spots)->get();
Excel::create('Spots', function($excel) use($res) {
$excel->setTitle('Title goes here');
$excel->setCreator('Creator Goes Here')->setCompany('Company Goes Here');
$excel->sheet('Excel sheet', function($sheet) use($res) {
$sheet->setOrientation('landscape');
$sheet->fromArray($res);
});
})->store('csv', storage_path('/exports', true));
$file = base_path() . '/storage/exports/Spots.csv';
$headers = ['Content-Type: application/csv', 'Content Description: File Transfer', 'Cache-Control: must-revalidate, post-check=0, pre-check=0'];
return response()->download($file, 'Spots.csv' , $headers);
}
Chrome developer console prints the results as raw lines.
The file is successfully exported and created in the disk.
The path to file is correct.
But the download is never started.
Echoing the response gives:
HTTP/1.0 200 OK
0: Content-Type: application/csv
Cache-Control: public
Content-Disposition: attachment; filename="Spots.csv"
Date: Mon, 26 Oct 2015 16:08:26 GMT
Last-Modified: Mon, 26 Oct 2015 16:08:26 GMT
1: Content-Description: File Transfer
2: Cache-Control: must-revalidate, post-check=0, pre-check=0
I put the answer here for everybody having the same issue.
#manix figured it out: I'm trying to download via Ajax, which needs to be done in another way, not the way I wrote my code